@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.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";
@@ -1362,6 +1362,10 @@ var INTENT_EXECUTOR = "0x00000000005aD9ce1f5035FD62CA96CEf16AdAAF";
1362
1362
  var PROXY_EXECUTOR = "0xF659d30D4EB88B06A909F20839D8959Bd77d8790";
1363
1363
  var INTENT_SMART_SESSIONS = "0xad568b3f825a8d5ffc06dd3253526b64d810ae89";
1364
1364
  var OWNABLE_VALIDATOR = "0x000000000013fdB5234E4E3162a810F54d9f7E98";
1365
+ var OWNABLE_VALIDATOR_DEPLOYMENTS = [
1366
+ "0x2483DA3A338895199E5e538530213157e931Bf06",
1367
+ OWNABLE_VALIDATOR
1368
+ ];
1365
1369
  var SAFE_7579_ADDRESS = "0x7579EE8307284F293B1927136486880611F20002";
1366
1370
  var ERC7579_LAUNCHPAD_ADDRESS = "0x7579011aB74c46090561ea277Ba79D510c6C00ff";
1367
1371
  var POOL_MODULE_ADDRESSES = [
@@ -1373,6 +1377,143 @@ var POOL_MODULE_ADDRESSES = [
1373
1377
  OWNABLE_VALIDATOR
1374
1378
  ];
1375
1379
 
1380
+ // src/utils/safe-signature.ts
1381
+ import { SMART_SESSIONS_ADDRESS } from "@rhinestone/module-sdk";
1382
+ import {
1383
+ concat,
1384
+ getAddress,
1385
+ hashTypedData
1386
+ } from "viem";
1387
+ var EMPTY_DATA = "0x";
1388
+ var SIGNATURE_LENGTH_BYTES = 65;
1389
+ function safeSigStaticPart(sig, dynamicOffset) {
1390
+ if (sig.isContractSignature) {
1391
+ return `${sig.signer.slice(2).padStart(64, "0")}${dynamicOffset ?? ""}00`;
1392
+ }
1393
+ return sig.data.slice(2);
1394
+ }
1395
+ function safeSigDynamicPart(sig) {
1396
+ if (!sig.isContractSignature) return "";
1397
+ const dynamicPartLength = (sig.data.slice(2).length / 2).toString(16).padStart(64, "0");
1398
+ return `${dynamicPartLength}${sig.data.slice(2)}`;
1399
+ }
1400
+ function buildSafeSignatureBytes(signatures) {
1401
+ const sorted = [...signatures].sort(
1402
+ (left, right) => left.signer.toLowerCase().localeCompare(right.signer.toLowerCase())
1403
+ );
1404
+ let signatureBytes = EMPTY_DATA.slice(2);
1405
+ let dynamicBytes = "";
1406
+ for (const signature of sorted) {
1407
+ if (signature.isContractSignature) {
1408
+ const dynamicPartPosition = (sorted.length * SIGNATURE_LENGTH_BYTES + dynamicBytes.length / 2).toString(16).padStart(64, "0");
1409
+ signatureBytes += safeSigStaticPart(signature, dynamicPartPosition);
1410
+ dynamicBytes += safeSigDynamicPart(signature);
1411
+ } else {
1412
+ signatureBytes += signature.data.slice(2);
1413
+ }
1414
+ }
1415
+ return `0x${signatureBytes}${dynamicBytes}`;
1416
+ }
1417
+ function wrapNestedSafeOwnerSignature(parentSafe, rawSignature, validator) {
1418
+ const normalizedParent = getAddress(parentSafe);
1419
+ const normalizedValidator = getAddress(validator);
1420
+ const inner = rawSignature.toLowerCase().startsWith(normalizedValidator.toLowerCase()) ? `0x${rawSignature.slice(42)}` : rawSignature;
1421
+ const safeSignature = {
1422
+ signer: normalizedParent,
1423
+ data: inner,
1424
+ isContractSignature: true
1425
+ };
1426
+ return concat([
1427
+ normalizedValidator,
1428
+ buildSafeSignatureBytes([safeSignature])
1429
+ ]);
1430
+ }
1431
+ function buildMultiChainSessionTypedData(params) {
1432
+ const smartSession = params.smartSessionAddress ?? SMART_SESSIONS_ADDRESS;
1433
+ return {
1434
+ domain: {
1435
+ name: "SmartSession",
1436
+ version: "1"
1437
+ },
1438
+ types: {
1439
+ PolicyData: [
1440
+ { name: "policy", type: "address" },
1441
+ { name: "initData", type: "bytes" }
1442
+ ],
1443
+ ActionData: [
1444
+ { name: "actionTargetSelector", type: "bytes4" },
1445
+ { name: "actionTarget", type: "address" },
1446
+ { name: "actionPolicies", type: "PolicyData[]" }
1447
+ ],
1448
+ ERC7739Context: [
1449
+ { name: "appDomainSeparator", type: "bytes32" },
1450
+ { name: "contentName", type: "string[]" }
1451
+ ],
1452
+ ERC7739Data: [
1453
+ { name: "allowedERC7739Content", type: "ERC7739Context[]" },
1454
+ { name: "erc1271Policies", type: "PolicyData[]" }
1455
+ ],
1456
+ SignedPermissions: [
1457
+ { name: "permitGenericPolicy", type: "bool" },
1458
+ { name: "permitAdminAccess", type: "bool" },
1459
+ { name: "ignoreSecurityAttestations", type: "bool" },
1460
+ { name: "permitERC4337Paymaster", type: "bool" },
1461
+ { name: "userOpPolicies", type: "PolicyData[]" },
1462
+ { name: "erc7739Policies", type: "ERC7739Data" },
1463
+ { name: "actions", type: "ActionData[]" }
1464
+ ],
1465
+ SignedSession: [
1466
+ { name: "account", type: "address" },
1467
+ { name: "permissions", type: "SignedPermissions" },
1468
+ { name: "sessionValidator", type: "address" },
1469
+ { name: "sessionValidatorInitData", type: "bytes" },
1470
+ { name: "salt", type: "bytes32" },
1471
+ { name: "smartSession", type: "address" },
1472
+ { name: "nonce", type: "uint256" }
1473
+ ],
1474
+ ChainSession: [
1475
+ { name: "chainId", type: "uint64" },
1476
+ { name: "session", type: "SignedSession" }
1477
+ ],
1478
+ MultiChainSession: [
1479
+ { name: "sessionsAndChainIds", type: "ChainSession[]" }
1480
+ ]
1481
+ },
1482
+ primaryType: "MultiChainSession",
1483
+ message: {
1484
+ sessionsAndChainIds: params.sessions.map((session, index) => ({
1485
+ chainId: BigInt(session.chainId),
1486
+ session: {
1487
+ account: params.childSafeAddress,
1488
+ permissions: {
1489
+ permitGenericPolicy: params.permitGenericPolicy,
1490
+ permitAdminAccess: false,
1491
+ ignoreSecurityAttestations: true,
1492
+ permitERC4337Paymaster: session.permitERC4337Paymaster,
1493
+ userOpPolicies: session.userOpPolicies,
1494
+ erc7739Policies: session.erc7739Policies,
1495
+ actions: session.actions
1496
+ },
1497
+ sessionValidator: session.sessionValidator,
1498
+ sessionValidatorInitData: session.sessionValidatorInitData,
1499
+ salt: session.salt,
1500
+ smartSession,
1501
+ nonce: params.sessionNonces[index]
1502
+ }
1503
+ }))
1504
+ }
1505
+ };
1506
+ }
1507
+ async function signMultiChainSessionTypedData(walletClient, typedData) {
1508
+ if (!walletClient.account) {
1509
+ throw new Error("Wallet not connected. Please connect your wallet first.");
1510
+ }
1511
+ return walletClient.signMessage({
1512
+ account: walletClient.account,
1513
+ message: { raw: hashTypedData(typedData) }
1514
+ });
1515
+ }
1516
+
1376
1517
  // src/utils/safe-account.ts
1377
1518
  var SAFE_7579_ADDRESS2 = "0x7579EE8307284F293B1927136486880611F20002";
1378
1519
  var ERC7579_LAUNCHPAD_ADDRESS2 = "0x7579011aB74c46090561ea277Ba79D510c6C00ff";
@@ -1382,7 +1523,7 @@ var getSafeAccount = async (config) => {
1382
1523
  if (!safeOwnerAddress) {
1383
1524
  throw new Error("Safe owner address is required");
1384
1525
  }
1385
- const formattedOwnerAddress = getAddress(safeOwnerAddress);
1526
+ const formattedOwnerAddress = getAddress2(safeOwnerAddress);
1386
1527
  const ownableValidator = getOwnableValidator({
1387
1528
  owners: [formattedOwnerAddress],
1388
1529
  threshold: 1
@@ -1434,12 +1575,12 @@ var isSafeDeployed = async (address, publicClient) => {
1434
1575
  }
1435
1576
  };
1436
1577
  var isOwnableValidatorOwner = async (safeAddress, userAddress, publicClient) => {
1437
- const normalizedUser = getAddress(userAddress);
1438
- const normalizedSafe = getAddress(safeAddress);
1578
+ const normalizedUser = getAddress2(userAddress);
1579
+ const normalizedSafe = getAddress2(safeAddress);
1439
1580
  const validatorAddresses = Array.from(
1440
1581
  /* @__PURE__ */ new Set([
1441
- getAddress(OWNABLE_VALIDATOR),
1442
- getAddress(OWNABLE_VALIDATOR_ADDRESS)
1582
+ getAddress2(OWNABLE_VALIDATOR),
1583
+ getAddress2(OWNABLE_VALIDATOR_ADDRESS)
1443
1584
  ])
1444
1585
  );
1445
1586
  for (const validatorAddress of validatorAddresses) {
@@ -1450,7 +1591,7 @@ var isOwnableValidatorOwner = async (safeAddress, userAddress, publicClient) =>
1450
1591
  functionName: "getOwners",
1451
1592
  args: [normalizedSafe]
1452
1593
  });
1453
- if (owners.some((owner) => getAddress(owner) === normalizedUser)) {
1594
+ if (owners.some((owner) => getAddress2(owner) === normalizedUser)) {
1454
1595
  return true;
1455
1596
  }
1456
1597
  } catch {
@@ -1458,13 +1599,12 @@ var isOwnableValidatorOwner = async (safeAddress, userAddress, publicClient) =>
1458
1599
  }
1459
1600
  return false;
1460
1601
  };
1602
+ var isEip7702Delegation = (code) => !!code && code.toLowerCase().startsWith("0xef0100");
1603
+ var hasPersistentContractCode = (code) => !!code && code !== "0x" && !isEip7702Delegation(code);
1461
1604
  var getAccountType = async (address, publicClient) => {
1462
1605
  try {
1463
1606
  const code = await publicClient.getCode({ address });
1464
- if (!code || code === "0x" || code.length === 2) {
1465
- return "EOA";
1466
- }
1467
- if (code.startsWith("0xef01")) {
1607
+ if (!code || code === "0x" || code.length === 2 || isEip7702Delegation(code)) {
1468
1608
  return "EOA";
1469
1609
  }
1470
1610
  try {
@@ -1494,18 +1634,33 @@ var getAccountType = async (address, publicClient) => {
1494
1634
  };
1495
1635
  var deploySafeAccount = async (config) => {
1496
1636
  try {
1497
- const { owner, httpClient, chainId, strategy = "safe_strategy" } = config;
1637
+ const {
1638
+ owner,
1639
+ httpClient,
1640
+ chainId,
1641
+ publicClient,
1642
+ safeOwnerAddress,
1643
+ strategy
1644
+ } = config;
1498
1645
  if (!owner || !owner.account) {
1499
1646
  throw new Error(
1500
1647
  "Wallet not connected. Please connect your wallet first."
1501
1648
  );
1502
1649
  }
1503
1650
  console.log("strategy", strategy);
1651
+ const strategyBody = strategy ? { strategy } : {};
1504
1652
  const prepareResponse = await httpClient.post(
1505
1653
  `${ENDPOINTS.SAFE_DEPLOY}?chainId=${chainId}`,
1506
- { strategy }
1654
+ strategyBody
1507
1655
  );
1508
1656
  console.log("prepareResponse", prepareResponse);
1657
+ if (prepareResponse.success && !prepareResponse.userOpHashToSign) {
1658
+ return {
1659
+ safeAddress: prepareResponse.safeAddress || "0x",
1660
+ txHash: "0x0",
1661
+ isDeployed: true
1662
+ };
1663
+ }
1509
1664
  if (!prepareResponse.userOpHashToSign) {
1510
1665
  throw new Error(
1511
1666
  "Backend did not return userOpHashToSign. Response: " + JSON.stringify(prepareResponse)
@@ -1516,9 +1671,29 @@ var deploySafeAccount = async (config) => {
1516
1671
  account: owner.account,
1517
1672
  message: { raw: userOpHashToSign }
1518
1673
  });
1674
+ const ownerAddress = getAddress2(safeOwnerAddress);
1675
+ const ownerCode = await publicClient.getCode({ address: ownerAddress }).catch((error) => {
1676
+ console.warn(
1677
+ `[ZyfaiSDK] Could not read code at owner ${ownerAddress}: ${error.message}. Submitting the owner signature unwrapped; a contract owner will be rejected with AA24.`
1678
+ );
1679
+ return void 0;
1680
+ });
1681
+ const delegatedEoa = isEip7702Delegation(ownerCode);
1682
+ const wrapContractSignature = hasPersistentContractCode(ownerCode);
1683
+ const ownerKind = delegatedEoa ? "eip7702" : wrapContractSignature ? "contract" : "eoa";
1684
+ console.info(
1685
+ `[ZyfaiSDK] safe-deploy signature chainId=${chainId} owner=${ownerAddress} ownerKind=${ownerKind} wrapped=${wrapContractSignature}`
1686
+ );
1687
+ const signatureToSubmit = wrapContractSignature ? buildSafeSignatureBytes([
1688
+ {
1689
+ signer: ownerAddress,
1690
+ data: userOpSignature,
1691
+ isContractSignature: true
1692
+ }
1693
+ ]) : userOpSignature;
1519
1694
  const deployResponse = await httpClient.post(
1520
1695
  `${ENDPOINTS.SAFE_DEPLOY}?chainId=${chainId}`,
1521
- { userOpSignature, strategy }
1696
+ { userOpSignature: signatureToSubmit, ...strategyBody }
1522
1697
  );
1523
1698
  if (!deployResponse.success) {
1524
1699
  throw new Error(
@@ -1537,10 +1712,22 @@ var deploySafeAccount = async (config) => {
1537
1712
  }
1538
1713
  };
1539
1714
  var signSessionKey = async (config, sessions, allPublicClients, signingParams) => {
1540
- const { owner, publicClient } = config;
1715
+ const { owner, publicClient, safeOwnerAddress } = config;
1541
1716
  if (!owner || !owner.account) {
1542
1717
  throw new Error("Wallet not connected. Please connect your wallet first.");
1543
1718
  }
1719
+ const ownerAccountType = await getAccountType(
1720
+ safeOwnerAddress,
1721
+ publicClient
1722
+ );
1723
+ if (ownerAccountType === "Safe") {
1724
+ return signNestedOwnerSessionKey(
1725
+ config,
1726
+ sessions,
1727
+ allPublicClients,
1728
+ signingParams
1729
+ );
1730
+ }
1544
1731
  const safeAccount = await getSafeAccount(config);
1545
1732
  const account = getAccount({
1546
1733
  address: safeAccount.address,
@@ -1579,6 +1766,219 @@ var signSessionKey = async (config, sessions, allPublicClients, signingParams) =
1579
1766
  sessionNonces
1580
1767
  };
1581
1768
  };
1769
+ var IS_MODULE_INSTALLED_ABI = [
1770
+ {
1771
+ type: "function",
1772
+ name: "isModuleInstalled",
1773
+ stateMutability: "view",
1774
+ inputs: [
1775
+ { name: "moduleTypeId", type: "uint256" },
1776
+ { name: "module", type: "address" },
1777
+ { name: "additionalContext", type: "bytes" }
1778
+ ],
1779
+ outputs: [{ type: "bool" }]
1780
+ }
1781
+ ];
1782
+ async function resolveOwnerValidator(publicClient, childSafeAddress) {
1783
+ for (const candidate of OWNABLE_VALIDATOR_DEPLOYMENTS) {
1784
+ const installed = await publicClient.readContract({
1785
+ address: childSafeAddress,
1786
+ abi: IS_MODULE_INSTALLED_ABI,
1787
+ functionName: "isModuleInstalled",
1788
+ args: [1n, candidate, "0x"]
1789
+ }).catch(() => false);
1790
+ if (installed) return candidate;
1791
+ }
1792
+ throw new Error(
1793
+ `No known OwnableValidator is installed on Safe ${childSafeAddress}. A nested Safe owner signature cannot be routed to a validator.`
1794
+ );
1795
+ }
1796
+ async function signNestedOwnerSessionKey(config, sessions, allPublicClients, signingParams) {
1797
+ const { owner, publicClient, safeOwnerAddress } = config;
1798
+ const derivedChild = (await getSafeAccount(config)).address;
1799
+ const childSafeAddress = getAddress2(
1800
+ config.childSafeAddress ?? derivedChild
1801
+ );
1802
+ const account = getAccount({
1803
+ address: childSafeAddress,
1804
+ type: "safe"
1805
+ });
1806
+ const clients = allPublicClients || [publicClient];
1807
+ const sessionNonces = await Promise.all(
1808
+ sessions.map((session) => {
1809
+ const sessionChainId = Number(session.chainId);
1810
+ const client = clients.find((c) => c.chain?.id === sessionChainId) || publicClient;
1811
+ return getSessionNonce({
1812
+ client,
1813
+ account,
1814
+ permissionId: getPermissionId({
1815
+ session
1816
+ })
1817
+ });
1818
+ })
1819
+ );
1820
+ const permitGenericPolicy = signingParams?.permitGenericPolicy ?? true;
1821
+ const typedData = buildMultiChainSessionTypedData({
1822
+ childSafeAddress,
1823
+ sessions,
1824
+ sessionNonces,
1825
+ permitGenericPolicy
1826
+ });
1827
+ const ownerValidator = await resolveOwnerValidator(
1828
+ publicClient,
1829
+ childSafeAddress
1830
+ );
1831
+ const rawSignature = await signMultiChainSessionTypedData(owner, typedData);
1832
+ const signature = wrapNestedSafeOwnerSignature(
1833
+ safeOwnerAddress,
1834
+ rawSignature,
1835
+ ownerValidator
1836
+ );
1837
+ return {
1838
+ signature,
1839
+ sessionNonces
1840
+ };
1841
+ }
1842
+
1843
+ // src/utils/nested-safe-deposit.ts
1844
+ import {
1845
+ getAddress as getAddress3
1846
+ } from "viem";
1847
+ var NESTED_SAFE_DEPOSIT_TIMEOUT_MS = 20 * 60 * 1e3;
1848
+ var NESTED_SAFE_DEPOSIT_POLL_MS = 1e4;
1849
+ var NESTED_SAFE_RESUME_WINDOW_MS = 24 * 60 * 60 * 1e3;
1850
+ var SAFE_TX_SERVICE_NETWORK = {
1851
+ 1: "eth",
1852
+ 42161: "arb1",
1853
+ 8453: "base",
1854
+ 10: "oeth",
1855
+ 59144: "linea",
1856
+ 146: "sonic",
1857
+ 9745: "plasma"
1858
+ };
1859
+ function safeTxServiceNetworkName(chainId) {
1860
+ return SAFE_TX_SERVICE_NETWORK[chainId];
1861
+ }
1862
+ function safeTxServiceNetworkNameOrThrow(chainId) {
1863
+ const networkName = safeTxServiceNetworkName(chainId);
1864
+ if (!networkName) {
1865
+ throw new Error(
1866
+ `Chain ${chainId} has no Safe Transaction Service. A nested Safe deposit cannot be tracked there.`
1867
+ );
1868
+ }
1869
+ return networkName;
1870
+ }
1871
+ async function assertParentSafeDeployedOnChain(parentSafe, publicClient, chainId) {
1872
+ const code = await publicClient.getCode({ address: getAddress3(parentSafe) });
1873
+ if (!code || code === "0x") {
1874
+ throw new Error(
1875
+ `Parent Safe ${parentSafe} has no code on chain ${chainId}. Choose a chain where the Safe is deployed.`
1876
+ );
1877
+ }
1878
+ }
1879
+ function sameAddress(left, right) {
1880
+ if (!left || !right) return false;
1881
+ try {
1882
+ return getAddress3(left) === getAddress3(right);
1883
+ } catch {
1884
+ return false;
1885
+ }
1886
+ }
1887
+ function transferMatches(transaction, params) {
1888
+ if (!sameAddress(transaction.to, params.tokenAddress)) return false;
1889
+ if (transaction.isSuccessful === false) return false;
1890
+ const decoded = transaction.dataDecoded;
1891
+ if (decoded?.method?.toLowerCase() !== "transfer") return false;
1892
+ const parameters = decoded.parameters;
1893
+ if (!parameters) return false;
1894
+ const destination = parameters.find(
1895
+ (p) => (p.name === "to" || p.name === "dst" || p.name === "_to") && p.type === "address"
1896
+ );
1897
+ if (!sameAddress(destination?.value, params.childSafe)) return false;
1898
+ if (params.amount === void 0) return true;
1899
+ const valueParam = parameters.find(
1900
+ (p) => (p.name === "value" || p.name === "amount" || p.name === "_value" || p.name === "wad") && p.type.startsWith("uint")
1901
+ );
1902
+ if (!valueParam) return false;
1903
+ try {
1904
+ return BigInt(valueParam.value) === params.amount;
1905
+ } catch {
1906
+ return false;
1907
+ }
1908
+ }
1909
+ function isWithinWindow(transaction, since) {
1910
+ if (!since) return true;
1911
+ const stamp = transaction.executionDate ?? transaction.submissionDate;
1912
+ if (!stamp) return false;
1913
+ const at = Date.parse(stamp);
1914
+ return Number.isFinite(at) && at >= since.getTime();
1915
+ }
1916
+ async function findSafeTransferByHash(params) {
1917
+ const networkName = safeTxServiceNetworkNameOrThrow(params.chainId);
1918
+ const url = `https://api.safe.global/tx-service/${networkName}/api/v2/multisig-transactions/${params.safeTxHash}/`;
1919
+ const response = await fetch(url);
1920
+ if (!response.ok) return null;
1921
+ const transaction = await response.json();
1922
+ if (!transaction.safeTxHash) return null;
1923
+ if (transaction.isSuccessful === false) {
1924
+ throw new Error(
1925
+ `Safe transaction ${params.safeTxHash} on chain ${params.chainId} reverted on-chain. No deposit was registered.`
1926
+ );
1927
+ }
1928
+ return {
1929
+ safeTxHash: transaction.safeTxHash,
1930
+ transactionHash: transaction.transactionHash ?? null,
1931
+ isExecuted: transaction.isExecuted === true && !!transaction.transactionHash
1932
+ };
1933
+ }
1934
+ async function findSafeTransferProposal(params) {
1935
+ const networkName = safeTxServiceNetworkNameOrThrow(params.chainId);
1936
+ const url = `https://api.safe.global/tx-service/${networkName}/api/v2/safes/${getAddress3(
1937
+ params.parentSafe
1938
+ )}/multisig-transactions/?ordering=-nonce`;
1939
+ const response = await fetch(url);
1940
+ if (!response.ok) return null;
1941
+ const body = await response.json();
1942
+ const match = (body.results ?? []).find(
1943
+ (transaction) => !!transaction.safeTxHash && isWithinWindow(transaction, params.since) && transferMatches(transaction, {
1944
+ childSafe: params.childSafe,
1945
+ tokenAddress: params.tokenAddress,
1946
+ amount: params.amount
1947
+ })
1948
+ );
1949
+ if (!match) return null;
1950
+ return {
1951
+ safeTxHash: match.safeTxHash,
1952
+ transactionHash: match.transactionHash ?? null,
1953
+ isExecuted: match.isExecuted === true && !!match.transactionHash
1954
+ };
1955
+ }
1956
+ async function waitForSafeTransferExecution(params) {
1957
+ safeTxServiceNetworkNameOrThrow(params.chainId);
1958
+ const timeoutMs = params.timeoutMs ?? NESTED_SAFE_DEPOSIT_TIMEOUT_MS;
1959
+ const pollMs = params.pollMs ?? NESTED_SAFE_DEPOSIT_POLL_MS;
1960
+ const started = Date.now();
1961
+ do {
1962
+ const proposal = params.safeTxHash ? await findSafeTransferByHash({
1963
+ chainId: params.chainId,
1964
+ safeTxHash: params.safeTxHash
1965
+ }) : await findSafeTransferProposal({
1966
+ parentSafe: params.parentSafe,
1967
+ childSafe: params.childSafe,
1968
+ chainId: params.chainId,
1969
+ tokenAddress: params.tokenAddress,
1970
+ amount: params.amount,
1971
+ since: params.since
1972
+ });
1973
+ if (proposal?.isExecuted && proposal.transactionHash) {
1974
+ return proposal.transactionHash;
1975
+ }
1976
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
1977
+ } while (Date.now() - started < timeoutMs);
1978
+ throw new Error(
1979
+ `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.`
1980
+ );
1981
+ }
1582
1982
 
1583
1983
  // src/utils/strategy.ts
1584
1984
  var PUBLIC_STRATEGIES = `"conservative", "aggressive" or "yieldmaxxing"`;
@@ -2246,7 +2646,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2246
2646
  }
2247
2647
  this.httpClient.setAuthToken(session.accessToken);
2248
2648
  this.authenticatedUserId = session.userId ?? "bearer-session";
2249
- this.sessionEoa = session.eoa ? getAddress2(session.eoa) : null;
2649
+ this.sessionEoa = session.eoa ? getAddress4(session.eoa) : null;
2250
2650
  this.sessionChannel = session.channel;
2251
2651
  this.isPredeployed = false;
2252
2652
  this.predeployedResolved = false;
@@ -2295,19 +2695,28 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2295
2695
  this.isPredeployed = loginResponse.predeployed || false;
2296
2696
  this.predeployedResolved = true;
2297
2697
  this.connectedSmartWallet = loginResponse.smartWallet || null;
2298
- this.sessionEoa = getAddress2(params.message.address);
2698
+ this.sessionEoa = getAddress4(params.message.address);
2299
2699
  this.sessionChannel = void 0;
2300
2700
  return loginResponse;
2301
2701
  }
2302
- /**
2303
- * Warn that a legacy method is deprecated in favor of sendDeposit.
2304
- * Predeployed wallets no longer require deploySafe / createSessionKey.
2305
- */
2702
+ /** Warn that a deprecated compatibility method was called. */
2306
2703
  warnDeprecatedOnboardingMethod(methodName) {
2307
2704
  console.warn(
2308
2705
  `[ZyfaiSDK] ${methodName}() is deprecated for partner integrations. Prefer sendDeposit() \u2014 predeployed Safes and session keys are handled automatically on first deposit.`
2309
2706
  );
2310
2707
  }
2708
+ /**
2709
+ * Warn only a pool wallet, which sendDeposit onboards on its own. A contract
2710
+ * owner is never predeployed and reaches these methods through sendDeposit,
2711
+ * so warning unconditionally tells that caller to use what it just called.
2712
+ * Call after authentication, once `isPredeployed` is resolved.
2713
+ */
2714
+ warnPredeployedOnboardingMethod(methodName) {
2715
+ if (!this.isPredeployed) return;
2716
+ console.warn(
2717
+ `[ZyfaiSDK] ${methodName}() is not needed for a predeployed wallet \u2014 sendDeposit() deploys the Safe and enables the agent session on first deposit.`
2718
+ );
2719
+ }
2311
2720
  /**
2312
2721
  * Authenticate user with SIWE (Sign-In with Ethereum) & JWT token
2313
2722
  * This is required for accessing user-specific endpoints like session-keys/config
@@ -2324,7 +2733,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2324
2733
  return;
2325
2734
  }
2326
2735
  const walletClient = this.getWalletClient();
2327
- const userAddress = getAddress2(walletClient.account.address);
2736
+ const userAddress = getAddress4(walletClient.account.address);
2328
2737
  const chainId = this.currentChainId || walletClient.chain?.id || 8453;
2329
2738
  const challengeResponse = await this.httpClient.post(ENDPOINTS.AUTH_CHALLENGE, {});
2330
2739
  let uri;
@@ -2889,6 +3298,50 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2889
3298
  * from the user record before allowing a transfer to an undeployed pool Safe.
2890
3299
  * @private
2891
3300
  */
3301
+ /**
3302
+ * Deploy the child Zyfai Safe and session for a nested (contract) owner.
3303
+ * @private
3304
+ */
3305
+ async ensureNestedOwnerReadyForDeposit(userAddress, chainId, strategy) {
3306
+ if (this.isPredeployed) return;
3307
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
3308
+ const ownerType = await getAccountType(
3309
+ userAddress,
3310
+ chainConfig.publicClient
3311
+ );
3312
+ if (ownerType !== "Safe") return;
3313
+ await assertParentSafeDeployedOnChain(
3314
+ userAddress,
3315
+ chainConfig.publicClient,
3316
+ chainId
3317
+ );
3318
+ const childAddress = await this.getSafeAddressFor(userAddress, chainId);
3319
+ if (!childAddress) {
3320
+ throw new Error("Child smart wallet address is not available");
3321
+ }
3322
+ const childDeployed = await isSafeDeployed(
3323
+ childAddress,
3324
+ chainConfig.publicClient
3325
+ );
3326
+ if (!childDeployed) {
3327
+ await this.deploySafe(userAddress, chainId, strategy, true);
3328
+ return;
3329
+ }
3330
+ console.info(
3331
+ `[ZyfaiSDK] nested deposit signing pending enable only chainId=${chainId} owner=${userAddress} sessionActive=${this.hasActiveSessionKey}`
3332
+ );
3333
+ await deploySafeAccount({
3334
+ owner: this.getWalletClient(chainId),
3335
+ safeOwnerAddress: userAddress,
3336
+ chain: chainConfig.chain,
3337
+ publicClient: chainConfig.publicClient,
3338
+ chainId,
3339
+ httpClient: this.httpClient
3340
+ });
3341
+ if (!this.hasActiveSessionKey) {
3342
+ await this.createSessionKey(userAddress, chainId);
3343
+ }
3344
+ }
2892
3345
  async hydrateSessionWallet() {
2893
3346
  if (this.predeployedResolved || !this.sessionEoa) return;
2894
3347
  const me = await this.httpClient.get(ENDPOINTS.USER_ME);
@@ -2973,9 +3426,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2973
3426
  /**
2974
3427
  * Deploy Safe Smart Wallet for a user
2975
3428
  *
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.
3429
+ * Not needed for a predeployed (pool) wallet: {@link ZyfaiSDK.sendDeposit} deploys the Safe and
3430
+ * enables the agent session on first deposit. Required for an owner that is not predeployed —
3431
+ * a contract owner such as a nested Safe, or a legacy self-deployed wallet — where `sendDeposit`
3432
+ * calls this method internally.
2979
3433
  *
2980
3434
  * @see {@link ZyfaiSDK.sendDeposit}
2981
3435
  *
@@ -2989,16 +3443,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2989
3443
  *
2990
3444
  * @example
2991
3445
  * ```typescript
2992
- * // Preferred: sendDeposit handles predeployed wallet onboarding
3446
+ * // Preferred: sendDeposit handles onboarding for every owner type
2993
3447
  * const sent = await sdk.sendDeposit(userAddress, 8453, amount, "USDC");
2994
3448
  * await sdk.waitForDepositCredit(sent.registration.id, 8453);
2995
3449
  *
2996
- * // Legacy: deploy with default conservative strategy
3450
+ * // Explicit: deploy with default conservative strategy
2997
3451
  * await sdk.deploySafe(userAddress, 8453);
2998
3452
  * ```
2999
3453
  */
3000
3454
  async deploySafe(userAddress, chainId, strategy, createSessionKey) {
3001
- this.warnDeprecatedOnboardingMethod("deploySafe");
3002
3455
  try {
3003
3456
  if (!userAddress) {
3004
3457
  throw new Error("User address is required");
@@ -3007,6 +3460,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3007
3460
  throw new Error(`Unsupported chain ID: ${chainId}`);
3008
3461
  }
3009
3462
  await this.authenticateUser();
3463
+ this.warnPredeployedOnboardingMethod("deploySafe");
3010
3464
  if (this.isPredeployed && this.isConnectedUser(userAddress)) {
3011
3465
  const predeployedAddress = await this.getSafeAddressFor(
3012
3466
  userAddress,
@@ -3036,16 +3490,28 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3036
3490
  }
3037
3491
  const walletClient = this.getWalletClient(chainId);
3038
3492
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
3039
- const safeAddress = await getDeterministicSafeAddress({
3040
- safeOwnerAddress: userAddress,
3041
- chain: chainConfig.chain,
3042
- publicClient: chainConfig.publicClient
3043
- });
3493
+ const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
3494
+ if (!safeAddress) {
3495
+ throw new Error("Smart wallet address is not available");
3496
+ }
3044
3497
  const alreadyDeployed = await isSafeDeployed(
3045
3498
  safeAddress,
3046
3499
  chainConfig.publicClient
3047
3500
  );
3048
3501
  if (alreadyDeployed) {
3502
+ let enableTxHash = "0x0";
3503
+ if (!this.isPredeployed) {
3504
+ const enabled = await deploySafeAccount({
3505
+ owner: walletClient,
3506
+ safeOwnerAddress: userAddress,
3507
+ chain: chainConfig.chain,
3508
+ publicClient: chainConfig.publicClient,
3509
+ chainId,
3510
+ httpClient: this.httpClient,
3511
+ strategy: strategy ? toInternalStrategy(strategy) : "safe_strategy"
3512
+ });
3513
+ enableTxHash = enabled.txHash || "0x0";
3514
+ }
3049
3515
  await this.updateUserProtocols(strategy);
3050
3516
  let sessionKeyCreated2 = false;
3051
3517
  if (createSessionKey) {
@@ -3062,7 +3528,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3062
3528
  return {
3063
3529
  success: true,
3064
3530
  safeAddress,
3065
- txHash: "0x0",
3531
+ txHash: enableTxHash,
3066
3532
  status: "deployed",
3067
3533
  sessionKeyCreated: sessionKeyCreated2
3068
3534
  };
@@ -3087,6 +3553,17 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3087
3553
  );
3088
3554
  }
3089
3555
  await this.updateUserProtocols(strategy);
3556
+ if (!this.isPredeployed) {
3557
+ await deploySafeAccount({
3558
+ owner: walletClient,
3559
+ safeOwnerAddress: userAddress,
3560
+ chain: chainConfig.chain,
3561
+ publicClient: chainConfig.publicClient,
3562
+ chainId,
3563
+ httpClient: this.httpClient,
3564
+ strategy: internalStrategy
3565
+ });
3566
+ }
3090
3567
  let sessionKeyCreated = false;
3091
3568
  if (createSessionKey) {
3092
3569
  try {
@@ -3108,18 +3585,17 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3108
3585
  };
3109
3586
  } catch (error) {
3110
3587
  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
- );
3588
+ throw new Error(`Safe deployment failed: ${error.message}`);
3114
3589
  }
3115
3590
  }
3116
3591
  /**
3117
3592
  * Create session key with auto-fetched configuration from Zyfai API
3118
3593
  * This is the simplified method that automatically fetches session configuration
3119
3594
  *
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.
3595
+ * Not needed for a predeployed (pool) wallet: its agent session is already enabled on-chain and
3596
+ * {@link ZyfaiSDK.sendDeposit} records it after the first deposit. Required for an owner that is
3597
+ * not predeployed — a contract owner such as a nested Safe, or a legacy self-deployed wallet —
3598
+ * where `sendDeposit` calls this method internally.
3123
3599
  *
3124
3600
  * @see {@link ZyfaiSDK.sendDeposit}
3125
3601
  *
@@ -3131,18 +3607,18 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3131
3607
  *
3132
3608
  * @example
3133
3609
  * ```typescript
3134
- * // Preferred: sendDeposit handles session onboarding for predeployed wallets
3610
+ * // Preferred: sendDeposit handles session onboarding for every owner type
3135
3611
  * const sent = await sdk.sendDeposit(userAddress, 8453, amount, "USDC");
3136
3612
  * await sdk.waitForDepositCredit(sent.registration.id, 8453);
3137
3613
  *
3138
- * // Legacy:
3614
+ * // Explicit:
3139
3615
  * const result = await sdk.createSessionKey(userAddress, 8453);
3140
3616
  * ```
3141
3617
  */
3142
3618
  async createSessionKey(userAddress, chainId) {
3143
- this.warnDeprecatedOnboardingMethod("createSessionKey");
3144
3619
  try {
3145
3620
  await this.authenticateUser();
3621
+ this.warnPredeployedOnboardingMethod("createSessionKey");
3146
3622
  if (!this.authenticatedUserId) {
3147
3623
  throw new Error(
3148
3624
  "User ID not available. Please ensure authentication completed successfully."
@@ -3187,6 +3663,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3187
3663
  userAddress,
3188
3664
  chainConfig.publicClient
3189
3665
  );
3666
+ if (accountType === "Safe") {
3667
+ await this.assertOwnerSafeOnSessionChains(
3668
+ userAddress,
3669
+ sessions
3670
+ );
3671
+ }
3190
3672
  const signingParams = {
3191
3673
  permitGenericPolicy,
3192
3674
  ignoreSecurityAttestations: accountType === "Safe"
@@ -3214,7 +3696,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3214
3696
  };
3215
3697
  } catch (error) {
3216
3698
  throw new Error(
3217
- `Failed to create session key: ${error.message}. createSessionKey() is deprecated \u2014 prefer sendDeposit() for predeployed wallet onboarding.`
3699
+ `Failed to create session key: ${error.message}`
3218
3700
  );
3219
3701
  }
3220
3702
  }
@@ -3222,6 +3704,35 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3222
3704
  * Internal method to sign session key
3223
3705
  * @private
3224
3706
  */
3707
+ /**
3708
+ * A nested Safe owner signs one MultiChainSession covering every chain in the
3709
+ * session configuration, and the child validates that signature against the
3710
+ * owner through ERC-1271 on each of them. A chain where the owner has no code
3711
+ * would accept the signature nowhere, so refuse rather than sign it.
3712
+ *
3713
+ * The session list is not filtered here: the execution API rebuilds the digest
3714
+ * from its own configuration, so dropping a chain client-side would change the
3715
+ * hash and the signature would be rejected everywhere.
3716
+ * @private
3717
+ */
3718
+ async assertOwnerSafeOnSessionChains(ownerAddress, sessions) {
3719
+ const chainIds = [
3720
+ ...new Set(sessions.map((session) => Number(session.chainId)))
3721
+ ].filter(isSupportedChain);
3722
+ const missing = [];
3723
+ await Promise.all(
3724
+ chainIds.map(async (id) => {
3725
+ const { publicClient } = getChainConfig(id, this.rpcUrls);
3726
+ const code = await publicClient.getCode({ address: ownerAddress });
3727
+ if (!code || code === "0x") missing.push(id);
3728
+ })
3729
+ );
3730
+ if (missing.length > 0) {
3731
+ throw new Error(
3732
+ `Owner Safe ${ownerAddress} has no code on chain(s) ${missing.sort((a, b) => a - b).join(", ")} covered by the session configuration. Deploy the Safe there, or restrict the user's chains, before signing the session.`
3733
+ );
3734
+ }
3735
+ }
3225
3736
  async signSessionKey(userAddress, chainId, sessions, signingParams) {
3226
3737
  try {
3227
3738
  if (!userAddress) {
@@ -3235,14 +3746,13 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3235
3746
  }
3236
3747
  const walletClient = this.getWalletClient();
3237
3748
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
3238
- const accountType = await getAccountType(
3749
+ await this.hydrateSessionWallet();
3750
+ const childSafeAddress = await this.getSafeAddressFor(
3239
3751
  userAddress,
3240
- chainConfig.publicClient
3752
+ chainId
3241
3753
  );
3242
- if (accountType !== "EOA") {
3243
- throw new Error(
3244
- `Invalid account type for ${userAddress}. Must be an EOA.`
3245
- );
3754
+ if (!childSafeAddress) {
3755
+ throw new Error("Child smart wallet address is not available");
3246
3756
  }
3247
3757
  const sessionChainIds = [
3248
3758
  ...new Set(sessions.map((s) => Number(s.chainId)))
@@ -3252,6 +3762,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3252
3762
  {
3253
3763
  owner: walletClient,
3254
3764
  safeOwnerAddress: userAddress,
3765
+ childSafeAddress,
3255
3766
  chain: chainConfig.chain,
3256
3767
  publicClient: chainConfig.publicClient
3257
3768
  },
@@ -3743,6 +4254,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3743
4254
  throw new Error("Smart wallet address is not available");
3744
4255
  }
3745
4256
  const amountBigInt = BigInt(amount);
4257
+ const ownerType = await getAccountType(
4258
+ userAddress,
4259
+ chainConfig.publicClient
4260
+ );
4261
+ if (ownerType !== "EOA" && ownerType !== "Safe") {
4262
+ throw new Error(
4263
+ `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.`
4264
+ );
4265
+ }
3746
4266
  const [isDeployed, currentSafeBalance] = await Promise.all([
3747
4267
  isSafeDeployed(safeAddress, chainConfig.publicClient),
3748
4268
  minRequired !== void 0 ? chainConfig.publicClient.readContract({
@@ -3754,7 +4274,18 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3754
4274
  this.prepareFirstDeposit(strategy)
3755
4275
  ]).then(([deployed, balance]) => [deployed, balance]);
3756
4276
  if (!isDeployed) {
3757
- if (!(this.isPredeployed && this.isConnectedUser(userAddress))) {
4277
+ if (ownerType === "Safe" && !this.isPredeployed) {
4278
+ await assertParentSafeDeployedOnChain(
4279
+ userAddress,
4280
+ chainConfig.publicClient,
4281
+ chainId
4282
+ );
4283
+ await this.ensureNestedOwnerReadyForDeposit(
4284
+ userAddress,
4285
+ chainId,
4286
+ strategy
4287
+ );
4288
+ } else if (!(this.isPredeployed && this.isConnectedUser(userAddress))) {
3758
4289
  throw new Error(
3759
4290
  `Safe not available for ${userAddress} on chain ${chainId}.`
3760
4291
  );
@@ -3777,16 +4308,74 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3777
4308
  );
3778
4309
  }
3779
4310
  }
4311
+ if (ownerType === "Safe" && isDeployed) {
4312
+ await assertParentSafeDeployedOnChain(
4313
+ userAddress,
4314
+ chainConfig.publicClient,
4315
+ chainId
4316
+ );
4317
+ await this.ensureNestedOwnerReadyForDeposit(
4318
+ userAddress,
4319
+ chainId,
4320
+ strategy
4321
+ );
4322
+ }
3780
4323
  if (allowPermit && this.isPredeployed && this.isConnectedUser(userAddress)) {
3781
4324
  const sponsored = await this.sendFirstPermitDeposit({
3782
- owner: getAddress2(userAddress),
4325
+ owner: getAddress4(userAddress),
3783
4326
  safe: safeAddress,
3784
4327
  chainId,
3785
- token: getAddress2(token),
4328
+ token: getAddress4(token),
3786
4329
  amount: amountBigInt
3787
4330
  });
3788
4331
  if (sponsored) return sponsored;
3789
4332
  }
4333
+ if (ownerType === "Safe") {
4334
+ const since = new Date(Date.now() - NESTED_SAFE_RESUME_WINDOW_MS);
4335
+ const inFlight = await findSafeTransferProposal({
4336
+ parentSafe: userAddress,
4337
+ childSafe: safeAddress,
4338
+ chainId,
4339
+ tokenAddress: token,
4340
+ amount: amountBigInt,
4341
+ since
4342
+ });
4343
+ let safeTxHash = inFlight?.safeTxHash;
4344
+ if (!inFlight) {
4345
+ const proposed = await walletClient.writeContract({
4346
+ address: token,
4347
+ abi: erc20TransferWriteAbi(assetSymbol),
4348
+ functionName: "transfer",
4349
+ args: [safeAddress, amountBigInt],
4350
+ chain: chainConfig.chain,
4351
+ account: walletClient.account
4352
+ });
4353
+ safeTxHash = (await findSafeTransferByHash({ chainId, safeTxHash: proposed }))?.safeTxHash;
4354
+ }
4355
+ const executedHash = inFlight?.isExecuted && inFlight.transactionHash ? inFlight.transactionHash : await waitForSafeTransferExecution({
4356
+ parentSafe: userAddress,
4357
+ childSafe: safeAddress,
4358
+ chainId,
4359
+ tokenAddress: token,
4360
+ amount: amountBigInt,
4361
+ safeTxHash,
4362
+ since
4363
+ });
4364
+ const registration2 = await this.registerDeposit(
4365
+ chainId,
4366
+ executedHash,
4367
+ amount,
4368
+ token
4369
+ );
4370
+ return {
4371
+ success: true,
4372
+ txHash: executedHash,
4373
+ smartWallet: safeAddress,
4374
+ amount: amountBigInt.toString(),
4375
+ route: "direct",
4376
+ registration: registration2
4377
+ };
4378
+ }
3790
4379
  const txHash = await walletClient.writeContract({
3791
4380
  address: token,
3792
4381
  abi: erc20TransferWriteAbi(assetSymbol),
@@ -3839,7 +4428,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3839
4428
  * ```
3840
4429
  */
3841
4430
  async getFirstPermitDepositStatus(userAddress) {
3842
- if (!this.sessionEoa || !isAddressEqual2(getAddress2(userAddress), this.sessionEoa)) {
4431
+ if (!this.sessionEoa || !isAddressEqual2(getAddress4(userAddress), this.sessionEoa)) {
3843
4432
  throw new Error("userAddress does not match authenticated session EOA");
3844
4433
  }
3845
4434
  return (await this.getFirstPermitDepositAvailability()).intent;
@@ -4524,7 +5113,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4524
5113
  if (!userAddress) {
4525
5114
  throw new Error("A user address is required");
4526
5115
  }
4527
- const owner = getAddress2(userAddress);
5116
+ const owner = getAddress4(userAddress);
4528
5117
  const chainId = 8453;
4529
5118
  await this.hydrateSessionWallet();
4530
5119
  const safe = await this.getSafeAddressFor(owner, chainId);
@@ -4546,7 +5135,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4546
5135
  ]).catch(() => {
4547
5136
  throw new Error(`Safe ${safe} is not deployed on Base`);
4548
5137
  });
4549
- if (threshold !== 1n || !owners.some((o) => getAddress2(o) === owner)) {
5138
+ if (threshold !== 1n || !owners.some((o) => getAddress4(o) === owner)) {
4550
5139
  throw new Error(
4551
5140
  `${owner} cannot execute Safe ${safe} alone (not an owner, or threshold above 1)`
4552
5141
  );
@@ -4635,7 +5224,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4635
5224
  if (!userAddress) {
4636
5225
  throw new Error("A user address is required");
4637
5226
  }
4638
- if (this.sessionEoa && getAddress2(userAddress) !== this.sessionEoa) {
5227
+ if (this.sessionEoa && getAddress4(userAddress) !== this.sessionEoa) {
4639
5228
  throw new Error("userAddress does not match authenticated session EOA");
4640
5229
  }
4641
5230
  }
@@ -4781,7 +5370,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4781
5370
  */
4782
5371
  async prepareDeposit(params) {
4783
5372
  const { userAddress, chainId, amount, asset } = params;
4784
- if (this.sessionEoa && getAddress2(userAddress) !== this.sessionEoa) {
5373
+ if (this.sessionEoa && getAddress4(userAddress) !== this.sessionEoa) {
4785
5374
  throw new Error("userAddress does not match authenticated session EOA");
4786
5375
  }
4787
5376
  const setup = await this.ensureDepositProfileForPrepare({
@@ -7378,7 +7967,7 @@ function hashV1SessionEnable(chainSessions) {
7378
7967
 
7379
7968
  // src/utils/userop-verification.ts
7380
7969
  import {
7381
- concat,
7970
+ concat as concat2,
7382
7971
  decodeAbiParameters,
7383
7972
  decodeFunctionData,
7384
7973
  encodeAbiParameters,
@@ -7448,8 +8037,8 @@ function parseUserOperationJson(json) {
7448
8037
  }
7449
8038
  var uint128 = (value) => numberToHex(value, { size: 16 });
7450
8039
  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([
8040
+ const initCode = userOp.factory ? concat2([userOp.factory, userOp.factoryData ?? "0x"]) : "0x";
8041
+ const paymasterAndData = userOp.paymaster ? concat2([
7453
8042
  userOp.paymaster,
7454
8043
  uint128(userOp.paymasterVerificationGasLimit ?? 0n),
7455
8044
  uint128(userOp.paymasterPostOpGasLimit ?? 0n),
@@ -7471,9 +8060,9 @@ function hashUserOperationV07(userOp, chainId, entryPoint = ENTRY_POINT_V07_ADDR
7471
8060
  userOp.nonce,
7472
8061
  keccak256(initCode),
7473
8062
  keccak256(userOp.callData),
7474
- concat([uint128(userOp.verificationGasLimit), uint128(userOp.callGasLimit)]),
8063
+ concat2([uint128(userOp.verificationGasLimit), uint128(userOp.callGasLimit)]),
7475
8064
  userOp.preVerificationGas,
7476
- concat([uint128(userOp.maxPriorityFeePerGas), uint128(userOp.maxFeePerGas)]),
8065
+ concat2([uint128(userOp.maxPriorityFeePerGas), uint128(userOp.maxFeePerGas)]),
7477
8066
  keccak256(paymasterAndData)
7478
8067
  ]
7479
8068
  );
@@ -7685,6 +8274,385 @@ function createBankrProvider(config) {
7685
8274
  };
7686
8275
  return provider;
7687
8276
  }
8277
+
8278
+ // src/providers/safe-owner.ts
8279
+ import {
8280
+ createPublicClient as createPublicClient2,
8281
+ createWalletClient as createWalletClient2,
8282
+ encodeAbiParameters as encodeAbiParameters2,
8283
+ encodeFunctionData as encodeFunctionData3,
8284
+ getAddress as getAddress5,
8285
+ hashMessage as hashMessage2,
8286
+ hashTypedData as hashTypedData2,
8287
+ hexToSignature,
8288
+ http as http3,
8289
+ isAddress as isAddress3,
8290
+ parseAbi as parseAbi3,
8291
+ signatureToHex,
8292
+ stringToHex
8293
+ } from "viem";
8294
+ var EIP1271_MAGIC_VALUE = "0x1626ba7e";
8295
+ var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
8296
+ var SAFE_ABI2 = parseAbi3([
8297
+ "function getThreshold() view returns (uint256)",
8298
+ "function getOwners() view returns (address[])",
8299
+ "function nonce() view returns (uint256)",
8300
+ "function getMessageHash(bytes message) view returns (bytes32)",
8301
+ "function getTransactionHash(address to, uint256 value, bytes data, uint8 operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce) view returns (bytes32)",
8302
+ "function execTransaction(address to, uint256 value, bytes data, uint8 operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, bytes signatures) payable returns (bool)",
8303
+ "function isValidSignature(bytes32 _dataHash, bytes _signature) view returns (bytes4)"
8304
+ ]);
8305
+ async function createSafeOwnerProvider(config) {
8306
+ if (!isAddress3(config.safeAddress)) {
8307
+ throw new Error("safeAddress must be an Ethereum address");
8308
+ }
8309
+ const safeAddress = getAddress5(config.safeAddress);
8310
+ const publicClient = createPublicClient2({
8311
+ chain: config.chain,
8312
+ transport: http3()
8313
+ });
8314
+ const ownerWallet = await resolveOwnerWallet(config.owner, config.chain);
8315
+ const code = await publicClient.getCode({ address: safeAddress });
8316
+ if (!code || code === "0x") {
8317
+ throw new Error(
8318
+ `Safe ${safeAddress} has no code on chain ${config.chain.id}`
8319
+ );
8320
+ }
8321
+ const [threshold, owners] = await Promise.all([
8322
+ publicClient.readContract({
8323
+ address: safeAddress,
8324
+ abi: SAFE_ABI2,
8325
+ functionName: "getThreshold"
8326
+ }),
8327
+ publicClient.readContract({
8328
+ address: safeAddress,
8329
+ abi: SAFE_ABI2,
8330
+ functionName: "getOwners"
8331
+ })
8332
+ ]);
8333
+ if (threshold !== 1n) {
8334
+ throw new Error(
8335
+ `Safe ${safeAddress} threshold is ${threshold.toString()}. createSafeOwnerProvider can execute only a threshold-1 Safe. For a multisig such as 2-of-4, connect the Safe with WalletConnect or the Safe App and pass that provider to connectAccount. sendDeposit waits while the other owners confirm.`
8336
+ );
8337
+ }
8338
+ const ownerAddress = ownerWallet.address;
8339
+ if (!owners.some((owner) => getAddress5(owner) === ownerAddress)) {
8340
+ throw new Error(`${ownerAddress} is not an owner of Safe ${safeAddress}`);
8341
+ }
8342
+ const signSafeDigest = async (dataHash) => {
8343
+ const encoded = encodeAbiParameters2([{ type: "bytes32" }], [dataHash]);
8344
+ const messageHash = await publicClient.readContract({
8345
+ address: safeAddress,
8346
+ abi: SAFE_ABI2,
8347
+ functionName: "getMessageHash",
8348
+ args: [encoded]
8349
+ });
8350
+ return ownerWallet.signHash(messageHash);
8351
+ };
8352
+ const probeHash = hashMessage2("zyfai safe owner");
8353
+ const probeSignature = await signSafeDigest(probeHash);
8354
+ const magic = await publicClient.readContract({
8355
+ address: safeAddress,
8356
+ abi: SAFE_ABI2,
8357
+ functionName: "isValidSignature",
8358
+ args: [probeHash, probeSignature]
8359
+ });
8360
+ if (magic.toLowerCase() !== EIP1271_MAGIC_VALUE) {
8361
+ throw new Error(
8362
+ `Safe ${safeAddress} rejected the owner signature (isValidSignature returned ${magic})`
8363
+ );
8364
+ }
8365
+ const executeFromSafe = async (tx) => {
8366
+ const nonce = await publicClient.readContract({
8367
+ address: safeAddress,
8368
+ abi: SAFE_ABI2,
8369
+ functionName: "nonce"
8370
+ });
8371
+ const safeTxHash = await publicClient.readContract({
8372
+ address: safeAddress,
8373
+ abi: SAFE_ABI2,
8374
+ functionName: "getTransactionHash",
8375
+ args: [
8376
+ tx.to,
8377
+ tx.value,
8378
+ tx.data,
8379
+ 0,
8380
+ 0n,
8381
+ 0n,
8382
+ 0n,
8383
+ ZERO_ADDRESS,
8384
+ ZERO_ADDRESS,
8385
+ nonce
8386
+ ]
8387
+ });
8388
+ const signature = await ownerWallet.signHash(safeTxHash);
8389
+ const data = encodeFunctionData3({
8390
+ abi: SAFE_ABI2,
8391
+ functionName: "execTransaction",
8392
+ args: [
8393
+ tx.to,
8394
+ tx.value,
8395
+ tx.data,
8396
+ 0,
8397
+ 0n,
8398
+ 0n,
8399
+ 0n,
8400
+ ZERO_ADDRESS,
8401
+ ZERO_ADDRESS,
8402
+ signature
8403
+ ]
8404
+ });
8405
+ const hash = await ownerWallet.sendTransaction({
8406
+ to: safeAddress,
8407
+ data,
8408
+ value: 0n
8409
+ });
8410
+ const receipt = await publicClient.waitForTransactionReceipt({ hash });
8411
+ if (receipt.status !== "success") {
8412
+ throw new Error(`Safe transaction reverted: ${hash}`);
8413
+ }
8414
+ return hash;
8415
+ };
8416
+ return {
8417
+ async request({ method, params }) {
8418
+ if (method === "eth_requestAccounts" || method === "eth_accounts") {
8419
+ return [safeAddress];
8420
+ }
8421
+ if (method === "personal_sign" || method === "eth_sign") {
8422
+ return signSafeDigest(personalSignDigest(params));
8423
+ }
8424
+ if (method === "eth_signTypedData_v4" || method === "eth_signTypedData") {
8425
+ return signSafeDigest(typedDataDigest(params));
8426
+ }
8427
+ if (method === "eth_sendTransaction" || method === "wallet_sendTransaction") {
8428
+ return executeFromSafe(readSafeTransaction(params));
8429
+ }
8430
+ return publicClient.request({
8431
+ method,
8432
+ params: params ?? []
8433
+ });
8434
+ }
8435
+ };
8436
+ }
8437
+ async function resolveOwnerWallet(owner, chain) {
8438
+ if (isHashSigner(owner)) {
8439
+ const address = getAddress5(owner.address);
8440
+ const wallet = createWalletClient2({
8441
+ account: owner,
8442
+ chain,
8443
+ transport: http3()
8444
+ });
8445
+ return {
8446
+ address,
8447
+ signHash: (hash) => owner.sign({ hash }),
8448
+ signTypedData: (params) => signAccountTypedData(owner, params),
8449
+ sendTransaction: (tx) => wallet.sendTransaction({
8450
+ account: owner,
8451
+ chain,
8452
+ to: tx.to,
8453
+ data: tx.data,
8454
+ value: tx.value
8455
+ })
8456
+ };
8457
+ }
8458
+ if (isWalletClient(owner)) {
8459
+ const address = await walletClientAddress(owner);
8460
+ return {
8461
+ address,
8462
+ signHash: (hash) => signOwnerHash(looseRequest(owner.request), owner.account, address, hash),
8463
+ signTypedData: (params) => {
8464
+ const { domain, types, primaryType, message } = parseTypedDataPayload(params);
8465
+ return owner.signTypedData({
8466
+ account: owner.account ?? address,
8467
+ domain,
8468
+ types,
8469
+ primaryType,
8470
+ message
8471
+ });
8472
+ },
8473
+ sendTransaction: (tx) => owner.sendTransaction({
8474
+ account: owner.account ?? address,
8475
+ chain: owner.chain ?? chain,
8476
+ to: tx.to,
8477
+ data: tx.data,
8478
+ value: tx.value
8479
+ })
8480
+ };
8481
+ }
8482
+ if (isEip1193(owner)) {
8483
+ const address = await eip1193Address(owner);
8484
+ return {
8485
+ address,
8486
+ signHash: (hash) => signOwnerHash(looseRequest(owner.request), void 0, address, hash),
8487
+ signTypedData: async (params) => {
8488
+ const { requestPayload } = parseTypedDataPayload(params);
8489
+ const signature = await owner.request({
8490
+ method: "eth_signTypedData_v4",
8491
+ params: [address, JSON.stringify(requestPayload)]
8492
+ });
8493
+ if (typeof signature !== "string" || !signature.startsWith("0x")) {
8494
+ throw new Error("Owner wallet did not return a typed-data signature");
8495
+ }
8496
+ return signature;
8497
+ },
8498
+ sendTransaction: async (tx) => {
8499
+ const hash = await owner.request({
8500
+ method: "eth_sendTransaction",
8501
+ params: [
8502
+ {
8503
+ from: address,
8504
+ to: tx.to,
8505
+ data: tx.data,
8506
+ value: tx.value === 0n ? "0x0" : `0x${tx.value.toString(16)}`
8507
+ }
8508
+ ]
8509
+ });
8510
+ if (typeof hash !== "string" || !hash.startsWith("0x")) {
8511
+ throw new Error("Owner wallet did not return a transaction hash");
8512
+ }
8513
+ return hash;
8514
+ }
8515
+ };
8516
+ }
8517
+ throw new Error(
8518
+ "owner must be a viem wallet client, an account that can sign hashes, or an EIP-1193 provider"
8519
+ );
8520
+ }
8521
+ function isWalletClient(owner) {
8522
+ return typeof owner === "object" && owner !== null && "transport" in owner && "sendTransaction" in owner && typeof owner.sendTransaction === "function";
8523
+ }
8524
+ function isHashSigner(owner) {
8525
+ return typeof owner === "object" && owner !== null && "address" in owner && "sign" in owner && typeof owner.sign === "function" && !("transport" in owner);
8526
+ }
8527
+ function isEip1193(owner) {
8528
+ return typeof owner === "object" && owner !== null && "request" in owner && typeof owner.request === "function" && !("transport" in owner) && !isHashSigner(owner);
8529
+ }
8530
+ function looseRequest(request) {
8531
+ return request;
8532
+ }
8533
+ async function walletClientAddress(owner) {
8534
+ if (owner.account?.address && isAddress3(owner.account.address)) {
8535
+ return getAddress5(owner.account.address);
8536
+ }
8537
+ return requestAccount(looseRequest(owner.request));
8538
+ }
8539
+ async function eip1193Address(owner) {
8540
+ return requestAccount(looseRequest(owner.request));
8541
+ }
8542
+ async function requestAccount(request) {
8543
+ const accounts = await request({ method: "eth_requestAccounts" });
8544
+ const first = Array.isArray(accounts) ? accounts[0] : void 0;
8545
+ if (typeof first !== "string" || !isAddress3(first)) {
8546
+ throw new Error("Owner wallet did not return an account");
8547
+ }
8548
+ return getAddress5(first);
8549
+ }
8550
+ async function signOwnerHash(request, account, address, hash) {
8551
+ if (account?.sign) {
8552
+ return account.sign({ hash });
8553
+ }
8554
+ const signature = await request({
8555
+ method: "personal_sign",
8556
+ params: [hash, address]
8557
+ });
8558
+ if (typeof signature !== "string" || !signature.startsWith("0x")) {
8559
+ throw new Error("Owner wallet did not return a signature");
8560
+ }
8561
+ return asSafeEthSign(signature);
8562
+ }
8563
+ function asSafeEthSign(signature) {
8564
+ const sig = hexToSignature(signature);
8565
+ const current = sig.v === void 0 ? sig.yParity === 1 ? 28 : 27 : Number(sig.v);
8566
+ const v = current >= 27 ? current + 4 : current + 31;
8567
+ return signatureToHex({ r: sig.r, s: sig.s, v: BigInt(v) });
8568
+ }
8569
+ function personalSignDigest(params) {
8570
+ const [first, second] = params ?? [];
8571
+ const message = typeof first === "string" && isAddress3(first) ? second : first;
8572
+ const hex = typeof message === "string" && message.startsWith("0x") ? message : stringToHex(String(message ?? ""));
8573
+ return hashMessage2({ raw: hex });
8574
+ }
8575
+ function parseTypedDataPayload(params) {
8576
+ const [first, second] = params ?? [];
8577
+ const payload = typeof first === "string" && isAddress3(first) ? second : first;
8578
+ const parsed = typeof payload === "string" ? JSON.parse(payload) : payload;
8579
+ const types = { ...parsed.types };
8580
+ delete types.EIP712Domain;
8581
+ const domain = { ...parsed.domain ?? {} };
8582
+ if (typeof domain.chainId === "string") {
8583
+ domain.chainId = BigInt(domain.chainId);
8584
+ }
8585
+ const message = coerceEip712Value(
8586
+ parsed.primaryType,
8587
+ parsed.message,
8588
+ types
8589
+ );
8590
+ return {
8591
+ domain,
8592
+ types,
8593
+ primaryType: parsed.primaryType,
8594
+ message,
8595
+ requestPayload: parsed
8596
+ };
8597
+ }
8598
+ function typedDataDigest(params) {
8599
+ const { domain, types, primaryType, message } = parseTypedDataPayload(params);
8600
+ return hashTypedData2({ domain, types, primaryType, message });
8601
+ }
8602
+ async function signAccountTypedData(account, params) {
8603
+ const { domain, types, primaryType, message } = parseTypedDataPayload(params);
8604
+ if (!account.signTypedData) {
8605
+ throw new Error("Owner account cannot sign typed data");
8606
+ }
8607
+ return account.signTypedData({
8608
+ domain,
8609
+ types,
8610
+ primaryType,
8611
+ message
8612
+ });
8613
+ }
8614
+ function coerceEip712Value(type, value, types) {
8615
+ if (value == null) return value;
8616
+ const array = type.match(/^(.*)\[(\d*)\]$/);
8617
+ if (array) {
8618
+ if (!Array.isArray(value)) return value;
8619
+ return value.map((item) => coerceEip712Value(array[1], item, types));
8620
+ }
8621
+ const struct = types[type];
8622
+ if (struct) {
8623
+ if (typeof value !== "object" || Array.isArray(value)) return value;
8624
+ const record = value;
8625
+ const next = {};
8626
+ for (const field of struct) {
8627
+ next[field.name] = coerceEip712Value(
8628
+ field.type,
8629
+ record[field.name],
8630
+ types
8631
+ );
8632
+ }
8633
+ return next;
8634
+ }
8635
+ if (/^u?int\d*$/.test(type)) {
8636
+ if (typeof value === "bigint") return value;
8637
+ if (typeof value === "string" || typeof value === "number") {
8638
+ return BigInt(value);
8639
+ }
8640
+ }
8641
+ return value;
8642
+ }
8643
+ function readSafeTransaction(params) {
8644
+ const tx = Array.isArray(params) ? params[0] : void 0;
8645
+ if (!tx?.to || !isAddress3(tx.to)) {
8646
+ throw new Error("Safe transaction is missing a destination");
8647
+ }
8648
+ const data = typeof tx.data === "string" && tx.data.startsWith("0x") ? tx.data : "0x";
8649
+ let value = 0n;
8650
+ if (typeof tx.value === "bigint") value = tx.value;
8651
+ else if (typeof tx.value === "number" || typeof tx.value === "string") {
8652
+ value = BigInt(tx.value);
8653
+ }
8654
+ return { to: getAddress5(tx.to), data, value };
8655
+ }
7688
8656
  export {
7689
8657
  ALLOWED_HISTORY_DAYS,
7690
8658
  API_ENDPOINT,
@@ -7717,6 +8685,7 @@ export {
7717
8685
  ZyfaiSDK,
7718
8686
  buildV1ChainSessions,
7719
8687
  createBankrProvider,
8688
+ createSafeOwnerProvider,
7720
8689
  decodeUserOperationCalls,
7721
8690
  getChainConfig,
7722
8691
  getDataApiBaseUrl,