@zyfai/sdk 1.5.0 → 1.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -61,6 +61,7 @@ __export(index_exports, {
61
61
  ZyfaiSDK: () => ZyfaiSDK,
62
62
  buildV1ChainSessions: () => buildV1ChainSessions,
63
63
  createBankrProvider: () => createBankrProvider,
64
+ createSafeOwnerProvider: () => createSafeOwnerProvider,
64
65
  decodeUserOperationCalls: () => decodeUserOperationCalls,
65
66
  getChainConfig: () => getChainConfig,
66
67
  getDataApiBaseUrl: () => getDataApiBaseUrl,
@@ -915,7 +916,7 @@ function isMainnetMinPortfolioExempt(chainId, ...addresses) {
915
916
 
916
917
  // src/core/ZyfaiSDK.ts
917
918
  var import_accounts2 = require("viem/accounts");
918
- var import_viem6 = require("viem");
919
+ var import_viem8 = require("viem");
919
920
  var import_relay_sdk2 = require("@relayprotocol/relay-sdk");
920
921
 
921
922
  // src/config/chains.ts
@@ -1400,9 +1401,9 @@ function getManagedAssets() {
1400
1401
  }
1401
1402
 
1402
1403
  // src/utils/safe-account.ts
1403
- var import_module_sdk = require("@rhinestone/module-sdk");
1404
+ var import_module_sdk2 = require("@rhinestone/module-sdk");
1404
1405
  var import_accounts = require("permissionless/accounts");
1405
- var import_viem5 = require("viem");
1406
+ var import_viem6 = require("viem");
1406
1407
  var import_account_abstraction = require("viem/account-abstraction");
1407
1408
 
1408
1409
  // src/config/modules.ts
@@ -1412,6 +1413,10 @@ var INTENT_EXECUTOR = "0x00000000005aD9ce1f5035FD62CA96CEf16AdAAF";
1412
1413
  var PROXY_EXECUTOR = "0xF659d30D4EB88B06A909F20839D8959Bd77d8790";
1413
1414
  var INTENT_SMART_SESSIONS = "0xad568b3f825a8d5ffc06dd3253526b64d810ae89";
1414
1415
  var OWNABLE_VALIDATOR = "0x000000000013fdB5234E4E3162a810F54d9f7E98";
1416
+ var OWNABLE_VALIDATOR_DEPLOYMENTS = [
1417
+ "0x2483DA3A338895199E5e538530213157e931Bf06",
1418
+ OWNABLE_VALIDATOR
1419
+ ];
1415
1420
  var SAFE_7579_ADDRESS = "0x7579EE8307284F293B1927136486880611F20002";
1416
1421
  var ERC7579_LAUNCHPAD_ADDRESS = "0x7579011aB74c46090561ea277Ba79D510c6C00ff";
1417
1422
  var POOL_MODULE_ADDRESSES = [
@@ -1423,6 +1428,139 @@ var POOL_MODULE_ADDRESSES = [
1423
1428
  OWNABLE_VALIDATOR
1424
1429
  ];
1425
1430
 
1431
+ // src/utils/safe-signature.ts
1432
+ var import_module_sdk = require("@rhinestone/module-sdk");
1433
+ var import_viem5 = require("viem");
1434
+ var EMPTY_DATA = "0x";
1435
+ var SIGNATURE_LENGTH_BYTES = 65;
1436
+ function safeSigStaticPart(sig, dynamicOffset) {
1437
+ if (sig.isContractSignature) {
1438
+ return `${sig.signer.slice(2).padStart(64, "0")}${dynamicOffset ?? ""}00`;
1439
+ }
1440
+ return sig.data.slice(2);
1441
+ }
1442
+ function safeSigDynamicPart(sig) {
1443
+ if (!sig.isContractSignature) return "";
1444
+ const dynamicPartLength = (sig.data.slice(2).length / 2).toString(16).padStart(64, "0");
1445
+ return `${dynamicPartLength}${sig.data.slice(2)}`;
1446
+ }
1447
+ function buildSafeSignatureBytes(signatures) {
1448
+ const sorted = [...signatures].sort(
1449
+ (left, right) => left.signer.toLowerCase().localeCompare(right.signer.toLowerCase())
1450
+ );
1451
+ let signatureBytes = EMPTY_DATA.slice(2);
1452
+ let dynamicBytes = "";
1453
+ for (const signature of sorted) {
1454
+ if (signature.isContractSignature) {
1455
+ const dynamicPartPosition = (sorted.length * SIGNATURE_LENGTH_BYTES + dynamicBytes.length / 2).toString(16).padStart(64, "0");
1456
+ signatureBytes += safeSigStaticPart(signature, dynamicPartPosition);
1457
+ dynamicBytes += safeSigDynamicPart(signature);
1458
+ } else {
1459
+ signatureBytes += signature.data.slice(2);
1460
+ }
1461
+ }
1462
+ return `0x${signatureBytes}${dynamicBytes}`;
1463
+ }
1464
+ function wrapNestedSafeOwnerSignature(parentSafe, rawSignature, validator) {
1465
+ const normalizedParent = (0, import_viem5.getAddress)(parentSafe);
1466
+ const normalizedValidator = (0, import_viem5.getAddress)(validator);
1467
+ const inner = rawSignature.toLowerCase().startsWith(normalizedValidator.toLowerCase()) ? `0x${rawSignature.slice(42)}` : rawSignature;
1468
+ const safeSignature = {
1469
+ signer: normalizedParent,
1470
+ data: inner,
1471
+ isContractSignature: true
1472
+ };
1473
+ return (0, import_viem5.concat)([
1474
+ normalizedValidator,
1475
+ buildSafeSignatureBytes([safeSignature])
1476
+ ]);
1477
+ }
1478
+ function buildMultiChainSessionTypedData(params) {
1479
+ const smartSession = params.smartSessionAddress ?? import_module_sdk.SMART_SESSIONS_ADDRESS;
1480
+ return {
1481
+ domain: {
1482
+ name: "SmartSession",
1483
+ version: "1"
1484
+ },
1485
+ types: {
1486
+ PolicyData: [
1487
+ { name: "policy", type: "address" },
1488
+ { name: "initData", type: "bytes" }
1489
+ ],
1490
+ ActionData: [
1491
+ { name: "actionTargetSelector", type: "bytes4" },
1492
+ { name: "actionTarget", type: "address" },
1493
+ { name: "actionPolicies", type: "PolicyData[]" }
1494
+ ],
1495
+ ERC7739Context: [
1496
+ { name: "appDomainSeparator", type: "bytes32" },
1497
+ { name: "contentName", type: "string[]" }
1498
+ ],
1499
+ ERC7739Data: [
1500
+ { name: "allowedERC7739Content", type: "ERC7739Context[]" },
1501
+ { name: "erc1271Policies", type: "PolicyData[]" }
1502
+ ],
1503
+ SignedPermissions: [
1504
+ { name: "permitGenericPolicy", type: "bool" },
1505
+ { name: "permitAdminAccess", type: "bool" },
1506
+ { name: "ignoreSecurityAttestations", type: "bool" },
1507
+ { name: "permitERC4337Paymaster", type: "bool" },
1508
+ { name: "userOpPolicies", type: "PolicyData[]" },
1509
+ { name: "erc7739Policies", type: "ERC7739Data" },
1510
+ { name: "actions", type: "ActionData[]" }
1511
+ ],
1512
+ SignedSession: [
1513
+ { name: "account", type: "address" },
1514
+ { name: "permissions", type: "SignedPermissions" },
1515
+ { name: "sessionValidator", type: "address" },
1516
+ { name: "sessionValidatorInitData", type: "bytes" },
1517
+ { name: "salt", type: "bytes32" },
1518
+ { name: "smartSession", type: "address" },
1519
+ { name: "nonce", type: "uint256" }
1520
+ ],
1521
+ ChainSession: [
1522
+ { name: "chainId", type: "uint64" },
1523
+ { name: "session", type: "SignedSession" }
1524
+ ],
1525
+ MultiChainSession: [
1526
+ { name: "sessionsAndChainIds", type: "ChainSession[]" }
1527
+ ]
1528
+ },
1529
+ primaryType: "MultiChainSession",
1530
+ message: {
1531
+ sessionsAndChainIds: params.sessions.map((session, index) => ({
1532
+ chainId: BigInt(session.chainId),
1533
+ session: {
1534
+ account: params.childSafeAddress,
1535
+ permissions: {
1536
+ permitGenericPolicy: params.permitGenericPolicy,
1537
+ permitAdminAccess: false,
1538
+ ignoreSecurityAttestations: true,
1539
+ permitERC4337Paymaster: session.permitERC4337Paymaster,
1540
+ userOpPolicies: session.userOpPolicies,
1541
+ erc7739Policies: session.erc7739Policies,
1542
+ actions: session.actions
1543
+ },
1544
+ sessionValidator: session.sessionValidator,
1545
+ sessionValidatorInitData: session.sessionValidatorInitData,
1546
+ salt: session.salt,
1547
+ smartSession,
1548
+ nonce: params.sessionNonces[index]
1549
+ }
1550
+ }))
1551
+ }
1552
+ };
1553
+ }
1554
+ async function signMultiChainSessionTypedData(walletClient, typedData) {
1555
+ if (!walletClient.account) {
1556
+ throw new Error("Wallet not connected. Please connect your wallet first.");
1557
+ }
1558
+ return walletClient.signMessage({
1559
+ account: walletClient.account,
1560
+ message: { raw: (0, import_viem5.hashTypedData)(typedData) }
1561
+ });
1562
+ }
1563
+
1426
1564
  // src/utils/safe-account.ts
1427
1565
  var SAFE_7579_ADDRESS2 = "0x7579EE8307284F293B1927136486880611F20002";
1428
1566
  var ERC7579_LAUNCHPAD_ADDRESS2 = "0x7579011aB74c46090561ea277Ba79D510c6C00ff";
@@ -1432,12 +1570,12 @@ var getSafeAccount = async (config) => {
1432
1570
  if (!safeOwnerAddress) {
1433
1571
  throw new Error("Safe owner address is required");
1434
1572
  }
1435
- const formattedOwnerAddress = (0, import_viem5.getAddress)(safeOwnerAddress);
1436
- const ownableValidator = (0, import_module_sdk.getOwnableValidator)({
1573
+ const formattedOwnerAddress = (0, import_viem6.getAddress)(safeOwnerAddress);
1574
+ const ownableValidator = (0, import_module_sdk2.getOwnableValidator)({
1437
1575
  owners: [formattedOwnerAddress],
1438
1576
  threshold: 1
1439
1577
  });
1440
- const saltHex = (0, import_viem5.fromHex)((0, import_viem5.toHex)(ACCOUNT_SALT), "bigint");
1578
+ const saltHex = (0, import_viem6.fromHex)((0, import_viem6.toHex)(ACCOUNT_SALT), "bigint");
1441
1579
  const tempOwner = {
1442
1580
  address: formattedOwnerAddress,
1443
1581
  type: "json-rpc"
@@ -1452,7 +1590,7 @@ var getSafeAccount = async (config) => {
1452
1590
  },
1453
1591
  safe4337ModuleAddress: SAFE_7579_ADDRESS2,
1454
1592
  erc7579LaunchpadAddress: ERC7579_LAUNCHPAD_ADDRESS2,
1455
- attesters: [import_module_sdk.RHINESTONE_ATTESTER_ADDRESS],
1593
+ attesters: [import_module_sdk2.RHINESTONE_ATTESTER_ADDRESS],
1456
1594
  attestersThreshold: 1,
1457
1595
  validators: [
1458
1596
  {
@@ -1484,12 +1622,12 @@ var isSafeDeployed = async (address, publicClient) => {
1484
1622
  }
1485
1623
  };
1486
1624
  var isOwnableValidatorOwner = async (safeAddress, userAddress, publicClient) => {
1487
- const normalizedUser = (0, import_viem5.getAddress)(userAddress);
1488
- const normalizedSafe = (0, import_viem5.getAddress)(safeAddress);
1625
+ const normalizedUser = (0, import_viem6.getAddress)(userAddress);
1626
+ const normalizedSafe = (0, import_viem6.getAddress)(safeAddress);
1489
1627
  const validatorAddresses = Array.from(
1490
1628
  /* @__PURE__ */ new Set([
1491
- (0, import_viem5.getAddress)(OWNABLE_VALIDATOR),
1492
- (0, import_viem5.getAddress)(import_module_sdk.OWNABLE_VALIDATOR_ADDRESS)
1629
+ (0, import_viem6.getAddress)(OWNABLE_VALIDATOR),
1630
+ (0, import_viem6.getAddress)(import_module_sdk2.OWNABLE_VALIDATOR_ADDRESS)
1493
1631
  ])
1494
1632
  );
1495
1633
  for (const validatorAddress of validatorAddresses) {
@@ -1500,7 +1638,7 @@ var isOwnableValidatorOwner = async (safeAddress, userAddress, publicClient) =>
1500
1638
  functionName: "getOwners",
1501
1639
  args: [normalizedSafe]
1502
1640
  });
1503
- if (owners.some((owner) => (0, import_viem5.getAddress)(owner) === normalizedUser)) {
1641
+ if (owners.some((owner) => (0, import_viem6.getAddress)(owner) === normalizedUser)) {
1504
1642
  return true;
1505
1643
  }
1506
1644
  } catch {
@@ -1508,13 +1646,12 @@ var isOwnableValidatorOwner = async (safeAddress, userAddress, publicClient) =>
1508
1646
  }
1509
1647
  return false;
1510
1648
  };
1649
+ var isEip7702Delegation = (code) => !!code && code.toLowerCase().startsWith("0xef0100");
1650
+ var hasPersistentContractCode = (code) => !!code && code !== "0x" && !isEip7702Delegation(code);
1511
1651
  var getAccountType = async (address, publicClient) => {
1512
1652
  try {
1513
1653
  const code = await publicClient.getCode({ address });
1514
- if (!code || code === "0x" || code.length === 2) {
1515
- return "EOA";
1516
- }
1517
- if (code.startsWith("0xef01")) {
1654
+ if (!code || code === "0x" || code.length === 2 || isEip7702Delegation(code)) {
1518
1655
  return "EOA";
1519
1656
  }
1520
1657
  try {
@@ -1544,18 +1681,33 @@ var getAccountType = async (address, publicClient) => {
1544
1681
  };
1545
1682
  var deploySafeAccount = async (config) => {
1546
1683
  try {
1547
- const { owner, httpClient, chainId, strategy = "safe_strategy" } = config;
1684
+ const {
1685
+ owner,
1686
+ httpClient,
1687
+ chainId,
1688
+ publicClient,
1689
+ safeOwnerAddress,
1690
+ strategy
1691
+ } = config;
1548
1692
  if (!owner || !owner.account) {
1549
1693
  throw new Error(
1550
1694
  "Wallet not connected. Please connect your wallet first."
1551
1695
  );
1552
1696
  }
1553
1697
  console.log("strategy", strategy);
1698
+ const strategyBody = strategy ? { strategy } : {};
1554
1699
  const prepareResponse = await httpClient.post(
1555
1700
  `${ENDPOINTS.SAFE_DEPLOY}?chainId=${chainId}`,
1556
- { strategy }
1701
+ strategyBody
1557
1702
  );
1558
1703
  console.log("prepareResponse", prepareResponse);
1704
+ if (prepareResponse.success && !prepareResponse.userOpHashToSign) {
1705
+ return {
1706
+ safeAddress: prepareResponse.safeAddress || "0x",
1707
+ txHash: "0x0",
1708
+ isDeployed: true
1709
+ };
1710
+ }
1559
1711
  if (!prepareResponse.userOpHashToSign) {
1560
1712
  throw new Error(
1561
1713
  "Backend did not return userOpHashToSign. Response: " + JSON.stringify(prepareResponse)
@@ -1566,9 +1718,29 @@ var deploySafeAccount = async (config) => {
1566
1718
  account: owner.account,
1567
1719
  message: { raw: userOpHashToSign }
1568
1720
  });
1721
+ const ownerAddress = (0, import_viem6.getAddress)(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.`
1725
+ );
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;
1569
1741
  const deployResponse = await httpClient.post(
1570
1742
  `${ENDPOINTS.SAFE_DEPLOY}?chainId=${chainId}`,
1571
- { userOpSignature, strategy }
1743
+ { userOpSignature: signatureToSubmit, ...strategyBody }
1572
1744
  );
1573
1745
  if (!deployResponse.success) {
1574
1746
  throw new Error(
@@ -1587,12 +1759,24 @@ var deploySafeAccount = async (config) => {
1587
1759
  }
1588
1760
  };
1589
1761
  var signSessionKey = async (config, sessions, allPublicClients, signingParams) => {
1590
- const { owner, publicClient } = config;
1762
+ const { owner, publicClient, safeOwnerAddress } = config;
1591
1763
  if (!owner || !owner.account) {
1592
1764
  throw new Error("Wallet not connected. Please connect your wallet first.");
1593
1765
  }
1766
+ const ownerAccountType = await getAccountType(
1767
+ safeOwnerAddress,
1768
+ publicClient
1769
+ );
1770
+ if (ownerAccountType === "Safe") {
1771
+ return signNestedOwnerSessionKey(
1772
+ config,
1773
+ sessions,
1774
+ allPublicClients,
1775
+ signingParams
1776
+ );
1777
+ }
1594
1778
  const safeAccount = await getSafeAccount(config);
1595
- const account = (0, import_module_sdk.getAccount)({
1779
+ const account = (0, import_module_sdk2.getAccount)({
1596
1780
  address: safeAccount.address,
1597
1781
  type: "safe"
1598
1782
  });
@@ -1601,16 +1785,16 @@ var signSessionKey = async (config, sessions, allPublicClients, signingParams) =
1601
1785
  sessions.map((session) => {
1602
1786
  const sessionChainId = Number(session.chainId);
1603
1787
  const client = clients.find((c) => c.chain?.id === sessionChainId) || publicClient;
1604
- return (0, import_module_sdk.getSessionNonce)({
1788
+ return (0, import_module_sdk2.getSessionNonce)({
1605
1789
  client,
1606
1790
  account,
1607
- permissionId: (0, import_module_sdk.getPermissionId)({
1791
+ permissionId: (0, import_module_sdk2.getPermissionId)({
1608
1792
  session
1609
1793
  })
1610
1794
  });
1611
1795
  })
1612
1796
  );
1613
- const sessionDetails = await (0, import_module_sdk.getEnableSessionDetails)({
1797
+ const sessionDetails = await (0, import_module_sdk2.getEnableSessionDetails)({
1614
1798
  sessions,
1615
1799
  account,
1616
1800
  clients,
@@ -1629,6 +1813,217 @@ var signSessionKey = async (config, sessions, allPublicClients, signingParams) =
1629
1813
  sessionNonces
1630
1814
  };
1631
1815
  };
1816
+ var IS_MODULE_INSTALLED_ABI = [
1817
+ {
1818
+ type: "function",
1819
+ name: "isModuleInstalled",
1820
+ stateMutability: "view",
1821
+ inputs: [
1822
+ { name: "moduleTypeId", type: "uint256" },
1823
+ { name: "module", type: "address" },
1824
+ { name: "additionalContext", type: "bytes" }
1825
+ ],
1826
+ outputs: [{ type: "bool" }]
1827
+ }
1828
+ ];
1829
+ async function resolveOwnerValidator(publicClient, childSafeAddress) {
1830
+ for (const candidate of OWNABLE_VALIDATOR_DEPLOYMENTS) {
1831
+ const installed = await publicClient.readContract({
1832
+ address: childSafeAddress,
1833
+ abi: IS_MODULE_INSTALLED_ABI,
1834
+ functionName: "isModuleInstalled",
1835
+ args: [1n, candidate, "0x"]
1836
+ }).catch(() => false);
1837
+ if (installed) return candidate;
1838
+ }
1839
+ throw new Error(
1840
+ `No known OwnableValidator is installed on Safe ${childSafeAddress}. A nested Safe owner signature cannot be routed to a validator.`
1841
+ );
1842
+ }
1843
+ async function signNestedOwnerSessionKey(config, sessions, allPublicClients, signingParams) {
1844
+ const { owner, publicClient, safeOwnerAddress } = config;
1845
+ const derivedChild = (await getSafeAccount(config)).address;
1846
+ const childSafeAddress = (0, import_viem6.getAddress)(
1847
+ config.childSafeAddress ?? derivedChild
1848
+ );
1849
+ const account = (0, import_module_sdk2.getAccount)({
1850
+ address: childSafeAddress,
1851
+ type: "safe"
1852
+ });
1853
+ const clients = allPublicClients || [publicClient];
1854
+ const sessionNonces = await Promise.all(
1855
+ sessions.map((session) => {
1856
+ const sessionChainId = Number(session.chainId);
1857
+ const client = clients.find((c) => c.chain?.id === sessionChainId) || publicClient;
1858
+ return (0, import_module_sdk2.getSessionNonce)({
1859
+ client,
1860
+ account,
1861
+ permissionId: (0, import_module_sdk2.getPermissionId)({
1862
+ session
1863
+ })
1864
+ });
1865
+ })
1866
+ );
1867
+ const permitGenericPolicy = signingParams?.permitGenericPolicy ?? true;
1868
+ const typedData = buildMultiChainSessionTypedData({
1869
+ childSafeAddress,
1870
+ sessions,
1871
+ sessionNonces,
1872
+ permitGenericPolicy
1873
+ });
1874
+ const ownerValidator = await resolveOwnerValidator(
1875
+ publicClient,
1876
+ childSafeAddress
1877
+ );
1878
+ const rawSignature = await signMultiChainSessionTypedData(owner, typedData);
1879
+ const signature = wrapNestedSafeOwnerSignature(
1880
+ safeOwnerAddress,
1881
+ rawSignature,
1882
+ ownerValidator
1883
+ );
1884
+ return {
1885
+ signature,
1886
+ sessionNonces
1887
+ };
1888
+ }
1889
+
1890
+ // src/utils/nested-safe-deposit.ts
1891
+ var import_viem7 = require("viem");
1892
+ var NESTED_SAFE_DEPOSIT_TIMEOUT_MS = 20 * 60 * 1e3;
1893
+ var NESTED_SAFE_DEPOSIT_POLL_MS = 1e4;
1894
+ var NESTED_SAFE_RESUME_WINDOW_MS = 24 * 60 * 60 * 1e3;
1895
+ var SAFE_TX_SERVICE_NETWORK = {
1896
+ 1: "eth",
1897
+ 42161: "arb1",
1898
+ 8453: "base",
1899
+ 10: "oeth",
1900
+ 59144: "linea",
1901
+ 146: "sonic",
1902
+ 9745: "plasma"
1903
+ };
1904
+ function safeTxServiceNetworkName(chainId) {
1905
+ return SAFE_TX_SERVICE_NETWORK[chainId];
1906
+ }
1907
+ function safeTxServiceNetworkNameOrThrow(chainId) {
1908
+ const networkName = safeTxServiceNetworkName(chainId);
1909
+ if (!networkName) {
1910
+ throw new Error(
1911
+ `Chain ${chainId} has no Safe Transaction Service. A nested Safe deposit cannot be tracked there.`
1912
+ );
1913
+ }
1914
+ return networkName;
1915
+ }
1916
+ async function assertParentSafeDeployedOnChain(parentSafe, publicClient, chainId) {
1917
+ const code = await publicClient.getCode({ address: (0, import_viem7.getAddress)(parentSafe) });
1918
+ if (!code || code === "0x") {
1919
+ throw new Error(
1920
+ `Parent Safe ${parentSafe} has no code on chain ${chainId}. Choose a chain where the Safe is deployed.`
1921
+ );
1922
+ }
1923
+ }
1924
+ function sameAddress(left, right) {
1925
+ if (!left || !right) return false;
1926
+ try {
1927
+ return (0, import_viem7.getAddress)(left) === (0, import_viem7.getAddress)(right);
1928
+ } catch {
1929
+ return false;
1930
+ }
1931
+ }
1932
+ function transferMatches(transaction, params) {
1933
+ if (!sameAddress(transaction.to, params.tokenAddress)) return false;
1934
+ if (transaction.isSuccessful === false) return false;
1935
+ const decoded = transaction.dataDecoded;
1936
+ if (decoded?.method?.toLowerCase() !== "transfer") return false;
1937
+ const parameters = decoded.parameters;
1938
+ if (!parameters) return false;
1939
+ const destination = parameters.find(
1940
+ (p) => (p.name === "to" || p.name === "dst" || p.name === "_to") && p.type === "address"
1941
+ );
1942
+ if (!sameAddress(destination?.value, params.childSafe)) return false;
1943
+ if (params.amount === void 0) return true;
1944
+ const valueParam = parameters.find(
1945
+ (p) => (p.name === "value" || p.name === "amount" || p.name === "_value" || p.name === "wad") && p.type.startsWith("uint")
1946
+ );
1947
+ if (!valueParam) return false;
1948
+ try {
1949
+ return BigInt(valueParam.value) === params.amount;
1950
+ } catch {
1951
+ return false;
1952
+ }
1953
+ }
1954
+ function isWithinWindow(transaction, since) {
1955
+ if (!since) return true;
1956
+ const stamp = transaction.executionDate ?? transaction.submissionDate;
1957
+ if (!stamp) return false;
1958
+ const at = Date.parse(stamp);
1959
+ return Number.isFinite(at) && at >= since.getTime();
1960
+ }
1961
+ async function findSafeTransferByHash(params) {
1962
+ const networkName = safeTxServiceNetworkNameOrThrow(params.chainId);
1963
+ const url = `https://api.safe.global/tx-service/${networkName}/api/v2/multisig-transactions/${params.safeTxHash}/`;
1964
+ const response = await fetch(url);
1965
+ if (!response.ok) return null;
1966
+ const transaction = await response.json();
1967
+ if (!transaction.safeTxHash) return null;
1968
+ if (transaction.isSuccessful === false) {
1969
+ throw new Error(
1970
+ `Safe transaction ${params.safeTxHash} on chain ${params.chainId} reverted on-chain. No deposit was registered.`
1971
+ );
1972
+ }
1973
+ return {
1974
+ safeTxHash: transaction.safeTxHash,
1975
+ transactionHash: transaction.transactionHash ?? null,
1976
+ isExecuted: transaction.isExecuted === true && !!transaction.transactionHash
1977
+ };
1978
+ }
1979
+ async function findSafeTransferProposal(params) {
1980
+ const networkName = safeTxServiceNetworkNameOrThrow(params.chainId);
1981
+ const url = `https://api.safe.global/tx-service/${networkName}/api/v2/safes/${(0, import_viem7.getAddress)(
1982
+ params.parentSafe
1983
+ )}/multisig-transactions/?ordering=-nonce`;
1984
+ const response = await fetch(url);
1985
+ if (!response.ok) return null;
1986
+ const body = await response.json();
1987
+ const match = (body.results ?? []).find(
1988
+ (transaction) => !!transaction.safeTxHash && isWithinWindow(transaction, params.since) && transferMatches(transaction, {
1989
+ childSafe: params.childSafe,
1990
+ tokenAddress: params.tokenAddress,
1991
+ amount: params.amount
1992
+ })
1993
+ );
1994
+ if (!match) return null;
1995
+ return {
1996
+ safeTxHash: match.safeTxHash,
1997
+ transactionHash: match.transactionHash ?? null,
1998
+ isExecuted: match.isExecuted === true && !!match.transactionHash
1999
+ };
2000
+ }
2001
+ async function waitForSafeTransferExecution(params) {
2002
+ safeTxServiceNetworkNameOrThrow(params.chainId);
2003
+ const timeoutMs = params.timeoutMs ?? NESTED_SAFE_DEPOSIT_TIMEOUT_MS;
2004
+ const pollMs = params.pollMs ?? NESTED_SAFE_DEPOSIT_POLL_MS;
2005
+ const started = Date.now();
2006
+ do {
2007
+ const proposal = params.safeTxHash ? await findSafeTransferByHash({
2008
+ chainId: params.chainId,
2009
+ safeTxHash: params.safeTxHash
2010
+ }) : await findSafeTransferProposal({
2011
+ parentSafe: params.parentSafe,
2012
+ childSafe: params.childSafe,
2013
+ chainId: params.chainId,
2014
+ tokenAddress: params.tokenAddress,
2015
+ amount: params.amount,
2016
+ since: params.since
2017
+ });
2018
+ if (proposal?.isExecuted && proposal.transactionHash) {
2019
+ return proposal.transactionHash;
2020
+ }
2021
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
2022
+ } while (Date.now() - started < timeoutMs);
2023
+ throw new Error(
2024
+ `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.`
2025
+ );
2026
+ }
1632
2027
 
1633
2028
  // src/utils/strategy.ts
1634
2029
  var PUBLIC_STRATEGIES = `"conservative", "aggressive" or "yieldmaxxing"`;
@@ -2296,7 +2691,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2296
2691
  }
2297
2692
  this.httpClient.setAuthToken(session.accessToken);
2298
2693
  this.authenticatedUserId = session.userId ?? "bearer-session";
2299
- this.sessionEoa = session.eoa ? (0, import_viem6.getAddress)(session.eoa) : null;
2694
+ this.sessionEoa = session.eoa ? (0, import_viem8.getAddress)(session.eoa) : null;
2300
2695
  this.sessionChannel = session.channel;
2301
2696
  this.isPredeployed = false;
2302
2697
  this.predeployedResolved = false;
@@ -2345,19 +2740,28 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2345
2740
  this.isPredeployed = loginResponse.predeployed || false;
2346
2741
  this.predeployedResolved = true;
2347
2742
  this.connectedSmartWallet = loginResponse.smartWallet || null;
2348
- this.sessionEoa = (0, import_viem6.getAddress)(params.message.address);
2743
+ this.sessionEoa = (0, import_viem8.getAddress)(params.message.address);
2349
2744
  this.sessionChannel = void 0;
2350
2745
  return loginResponse;
2351
2746
  }
2352
- /**
2353
- * Warn that a legacy method is deprecated in favor of sendDeposit.
2354
- * Predeployed wallets no longer require deploySafe / createSessionKey.
2355
- */
2747
+ /** Warn that a deprecated compatibility method was called. */
2356
2748
  warnDeprecatedOnboardingMethod(methodName) {
2357
2749
  console.warn(
2358
2750
  `[ZyfaiSDK] ${methodName}() is deprecated for partner integrations. Prefer sendDeposit() \u2014 predeployed Safes and session keys are handled automatically on first deposit.`
2359
2751
  );
2360
2752
  }
2753
+ /**
2754
+ * Warn only a pool wallet, which sendDeposit onboards on its own. A contract
2755
+ * owner is never predeployed and reaches these methods through sendDeposit,
2756
+ * so warning unconditionally tells that caller to use what it just called.
2757
+ * Call after authentication, once `isPredeployed` is resolved.
2758
+ */
2759
+ warnPredeployedOnboardingMethod(methodName) {
2760
+ if (!this.isPredeployed) return;
2761
+ console.warn(
2762
+ `[ZyfaiSDK] ${methodName}() is not needed for a predeployed wallet \u2014 sendDeposit() deploys the Safe and enables the agent session on first deposit.`
2763
+ );
2764
+ }
2361
2765
  /**
2362
2766
  * Authenticate user with SIWE (Sign-In with Ethereum) & JWT token
2363
2767
  * This is required for accessing user-specific endpoints like session-keys/config
@@ -2374,7 +2778,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2374
2778
  return;
2375
2779
  }
2376
2780
  const walletClient = this.getWalletClient();
2377
- const userAddress = (0, import_viem6.getAddress)(walletClient.account.address);
2781
+ const userAddress = (0, import_viem8.getAddress)(walletClient.account.address);
2378
2782
  const chainId = this.currentChainId || walletClient.chain?.id || 8453;
2379
2783
  const challengeResponse = await this.httpClient.post(ENDPOINTS.AUTH_CHALLENGE, {});
2380
2784
  let uri;
@@ -2752,10 +3156,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2752
3156
  this.walletClient.chain?.id || 8453,
2753
3157
  this.rpcUrls
2754
3158
  );
2755
- this.walletClient = (0, import_viem6.createWalletClient)({
3159
+ this.walletClient = (0, import_viem8.createWalletClient)({
2756
3160
  account: newAddress,
2757
3161
  chain: chainConfig.chain,
2758
- transport: (0, import_viem6.custom)(this.currentProvider)
3162
+ transport: (0, import_viem8.custom)(this.currentProvider)
2759
3163
  });
2760
3164
  this.currentChainId = this.walletClient.chain?.id || null;
2761
3165
  try {
@@ -2820,10 +3224,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2820
3224
  }
2821
3225
  this.signer = (0, import_accounts2.privateKeyToAccount)(privateKey);
2822
3226
  this.currentChainId = chainId;
2823
- this.walletClient = (0, import_viem6.createWalletClient)({
3227
+ this.walletClient = (0, import_viem8.createWalletClient)({
2824
3228
  account: this.signer,
2825
3229
  chain: chainConfig.chain,
2826
- transport: (0, import_viem6.http)(chainConfig.rpcUrl)
3230
+ transport: (0, import_viem8.http)(chainConfig.rpcUrl)
2827
3231
  });
2828
3232
  connectedAddress = this.signer.address;
2829
3233
  this.currentProvider = null;
@@ -2841,10 +3245,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2841
3245
  if (!accounts || accounts.length === 0) {
2842
3246
  throw new Error("No accounts found in wallet provider");
2843
3247
  }
2844
- this.walletClient = (0, import_viem6.createWalletClient)({
3248
+ this.walletClient = (0, import_viem8.createWalletClient)({
2845
3249
  account: accounts[0],
2846
3250
  chain: chainConfig.chain,
2847
- transport: (0, import_viem6.custom)(provider)
3251
+ transport: (0, import_viem8.custom)(provider)
2848
3252
  });
2849
3253
  connectedAddress = accounts[0];
2850
3254
  this.currentProvider = provider;
@@ -2853,7 +3257,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2853
3257
  provider.on("accountsChanged", this.handleAccountsChanged.bind(this));
2854
3258
  }
2855
3259
  } else if (provider.account && provider.transport) {
2856
- this.walletClient = (0, import_viem6.createWalletClient)({
3260
+ this.walletClient = (0, import_viem8.createWalletClient)({
2857
3261
  account: provider.account,
2858
3262
  chain: chainConfig.chain,
2859
3263
  transport: provider.transport
@@ -2914,10 +3318,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2914
3318
  targetChainId,
2915
3319
  this.rpcUrls
2916
3320
  );
2917
- return (0, import_viem6.createWalletClient)({
3321
+ return (0, import_viem8.createWalletClient)({
2918
3322
  account: this.signer,
2919
3323
  chain: targetChainConfig.chain,
2920
- transport: (0, import_viem6.http)(targetChainConfig.rpcUrl)
3324
+ transport: (0, import_viem8.http)(targetChainConfig.rpcUrl)
2921
3325
  });
2922
3326
  } else {
2923
3327
  if (!this.walletClient) {
@@ -2939,6 +3343,50 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2939
3343
  * from the user record before allowing a transfer to an undeployed pool Safe.
2940
3344
  * @private
2941
3345
  */
3346
+ /**
3347
+ * Deploy the child Zyfai Safe and session for a nested (contract) owner.
3348
+ * @private
3349
+ */
3350
+ async ensureNestedOwnerReadyForDeposit(userAddress, chainId, strategy) {
3351
+ if (this.isPredeployed) return;
3352
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
3353
+ const ownerType = await getAccountType(
3354
+ userAddress,
3355
+ chainConfig.publicClient
3356
+ );
3357
+ if (ownerType !== "Safe") return;
3358
+ await assertParentSafeDeployedOnChain(
3359
+ userAddress,
3360
+ chainConfig.publicClient,
3361
+ chainId
3362
+ );
3363
+ const childAddress = await this.getSafeAddressFor(userAddress, chainId);
3364
+ if (!childAddress) {
3365
+ throw new Error("Child smart wallet address is not available");
3366
+ }
3367
+ const childDeployed = await isSafeDeployed(
3368
+ childAddress,
3369
+ chainConfig.publicClient
3370
+ );
3371
+ if (!childDeployed) {
3372
+ await this.deploySafe(userAddress, chainId, strategy, true);
3373
+ return;
3374
+ }
3375
+ console.info(
3376
+ `[ZyfaiSDK] nested deposit signing pending enable only chainId=${chainId} owner=${userAddress} sessionActive=${this.hasActiveSessionKey}`
3377
+ );
3378
+ await deploySafeAccount({
3379
+ owner: this.getWalletClient(chainId),
3380
+ safeOwnerAddress: userAddress,
3381
+ chain: chainConfig.chain,
3382
+ publicClient: chainConfig.publicClient,
3383
+ chainId,
3384
+ httpClient: this.httpClient
3385
+ });
3386
+ if (!this.hasActiveSessionKey) {
3387
+ await this.createSessionKey(userAddress, chainId);
3388
+ }
3389
+ }
2942
3390
  async hydrateSessionWallet() {
2943
3391
  if (this.predeployedResolved || !this.sessionEoa) return;
2944
3392
  const me = await this.httpClient.get(ENDPOINTS.USER_ME);
@@ -3023,9 +3471,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3023
3471
  /**
3024
3472
  * Deploy Safe Smart Wallet for a user
3025
3473
  *
3026
- * @deprecated Prefer {@link ZyfaiSDK.sendDeposit}. Predeployed Safes and session keys are
3027
- * managed automatically on first deposit. This method remains available for
3028
- * legacy flows.
3474
+ * Not needed for a predeployed (pool) wallet: {@link ZyfaiSDK.sendDeposit} deploys the Safe and
3475
+ * enables the agent session on first deposit. Required for an owner that is not predeployed —
3476
+ * a contract owner such as a nested Safe, or a legacy self-deployed wallet — where `sendDeposit`
3477
+ * calls this method internally.
3029
3478
  *
3030
3479
  * @see {@link ZyfaiSDK.sendDeposit}
3031
3480
  *
@@ -3039,16 +3488,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3039
3488
  *
3040
3489
  * @example
3041
3490
  * ```typescript
3042
- * // Preferred: sendDeposit handles predeployed wallet onboarding
3491
+ * // Preferred: sendDeposit handles onboarding for every owner type
3043
3492
  * const sent = await sdk.sendDeposit(userAddress, 8453, amount, "USDC");
3044
3493
  * await sdk.waitForDepositCredit(sent.registration.id, 8453);
3045
3494
  *
3046
- * // Legacy: deploy with default conservative strategy
3495
+ * // Explicit: deploy with default conservative strategy
3047
3496
  * await sdk.deploySafe(userAddress, 8453);
3048
3497
  * ```
3049
3498
  */
3050
3499
  async deploySafe(userAddress, chainId, strategy, createSessionKey) {
3051
- this.warnDeprecatedOnboardingMethod("deploySafe");
3052
3500
  try {
3053
3501
  if (!userAddress) {
3054
3502
  throw new Error("User address is required");
@@ -3057,6 +3505,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3057
3505
  throw new Error(`Unsupported chain ID: ${chainId}`);
3058
3506
  }
3059
3507
  await this.authenticateUser();
3508
+ this.warnPredeployedOnboardingMethod("deploySafe");
3060
3509
  if (this.isPredeployed && this.isConnectedUser(userAddress)) {
3061
3510
  const predeployedAddress = await this.getSafeAddressFor(
3062
3511
  userAddress,
@@ -3086,16 +3535,28 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3086
3535
  }
3087
3536
  const walletClient = this.getWalletClient(chainId);
3088
3537
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
3089
- const safeAddress = await getDeterministicSafeAddress({
3090
- safeOwnerAddress: userAddress,
3091
- chain: chainConfig.chain,
3092
- publicClient: chainConfig.publicClient
3093
- });
3538
+ const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
3539
+ if (!safeAddress) {
3540
+ throw new Error("Smart wallet address is not available");
3541
+ }
3094
3542
  const alreadyDeployed = await isSafeDeployed(
3095
3543
  safeAddress,
3096
3544
  chainConfig.publicClient
3097
3545
  );
3098
3546
  if (alreadyDeployed) {
3547
+ let enableTxHash = "0x0";
3548
+ if (!this.isPredeployed) {
3549
+ const enabled = await deploySafeAccount({
3550
+ owner: walletClient,
3551
+ safeOwnerAddress: userAddress,
3552
+ chain: chainConfig.chain,
3553
+ publicClient: chainConfig.publicClient,
3554
+ chainId,
3555
+ httpClient: this.httpClient,
3556
+ strategy: strategy ? toInternalStrategy(strategy) : "safe_strategy"
3557
+ });
3558
+ enableTxHash = enabled.txHash || "0x0";
3559
+ }
3099
3560
  await this.updateUserProtocols(strategy);
3100
3561
  let sessionKeyCreated2 = false;
3101
3562
  if (createSessionKey) {
@@ -3112,7 +3573,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3112
3573
  return {
3113
3574
  success: true,
3114
3575
  safeAddress,
3115
- txHash: "0x0",
3576
+ txHash: enableTxHash,
3116
3577
  status: "deployed",
3117
3578
  sessionKeyCreated: sessionKeyCreated2
3118
3579
  };
@@ -3137,6 +3598,17 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3137
3598
  );
3138
3599
  }
3139
3600
  await this.updateUserProtocols(strategy);
3601
+ if (!this.isPredeployed) {
3602
+ await deploySafeAccount({
3603
+ owner: walletClient,
3604
+ safeOwnerAddress: userAddress,
3605
+ chain: chainConfig.chain,
3606
+ publicClient: chainConfig.publicClient,
3607
+ chainId,
3608
+ httpClient: this.httpClient,
3609
+ strategy: internalStrategy
3610
+ });
3611
+ }
3140
3612
  let sessionKeyCreated = false;
3141
3613
  if (createSessionKey) {
3142
3614
  try {
@@ -3158,18 +3630,17 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3158
3630
  };
3159
3631
  } catch (error) {
3160
3632
  console.error("Safe deployment failed:", error);
3161
- throw new Error(
3162
- `Safe deployment failed: ${error.message}. deploySafe() is deprecated \u2014 prefer sendDeposit() for predeployed wallet onboarding.`
3163
- );
3633
+ throw new Error(`Safe deployment failed: ${error.message}`);
3164
3634
  }
3165
3635
  }
3166
3636
  /**
3167
3637
  * Create session key with auto-fetched configuration from Zyfai API
3168
3638
  * This is the simplified method that automatically fetches session configuration
3169
3639
  *
3170
- * @deprecated Prefer {@link ZyfaiSDK.sendDeposit}. Predeployed wallets already have the
3171
- * agent session enabled; session activation is handled after first deposit.
3172
- * This method remains available for legacy flows.
3640
+ * Not needed for a predeployed (pool) wallet: its agent session is already enabled on-chain and
3641
+ * {@link ZyfaiSDK.sendDeposit} records it after the first deposit. Required for an owner that is
3642
+ * not predeployed — a contract owner such as a nested Safe, or a legacy self-deployed wallet —
3643
+ * where `sendDeposit` calls this method internally.
3173
3644
  *
3174
3645
  * @see {@link ZyfaiSDK.sendDeposit}
3175
3646
  *
@@ -3181,18 +3652,18 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3181
3652
  *
3182
3653
  * @example
3183
3654
  * ```typescript
3184
- * // Preferred: sendDeposit handles session onboarding for predeployed wallets
3655
+ * // Preferred: sendDeposit handles session onboarding for every owner type
3185
3656
  * const sent = await sdk.sendDeposit(userAddress, 8453, amount, "USDC");
3186
3657
  * await sdk.waitForDepositCredit(sent.registration.id, 8453);
3187
3658
  *
3188
- * // Legacy:
3659
+ * // Explicit:
3189
3660
  * const result = await sdk.createSessionKey(userAddress, 8453);
3190
3661
  * ```
3191
3662
  */
3192
3663
  async createSessionKey(userAddress, chainId) {
3193
- this.warnDeprecatedOnboardingMethod("createSessionKey");
3194
3664
  try {
3195
3665
  await this.authenticateUser();
3666
+ this.warnPredeployedOnboardingMethod("createSessionKey");
3196
3667
  if (!this.authenticatedUserId) {
3197
3668
  throw new Error(
3198
3669
  "User ID not available. Please ensure authentication completed successfully."
@@ -3237,6 +3708,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3237
3708
  userAddress,
3238
3709
  chainConfig.publicClient
3239
3710
  );
3711
+ if (accountType === "Safe") {
3712
+ await this.assertOwnerSafeOnSessionChains(
3713
+ userAddress,
3714
+ sessions
3715
+ );
3716
+ }
3240
3717
  const signingParams = {
3241
3718
  permitGenericPolicy,
3242
3719
  ignoreSecurityAttestations: accountType === "Safe"
@@ -3264,7 +3741,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3264
3741
  };
3265
3742
  } catch (error) {
3266
3743
  throw new Error(
3267
- `Failed to create session key: ${error.message}. createSessionKey() is deprecated \u2014 prefer sendDeposit() for predeployed wallet onboarding.`
3744
+ `Failed to create session key: ${error.message}`
3268
3745
  );
3269
3746
  }
3270
3747
  }
@@ -3272,6 +3749,35 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3272
3749
  * Internal method to sign session key
3273
3750
  * @private
3274
3751
  */
3752
+ /**
3753
+ * A nested Safe owner signs one MultiChainSession covering every chain in the
3754
+ * session configuration, and the child validates that signature against the
3755
+ * owner through ERC-1271 on each of them. A chain where the owner has no code
3756
+ * would accept the signature nowhere, so refuse rather than sign it.
3757
+ *
3758
+ * The session list is not filtered here: the execution API rebuilds the digest
3759
+ * from its own configuration, so dropping a chain client-side would change the
3760
+ * hash and the signature would be rejected everywhere.
3761
+ * @private
3762
+ */
3763
+ async assertOwnerSafeOnSessionChains(ownerAddress, sessions) {
3764
+ const chainIds = [
3765
+ ...new Set(sessions.map((session) => Number(session.chainId)))
3766
+ ].filter(isSupportedChain);
3767
+ const missing = [];
3768
+ await Promise.all(
3769
+ chainIds.map(async (id) => {
3770
+ const { publicClient } = getChainConfig(id, this.rpcUrls);
3771
+ const code = await publicClient.getCode({ address: ownerAddress });
3772
+ if (!code || code === "0x") missing.push(id);
3773
+ })
3774
+ );
3775
+ if (missing.length > 0) {
3776
+ throw new Error(
3777
+ `Owner Safe ${ownerAddress} has no code on chain(s) ${missing.sort((a, b) => a - b).join(", ")} covered by the session configuration. Deploy the Safe there, or restrict the user's chains, before signing the session.`
3778
+ );
3779
+ }
3780
+ }
3275
3781
  async signSessionKey(userAddress, chainId, sessions, signingParams) {
3276
3782
  try {
3277
3783
  if (!userAddress) {
@@ -3285,14 +3791,13 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3285
3791
  }
3286
3792
  const walletClient = this.getWalletClient();
3287
3793
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
3288
- const accountType = await getAccountType(
3794
+ await this.hydrateSessionWallet();
3795
+ const childSafeAddress = await this.getSafeAddressFor(
3289
3796
  userAddress,
3290
- chainConfig.publicClient
3797
+ chainId
3291
3798
  );
3292
- if (accountType !== "EOA") {
3293
- throw new Error(
3294
- `Invalid account type for ${userAddress}. Must be an EOA.`
3295
- );
3799
+ if (!childSafeAddress) {
3800
+ throw new Error("Child smart wallet address is not available");
3296
3801
  }
3297
3802
  const sessionChainIds = [
3298
3803
  ...new Set(sessions.map((s) => Number(s.chainId)))
@@ -3302,6 +3807,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3302
3807
  {
3303
3808
  owner: walletClient,
3304
3809
  safeOwnerAddress: userAddress,
3810
+ childSafeAddress,
3305
3811
  chain: chainConfig.chain,
3306
3812
  publicClient: chainConfig.publicClient
3307
3813
  },
@@ -3793,6 +4299,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3793
4299
  throw new Error("Smart wallet address is not available");
3794
4300
  }
3795
4301
  const amountBigInt = BigInt(amount);
4302
+ const ownerType = await getAccountType(
4303
+ userAddress,
4304
+ chainConfig.publicClient
4305
+ );
4306
+ if (ownerType !== "EOA" && ownerType !== "Safe") {
4307
+ throw new Error(
4308
+ `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.`
4309
+ );
4310
+ }
3796
4311
  const [isDeployed, currentSafeBalance] = await Promise.all([
3797
4312
  isSafeDeployed(safeAddress, chainConfig.publicClient),
3798
4313
  minRequired !== void 0 ? chainConfig.publicClient.readContract({
@@ -3804,7 +4319,18 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3804
4319
  this.prepareFirstDeposit(strategy)
3805
4320
  ]).then(([deployed, balance]) => [deployed, balance]);
3806
4321
  if (!isDeployed) {
3807
- if (!(this.isPredeployed && this.isConnectedUser(userAddress))) {
4322
+ if (ownerType === "Safe" && !this.isPredeployed) {
4323
+ await assertParentSafeDeployedOnChain(
4324
+ userAddress,
4325
+ chainConfig.publicClient,
4326
+ chainId
4327
+ );
4328
+ await this.ensureNestedOwnerReadyForDeposit(
4329
+ userAddress,
4330
+ chainId,
4331
+ strategy
4332
+ );
4333
+ } else if (!(this.isPredeployed && this.isConnectedUser(userAddress))) {
3808
4334
  throw new Error(
3809
4335
  `Safe not available for ${userAddress} on chain ${chainId}.`
3810
4336
  );
@@ -3827,16 +4353,74 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3827
4353
  );
3828
4354
  }
3829
4355
  }
4356
+ if (ownerType === "Safe" && isDeployed) {
4357
+ await assertParentSafeDeployedOnChain(
4358
+ userAddress,
4359
+ chainConfig.publicClient,
4360
+ chainId
4361
+ );
4362
+ await this.ensureNestedOwnerReadyForDeposit(
4363
+ userAddress,
4364
+ chainId,
4365
+ strategy
4366
+ );
4367
+ }
3830
4368
  if (allowPermit && this.isPredeployed && this.isConnectedUser(userAddress)) {
3831
4369
  const sponsored = await this.sendFirstPermitDeposit({
3832
- owner: (0, import_viem6.getAddress)(userAddress),
4370
+ owner: (0, import_viem8.getAddress)(userAddress),
3833
4371
  safe: safeAddress,
3834
4372
  chainId,
3835
- token: (0, import_viem6.getAddress)(token),
4373
+ token: (0, import_viem8.getAddress)(token),
3836
4374
  amount: amountBigInt
3837
4375
  });
3838
4376
  if (sponsored) return sponsored;
3839
4377
  }
4378
+ if (ownerType === "Safe") {
4379
+ const since = new Date(Date.now() - NESTED_SAFE_RESUME_WINDOW_MS);
4380
+ const inFlight = await findSafeTransferProposal({
4381
+ parentSafe: userAddress,
4382
+ childSafe: safeAddress,
4383
+ chainId,
4384
+ tokenAddress: token,
4385
+ amount: amountBigInt,
4386
+ since
4387
+ });
4388
+ let safeTxHash = inFlight?.safeTxHash;
4389
+ if (!inFlight) {
4390
+ const proposed = await walletClient.writeContract({
4391
+ address: token,
4392
+ abi: erc20TransferWriteAbi(assetSymbol),
4393
+ functionName: "transfer",
4394
+ args: [safeAddress, amountBigInt],
4395
+ chain: chainConfig.chain,
4396
+ account: walletClient.account
4397
+ });
4398
+ safeTxHash = (await findSafeTransferByHash({ chainId, safeTxHash: proposed }))?.safeTxHash;
4399
+ }
4400
+ const executedHash = inFlight?.isExecuted && inFlight.transactionHash ? inFlight.transactionHash : await waitForSafeTransferExecution({
4401
+ parentSafe: userAddress,
4402
+ childSafe: safeAddress,
4403
+ chainId,
4404
+ tokenAddress: token,
4405
+ amount: amountBigInt,
4406
+ safeTxHash,
4407
+ since
4408
+ });
4409
+ const registration2 = await this.registerDeposit(
4410
+ chainId,
4411
+ executedHash,
4412
+ amount,
4413
+ token
4414
+ );
4415
+ return {
4416
+ success: true,
4417
+ txHash: executedHash,
4418
+ smartWallet: safeAddress,
4419
+ amount: amountBigInt.toString(),
4420
+ route: "direct",
4421
+ registration: registration2
4422
+ };
4423
+ }
3840
4424
  const txHash = await walletClient.writeContract({
3841
4425
  address: token,
3842
4426
  abi: erc20TransferWriteAbi(assetSymbol),
@@ -3889,7 +4473,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3889
4473
  * ```
3890
4474
  */
3891
4475
  async getFirstPermitDepositStatus(userAddress) {
3892
- if (!this.sessionEoa || !(0, import_viem6.isAddressEqual)((0, import_viem6.getAddress)(userAddress), this.sessionEoa)) {
4476
+ if (!this.sessionEoa || !(0, import_viem8.isAddressEqual)((0, import_viem8.getAddress)(userAddress), this.sessionEoa)) {
3893
4477
  throw new Error("userAddress does not match authenticated session EOA");
3894
4478
  }
3895
4479
  return (await this.getFirstPermitDepositAvailability()).intent;
@@ -4360,16 +4944,16 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4360
4944
  method: "wallet_switchEthereumChain",
4361
4945
  params: [{ chainId: `0x${originChainId.toString(16)}` }]
4362
4946
  });
4363
- const chain = isSupportedChain(originChainId) ? getChainConfig(originChainId, this.rpcUrls).chain : (0, import_viem6.defineChain)({
4947
+ const chain = isSupportedChain(originChainId) ? getChainConfig(originChainId, this.rpcUrls).chain : (0, import_viem8.defineChain)({
4364
4948
  id: originChainId,
4365
4949
  name: `Chain ${originChainId}`,
4366
4950
  nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
4367
4951
  rpcUrls: { default: { http: ["http://127.0.0.1"] } }
4368
4952
  });
4369
- this.walletClient = (0, import_viem6.createWalletClient)({
4953
+ this.walletClient = (0, import_viem8.createWalletClient)({
4370
4954
  account: this.walletClient.account,
4371
4955
  chain,
4372
- transport: (0, import_viem6.custom)(this.currentProvider)
4956
+ transport: (0, import_viem8.custom)(this.currentProvider)
4373
4957
  });
4374
4958
  if (isSupportedChain(originChainId)) {
4375
4959
  this.currentChainId = originChainId;
@@ -4545,7 +5129,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4545
5129
  safeAddress,
4546
5130
  tokenAddress,
4547
5131
  to: tokenAddress,
4548
- data: (0, import_viem6.encodeFunctionData)({
5132
+ data: (0, import_viem8.encodeFunctionData)({
4549
5133
  abi: ERC20_ABI,
4550
5134
  functionName: "transfer",
4551
5135
  args: [safeAddress, amountBigInt]
@@ -4574,7 +5158,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4574
5158
  if (!userAddress) {
4575
5159
  throw new Error("A user address is required");
4576
5160
  }
4577
- const owner = (0, import_viem6.getAddress)(userAddress);
5161
+ const owner = (0, import_viem8.getAddress)(userAddress);
4578
5162
  const chainId = 8453;
4579
5163
  await this.hydrateSessionWallet();
4580
5164
  const safe = await this.getSafeAddressFor(owner, chainId);
@@ -4596,7 +5180,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4596
5180
  ]).catch(() => {
4597
5181
  throw new Error(`Safe ${safe} is not deployed on Base`);
4598
5182
  });
4599
- if (threshold !== 1n || !owners.some((o) => (0, import_viem6.getAddress)(o) === owner)) {
5183
+ if (threshold !== 1n || !owners.some((o) => (0, import_viem8.getAddress)(o) === owner)) {
4600
5184
  throw new Error(
4601
5185
  `${owner} cannot execute Safe ${safe} alone (not an owner, or threshold above 1)`
4602
5186
  );
@@ -4685,7 +5269,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4685
5269
  if (!userAddress) {
4686
5270
  throw new Error("A user address is required");
4687
5271
  }
4688
- if (this.sessionEoa && (0, import_viem6.getAddress)(userAddress) !== this.sessionEoa) {
5272
+ if (this.sessionEoa && (0, import_viem8.getAddress)(userAddress) !== this.sessionEoa) {
4689
5273
  throw new Error("userAddress does not match authenticated session EOA");
4690
5274
  }
4691
5275
  }
@@ -4831,7 +5415,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4831
5415
  */
4832
5416
  async prepareDeposit(params) {
4833
5417
  const { userAddress, chainId, amount, asset } = params;
4834
- if (this.sessionEoa && (0, import_viem6.getAddress)(userAddress) !== this.sessionEoa) {
5418
+ if (this.sessionEoa && (0, import_viem8.getAddress)(userAddress) !== this.sessionEoa) {
4835
5419
  throw new Error("userAddress does not match authenticated session EOA");
4836
5420
  }
4837
5421
  const setup = await this.ensureDepositProfileForPrepare({
@@ -6890,7 +7474,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
6890
7474
  if (!tokenUriResponse.tokenUri) {
6891
7475
  throw new Error("API did not return a tokenUri");
6892
7476
  }
6893
- const callData = (0, import_viem6.encodeFunctionData)({
7477
+ const callData = (0, import_viem8.encodeFunctionData)({
6894
7478
  abi: IDENTITY_REGISTRY_ABI,
6895
7479
  functionName: "register",
6896
7480
  args: [tokenUriResponse.tokenUri]
@@ -7359,8 +7943,8 @@ _ZyfaiSDK.IDENTITY_REGISTRY_CHAIN_IDS = [8453, 42161];
7359
7943
  var ZyfaiSDK = _ZyfaiSDK;
7360
7944
 
7361
7945
  // src/utils/session-verification.ts
7362
- var import_module_sdk2 = require("@rhinestone/module-sdk");
7363
- var import_viem7 = require("viem");
7946
+ var import_module_sdk3 = require("@rhinestone/module-sdk");
7947
+ var import_viem9 = require("viem");
7364
7948
  function buildV1ChainSessions(inputs) {
7365
7949
  const chainSessions = inputs.map(({ account, smartSession, nonce, session, permitGenericPolicy, permitAdminAccess, ignoreSecurityAttestations }) => ({
7366
7950
  chainId: session.chainId,
@@ -7389,8 +7973,8 @@ function validateV1ChainSessions(sessions) {
7389
7973
  const fail = () => {
7390
7974
  throw new Error("Invalid v1 chain session payload");
7391
7975
  };
7392
- const address = (v) => typeof v === "string" && (0, import_viem7.isAddress)(v);
7393
- const hex = (v, bytes) => typeof v === "string" && (0, import_viem7.isHex)(v, { strict: true }) && v.length % 2 === 0 && (bytes === void 0 || (0, import_viem7.size)(v) === bytes);
7976
+ const address = (v) => typeof v === "string" && (0, import_viem9.isAddress)(v);
7977
+ const hex = (v, bytes) => typeof v === "string" && (0, import_viem9.isHex)(v, { strict: true }) && v.length % 2 === 0 && (bytes === void 0 || (0, import_viem9.size)(v) === bytes);
7394
7978
  const policies = (v) => Array.isArray(v) && v.every((p) => p && address(p.policy) && hex(p.initData));
7395
7979
  if (!Array.isArray(sessions) || !sessions.length) fail();
7396
7980
  for (const entry of sessions) {
@@ -7422,14 +8006,14 @@ function parseV1ChainSessions(json) {
7422
8006
  }
7423
8007
  function hashV1SessionEnable(chainSessions) {
7424
8008
  validateV1ChainSessions(chainSessions);
7425
- const permissionEnableHash = (0, import_module_sdk2.hashChainSessions)(chainSessions);
7426
- return { permissionEnableHash, personalSignDigest: (0, import_viem7.hashMessage)({ raw: permissionEnableHash }) };
8009
+ const permissionEnableHash = (0, import_module_sdk3.hashChainSessions)(chainSessions);
8010
+ return { permissionEnableHash, personalSignDigest: (0, import_viem9.hashMessage)({ raw: permissionEnableHash }) };
7427
8011
  }
7428
8012
 
7429
8013
  // src/utils/userop-verification.ts
7430
- var import_viem8 = require("viem");
8014
+ var import_viem10 = require("viem");
7431
8015
  var ENTRY_POINT_V07_ADDRESS = "0x0000000071727De22E5E9d8BAf0edAc6f37da032";
7432
- var KNOWN_CALLS_ABI = (0, import_viem8.parseAbi)([
8016
+ var KNOWN_CALLS_ABI = (0, import_viem10.parseAbi)([
7433
8017
  "function setupSafe((address singleton, address[] owners, uint256 threshold, address setupTo, bytes setupData, address safe7579, (address module, bytes initData)[] validators, bytes callData) initData)",
7434
8018
  "function execute(bytes32 mode, bytes executionCalldata)",
7435
8019
  "function setRegistry(address registry, address[] attesters, uint8 threshold)",
@@ -7456,8 +8040,8 @@ function parseUserOperationJson(json) {
7456
8040
  if (!raw || typeof raw !== "object") fail();
7457
8041
  const input = raw;
7458
8042
  const integer = (v) => typeof v === "string" && /^(0|[1-9][0-9]*|0x[0-9a-fA-F]+)$/.test(v) ? BigInt(v) : fail();
7459
- const bytes = (v) => typeof v === "string" && (0, import_viem8.isHex)(v, { strict: true }) && v.length % 2 === 0 ? v : fail();
7460
- const address = (v) => typeof v === "string" && (0, import_viem8.isAddress)(v, { strict: false }) ? v : fail();
8043
+ const bytes = (v) => typeof v === "string" && (0, import_viem10.isHex)(v, { strict: true }) && v.length % 2 === 0 ? v : fail();
8044
+ const address = (v) => typeof v === "string" && (0, import_viem10.isAddress)(v, { strict: false }) ? v : fail();
7461
8045
  const op = {
7462
8046
  sender: address(input.sender),
7463
8047
  nonce: integer(input.nonce),
@@ -7484,16 +8068,16 @@ function parseUserOperationJson(json) {
7484
8068
  }
7485
8069
  return op;
7486
8070
  }
7487
- var uint128 = (value) => (0, import_viem8.numberToHex)(value, { size: 16 });
8071
+ var uint128 = (value) => (0, import_viem10.numberToHex)(value, { size: 16 });
7488
8072
  function hashUserOperationV07(userOp, chainId, entryPoint = ENTRY_POINT_V07_ADDRESS) {
7489
- const initCode = userOp.factory ? (0, import_viem8.concat)([userOp.factory, userOp.factoryData ?? "0x"]) : "0x";
7490
- const paymasterAndData = userOp.paymaster ? (0, import_viem8.concat)([
8073
+ const initCode = userOp.factory ? (0, import_viem10.concat)([userOp.factory, userOp.factoryData ?? "0x"]) : "0x";
8074
+ const paymasterAndData = userOp.paymaster ? (0, import_viem10.concat)([
7491
8075
  userOp.paymaster,
7492
8076
  uint128(userOp.paymasterVerificationGasLimit ?? 0n),
7493
8077
  uint128(userOp.paymasterPostOpGasLimit ?? 0n),
7494
8078
  userOp.paymasterData ?? "0x"
7495
8079
  ]) : "0x";
7496
- const packed = (0, import_viem8.encodeAbiParameters)(
8080
+ const packed = (0, import_viem10.encodeAbiParameters)(
7497
8081
  [
7498
8082
  { type: "address" },
7499
8083
  { type: "uint256" },
@@ -7507,26 +8091,26 @@ function hashUserOperationV07(userOp, chainId, entryPoint = ENTRY_POINT_V07_ADDR
7507
8091
  [
7508
8092
  userOp.sender,
7509
8093
  userOp.nonce,
7510
- (0, import_viem8.keccak256)(initCode),
7511
- (0, import_viem8.keccak256)(userOp.callData),
7512
- (0, import_viem8.concat)([uint128(userOp.verificationGasLimit), uint128(userOp.callGasLimit)]),
8094
+ (0, import_viem10.keccak256)(initCode),
8095
+ (0, import_viem10.keccak256)(userOp.callData),
8096
+ (0, import_viem10.concat)([uint128(userOp.verificationGasLimit), uint128(userOp.callGasLimit)]),
7513
8097
  userOp.preVerificationGas,
7514
- (0, import_viem8.concat)([uint128(userOp.maxPriorityFeePerGas), uint128(userOp.maxFeePerGas)]),
7515
- (0, import_viem8.keccak256)(paymasterAndData)
8098
+ (0, import_viem10.concat)([uint128(userOp.maxPriorityFeePerGas), uint128(userOp.maxFeePerGas)]),
8099
+ (0, import_viem10.keccak256)(paymasterAndData)
7516
8100
  ]
7517
8101
  );
7518
- return (0, import_viem8.keccak256)(
7519
- (0, import_viem8.encodeAbiParameters)(
8102
+ return (0, import_viem10.keccak256)(
8103
+ (0, import_viem10.encodeAbiParameters)(
7520
8104
  [{ type: "bytes32" }, { type: "address" }, { type: "uint256" }],
7521
- [(0, import_viem8.keccak256)(packed), entryPoint, BigInt(chainId)]
8105
+ [(0, import_viem10.keccak256)(packed), entryPoint, BigInt(chainId)]
7522
8106
  )
7523
8107
  );
7524
8108
  }
7525
8109
  function decodeCall(target, value, data) {
7526
- const call = { target, value, selector: (0, import_viem8.size)(data) >= 4 ? (0, import_viem8.slice)(data, 0, 4) : "0x" };
8110
+ const call = { target, value, selector: (0, import_viem10.size)(data) >= 4 ? (0, import_viem10.slice)(data, 0, 4) : "0x" };
7527
8111
  let decoded;
7528
8112
  try {
7529
- decoded = (0, import_viem8.decodeFunctionData)({ abi: KNOWN_CALLS_ABI, data });
8113
+ decoded = (0, import_viem10.decodeFunctionData)({ abi: KNOWN_CALLS_ABI, data });
7530
8114
  } catch {
7531
8115
  return call;
7532
8116
  }
@@ -7537,18 +8121,18 @@ function decodeCall(target, value, data) {
7537
8121
  call.calls = [decodeCall(target, 0n, initData.callData)];
7538
8122
  } else if (decoded.functionName === "execute") {
7539
8123
  const [mode, executionCalldata] = decoded.args;
7540
- const callType = (0, import_viem8.slice)(mode, 0, 1);
8124
+ const callType = (0, import_viem10.slice)(mode, 0, 1);
7541
8125
  if (callType === ERC7579_CALLTYPE_BATCH) {
7542
- const [executions] = (0, import_viem8.decodeAbiParameters)(
8126
+ const [executions] = (0, import_viem10.decodeAbiParameters)(
7543
8127
  [{ type: "tuple[]", components: [{ type: "address", name: "target" }, { type: "uint256", name: "value" }, { type: "bytes", name: "callData" }] }],
7544
8128
  executionCalldata
7545
8129
  );
7546
8130
  call.calls = executions.map((e) => decodeCall(e.target, e.value, e.callData));
7547
8131
  } else if (callType === ERC7579_CALLTYPE_SINGLE) {
7548
8132
  call.calls = [decodeCall(
7549
- (0, import_viem8.slice)(executionCalldata, 0, 20),
7550
- BigInt((0, import_viem8.slice)(executionCalldata, 20, 52)),
7551
- (0, import_viem8.size)(executionCalldata) > 52 ? (0, import_viem8.slice)(executionCalldata, 52) : "0x"
8133
+ (0, import_viem10.slice)(executionCalldata, 0, 20),
8134
+ BigInt((0, import_viem10.slice)(executionCalldata, 20, 52)),
8135
+ (0, import_viem10.size)(executionCalldata) > 52 ? (0, import_viem10.slice)(executionCalldata, 52) : "0x"
7552
8136
  )];
7553
8137
  }
7554
8138
  }
@@ -7723,6 +8307,371 @@ function createBankrProvider(config) {
7723
8307
  };
7724
8308
  return provider;
7725
8309
  }
8310
+
8311
+ // src/providers/safe-owner.ts
8312
+ var import_viem11 = require("viem");
8313
+ var EIP1271_MAGIC_VALUE = "0x1626ba7e";
8314
+ var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
8315
+ var SAFE_ABI2 = (0, import_viem11.parseAbi)([
8316
+ "function getThreshold() view returns (uint256)",
8317
+ "function getOwners() view returns (address[])",
8318
+ "function nonce() view returns (uint256)",
8319
+ "function getMessageHash(bytes message) view returns (bytes32)",
8320
+ "function getTransactionHash(address to, uint256 value, bytes data, uint8 operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce) view returns (bytes32)",
8321
+ "function execTransaction(address to, uint256 value, bytes data, uint8 operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, bytes signatures) payable returns (bool)",
8322
+ "function isValidSignature(bytes32 _dataHash, bytes _signature) view returns (bytes4)"
8323
+ ]);
8324
+ async function createSafeOwnerProvider(config) {
8325
+ if (!(0, import_viem11.isAddress)(config.safeAddress)) {
8326
+ throw new Error("safeAddress must be an Ethereum address");
8327
+ }
8328
+ const safeAddress = (0, import_viem11.getAddress)(config.safeAddress);
8329
+ const publicClient = (0, import_viem11.createPublicClient)({
8330
+ chain: config.chain,
8331
+ transport: (0, import_viem11.http)()
8332
+ });
8333
+ const ownerWallet = await resolveOwnerWallet(config.owner, config.chain);
8334
+ const code = await publicClient.getCode({ address: safeAddress });
8335
+ if (!code || code === "0x") {
8336
+ throw new Error(
8337
+ `Safe ${safeAddress} has no code on chain ${config.chain.id}`
8338
+ );
8339
+ }
8340
+ const [threshold, owners] = await Promise.all([
8341
+ publicClient.readContract({
8342
+ address: safeAddress,
8343
+ abi: SAFE_ABI2,
8344
+ functionName: "getThreshold"
8345
+ }),
8346
+ publicClient.readContract({
8347
+ address: safeAddress,
8348
+ abi: SAFE_ABI2,
8349
+ functionName: "getOwners"
8350
+ })
8351
+ ]);
8352
+ if (threshold !== 1n) {
8353
+ throw new Error(
8354
+ `Safe ${safeAddress} threshold is ${threshold.toString()}. createSafeOwnerProvider can execute only a threshold-1 Safe. For a multisig such as 2-of-4, connect the Safe with WalletConnect or the Safe App and pass that provider to connectAccount. sendDeposit waits while the other owners confirm.`
8355
+ );
8356
+ }
8357
+ const ownerAddress = ownerWallet.address;
8358
+ if (!owners.some((owner) => (0, import_viem11.getAddress)(owner) === ownerAddress)) {
8359
+ throw new Error(`${ownerAddress} is not an owner of Safe ${safeAddress}`);
8360
+ }
8361
+ const signSafeDigest = async (dataHash) => {
8362
+ const encoded = (0, import_viem11.encodeAbiParameters)([{ type: "bytes32" }], [dataHash]);
8363
+ const messageHash = await publicClient.readContract({
8364
+ address: safeAddress,
8365
+ abi: SAFE_ABI2,
8366
+ functionName: "getMessageHash",
8367
+ args: [encoded]
8368
+ });
8369
+ return ownerWallet.signHash(messageHash);
8370
+ };
8371
+ const probeHash = (0, import_viem11.hashMessage)("zyfai safe owner");
8372
+ const probeSignature = await signSafeDigest(probeHash);
8373
+ const magic = await publicClient.readContract({
8374
+ address: safeAddress,
8375
+ abi: SAFE_ABI2,
8376
+ functionName: "isValidSignature",
8377
+ args: [probeHash, probeSignature]
8378
+ });
8379
+ if (magic.toLowerCase() !== EIP1271_MAGIC_VALUE) {
8380
+ throw new Error(
8381
+ `Safe ${safeAddress} rejected the owner signature (isValidSignature returned ${magic})`
8382
+ );
8383
+ }
8384
+ const executeFromSafe = async (tx) => {
8385
+ const nonce = await publicClient.readContract({
8386
+ address: safeAddress,
8387
+ abi: SAFE_ABI2,
8388
+ functionName: "nonce"
8389
+ });
8390
+ const safeTxHash = await publicClient.readContract({
8391
+ address: safeAddress,
8392
+ abi: SAFE_ABI2,
8393
+ functionName: "getTransactionHash",
8394
+ args: [
8395
+ tx.to,
8396
+ tx.value,
8397
+ tx.data,
8398
+ 0,
8399
+ 0n,
8400
+ 0n,
8401
+ 0n,
8402
+ ZERO_ADDRESS,
8403
+ ZERO_ADDRESS,
8404
+ nonce
8405
+ ]
8406
+ });
8407
+ const signature = await ownerWallet.signHash(safeTxHash);
8408
+ const data = (0, import_viem11.encodeFunctionData)({
8409
+ abi: SAFE_ABI2,
8410
+ functionName: "execTransaction",
8411
+ args: [
8412
+ tx.to,
8413
+ tx.value,
8414
+ tx.data,
8415
+ 0,
8416
+ 0n,
8417
+ 0n,
8418
+ 0n,
8419
+ ZERO_ADDRESS,
8420
+ ZERO_ADDRESS,
8421
+ signature
8422
+ ]
8423
+ });
8424
+ const hash = await ownerWallet.sendTransaction({
8425
+ to: safeAddress,
8426
+ data,
8427
+ value: 0n
8428
+ });
8429
+ const receipt = await publicClient.waitForTransactionReceipt({ hash });
8430
+ if (receipt.status !== "success") {
8431
+ throw new Error(`Safe transaction reverted: ${hash}`);
8432
+ }
8433
+ return hash;
8434
+ };
8435
+ return {
8436
+ async request({ method, params }) {
8437
+ if (method === "eth_requestAccounts" || method === "eth_accounts") {
8438
+ return [safeAddress];
8439
+ }
8440
+ if (method === "personal_sign" || method === "eth_sign") {
8441
+ return signSafeDigest(personalSignDigest(params));
8442
+ }
8443
+ if (method === "eth_signTypedData_v4" || method === "eth_signTypedData") {
8444
+ return signSafeDigest(typedDataDigest(params));
8445
+ }
8446
+ if (method === "eth_sendTransaction" || method === "wallet_sendTransaction") {
8447
+ return executeFromSafe(readSafeTransaction(params));
8448
+ }
8449
+ return publicClient.request({
8450
+ method,
8451
+ params: params ?? []
8452
+ });
8453
+ }
8454
+ };
8455
+ }
8456
+ async function resolveOwnerWallet(owner, chain) {
8457
+ if (isHashSigner(owner)) {
8458
+ const address = (0, import_viem11.getAddress)(owner.address);
8459
+ const wallet = (0, import_viem11.createWalletClient)({
8460
+ account: owner,
8461
+ chain,
8462
+ transport: (0, import_viem11.http)()
8463
+ });
8464
+ return {
8465
+ address,
8466
+ signHash: (hash) => owner.sign({ hash }),
8467
+ signTypedData: (params) => signAccountTypedData(owner, params),
8468
+ sendTransaction: (tx) => wallet.sendTransaction({
8469
+ account: owner,
8470
+ chain,
8471
+ to: tx.to,
8472
+ data: tx.data,
8473
+ value: tx.value
8474
+ })
8475
+ };
8476
+ }
8477
+ if (isWalletClient(owner)) {
8478
+ const address = await walletClientAddress(owner);
8479
+ return {
8480
+ address,
8481
+ signHash: (hash) => signOwnerHash(looseRequest(owner.request), owner.account, address, hash),
8482
+ signTypedData: (params) => {
8483
+ const { domain, types, primaryType, message } = parseTypedDataPayload(params);
8484
+ return owner.signTypedData({
8485
+ account: owner.account ?? address,
8486
+ domain,
8487
+ types,
8488
+ primaryType,
8489
+ message
8490
+ });
8491
+ },
8492
+ sendTransaction: (tx) => owner.sendTransaction({
8493
+ account: owner.account ?? address,
8494
+ chain: owner.chain ?? chain,
8495
+ to: tx.to,
8496
+ data: tx.data,
8497
+ value: tx.value
8498
+ })
8499
+ };
8500
+ }
8501
+ if (isEip1193(owner)) {
8502
+ const address = await eip1193Address(owner);
8503
+ return {
8504
+ address,
8505
+ signHash: (hash) => signOwnerHash(looseRequest(owner.request), void 0, address, hash),
8506
+ signTypedData: async (params) => {
8507
+ const { requestPayload } = parseTypedDataPayload(params);
8508
+ const signature = await owner.request({
8509
+ method: "eth_signTypedData_v4",
8510
+ params: [address, JSON.stringify(requestPayload)]
8511
+ });
8512
+ if (typeof signature !== "string" || !signature.startsWith("0x")) {
8513
+ throw new Error("Owner wallet did not return a typed-data signature");
8514
+ }
8515
+ return signature;
8516
+ },
8517
+ sendTransaction: async (tx) => {
8518
+ const hash = await owner.request({
8519
+ method: "eth_sendTransaction",
8520
+ params: [
8521
+ {
8522
+ from: address,
8523
+ to: tx.to,
8524
+ data: tx.data,
8525
+ value: tx.value === 0n ? "0x0" : `0x${tx.value.toString(16)}`
8526
+ }
8527
+ ]
8528
+ });
8529
+ if (typeof hash !== "string" || !hash.startsWith("0x")) {
8530
+ throw new Error("Owner wallet did not return a transaction hash");
8531
+ }
8532
+ return hash;
8533
+ }
8534
+ };
8535
+ }
8536
+ throw new Error(
8537
+ "owner must be a viem wallet client, an account that can sign hashes, or an EIP-1193 provider"
8538
+ );
8539
+ }
8540
+ function isWalletClient(owner) {
8541
+ return typeof owner === "object" && owner !== null && "transport" in owner && "sendTransaction" in owner && typeof owner.sendTransaction === "function";
8542
+ }
8543
+ function isHashSigner(owner) {
8544
+ return typeof owner === "object" && owner !== null && "address" in owner && "sign" in owner && typeof owner.sign === "function" && !("transport" in owner);
8545
+ }
8546
+ function isEip1193(owner) {
8547
+ return typeof owner === "object" && owner !== null && "request" in owner && typeof owner.request === "function" && !("transport" in owner) && !isHashSigner(owner);
8548
+ }
8549
+ function looseRequest(request) {
8550
+ return request;
8551
+ }
8552
+ async function walletClientAddress(owner) {
8553
+ if (owner.account?.address && (0, import_viem11.isAddress)(owner.account.address)) {
8554
+ return (0, import_viem11.getAddress)(owner.account.address);
8555
+ }
8556
+ return requestAccount(looseRequest(owner.request));
8557
+ }
8558
+ async function eip1193Address(owner) {
8559
+ return requestAccount(looseRequest(owner.request));
8560
+ }
8561
+ async function requestAccount(request) {
8562
+ const accounts = await request({ method: "eth_requestAccounts" });
8563
+ const first = Array.isArray(accounts) ? accounts[0] : void 0;
8564
+ if (typeof first !== "string" || !(0, import_viem11.isAddress)(first)) {
8565
+ throw new Error("Owner wallet did not return an account");
8566
+ }
8567
+ return (0, import_viem11.getAddress)(first);
8568
+ }
8569
+ async function signOwnerHash(request, account, address, hash) {
8570
+ if (account?.sign) {
8571
+ return account.sign({ hash });
8572
+ }
8573
+ const signature = await request({
8574
+ method: "personal_sign",
8575
+ params: [hash, address]
8576
+ });
8577
+ if (typeof signature !== "string" || !signature.startsWith("0x")) {
8578
+ throw new Error("Owner wallet did not return a signature");
8579
+ }
8580
+ return asSafeEthSign(signature);
8581
+ }
8582
+ function asSafeEthSign(signature) {
8583
+ const sig = (0, import_viem11.hexToSignature)(signature);
8584
+ const current = sig.v === void 0 ? sig.yParity === 1 ? 28 : 27 : Number(sig.v);
8585
+ const v = current >= 27 ? current + 4 : current + 31;
8586
+ return (0, import_viem11.signatureToHex)({ r: sig.r, s: sig.s, v: BigInt(v) });
8587
+ }
8588
+ function personalSignDigest(params) {
8589
+ const [first, second] = params ?? [];
8590
+ const message = typeof first === "string" && (0, import_viem11.isAddress)(first) ? second : first;
8591
+ const hex = typeof message === "string" && message.startsWith("0x") ? message : (0, import_viem11.stringToHex)(String(message ?? ""));
8592
+ return (0, import_viem11.hashMessage)({ raw: hex });
8593
+ }
8594
+ function parseTypedDataPayload(params) {
8595
+ const [first, second] = params ?? [];
8596
+ const payload = typeof first === "string" && (0, import_viem11.isAddress)(first) ? second : first;
8597
+ const parsed = typeof payload === "string" ? JSON.parse(payload) : payload;
8598
+ const types = { ...parsed.types };
8599
+ delete types.EIP712Domain;
8600
+ const domain = { ...parsed.domain ?? {} };
8601
+ if (typeof domain.chainId === "string") {
8602
+ domain.chainId = BigInt(domain.chainId);
8603
+ }
8604
+ const message = coerceEip712Value(
8605
+ parsed.primaryType,
8606
+ parsed.message,
8607
+ types
8608
+ );
8609
+ return {
8610
+ domain,
8611
+ types,
8612
+ primaryType: parsed.primaryType,
8613
+ message,
8614
+ requestPayload: parsed
8615
+ };
8616
+ }
8617
+ function typedDataDigest(params) {
8618
+ const { domain, types, primaryType, message } = parseTypedDataPayload(params);
8619
+ return (0, import_viem11.hashTypedData)({ domain, types, primaryType, message });
8620
+ }
8621
+ async function signAccountTypedData(account, params) {
8622
+ const { domain, types, primaryType, message } = parseTypedDataPayload(params);
8623
+ if (!account.signTypedData) {
8624
+ throw new Error("Owner account cannot sign typed data");
8625
+ }
8626
+ return account.signTypedData({
8627
+ domain,
8628
+ types,
8629
+ primaryType,
8630
+ message
8631
+ });
8632
+ }
8633
+ function coerceEip712Value(type, value, types) {
8634
+ if (value == null) return value;
8635
+ const array = type.match(/^(.*)\[(\d*)\]$/);
8636
+ if (array) {
8637
+ if (!Array.isArray(value)) return value;
8638
+ return value.map((item) => coerceEip712Value(array[1], item, types));
8639
+ }
8640
+ const struct = types[type];
8641
+ if (struct) {
8642
+ if (typeof value !== "object" || Array.isArray(value)) return value;
8643
+ const record = value;
8644
+ const next = {};
8645
+ for (const field of struct) {
8646
+ next[field.name] = coerceEip712Value(
8647
+ field.type,
8648
+ record[field.name],
8649
+ types
8650
+ );
8651
+ }
8652
+ return next;
8653
+ }
8654
+ if (/^u?int\d*$/.test(type)) {
8655
+ if (typeof value === "bigint") return value;
8656
+ if (typeof value === "string" || typeof value === "number") {
8657
+ return BigInt(value);
8658
+ }
8659
+ }
8660
+ return value;
8661
+ }
8662
+ function readSafeTransaction(params) {
8663
+ const tx = Array.isArray(params) ? params[0] : void 0;
8664
+ if (!tx?.to || !(0, import_viem11.isAddress)(tx.to)) {
8665
+ throw new Error("Safe transaction is missing a destination");
8666
+ }
8667
+ const data = typeof tx.data === "string" && tx.data.startsWith("0x") ? tx.data : "0x";
8668
+ let value = 0n;
8669
+ if (typeof tx.value === "bigint") value = tx.value;
8670
+ else if (typeof tx.value === "number" || typeof tx.value === "string") {
8671
+ value = BigInt(tx.value);
8672
+ }
8673
+ return { to: (0, import_viem11.getAddress)(tx.to), data, value };
8674
+ }
7726
8675
  // Annotate the CommonJS export names for ESM import in node:
7727
8676
  0 && (module.exports = {
7728
8677
  ALLOWED_HISTORY_DAYS,
@@ -7756,6 +8705,7 @@ function createBankrProvider(config) {
7756
8705
  ZyfaiSDK,
7757
8706
  buildV1ChainSessions,
7758
8707
  createBankrProvider,
8708
+ createSafeOwnerProvider,
7759
8709
  decodeUserOperationCalls,
7760
8710
  getChainConfig,
7761
8711
  getDataApiBaseUrl,