anymal-protocol 1.0.118 → 1.0.120

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
@@ -24,6 +24,8 @@ __export(index_exports, {
24
24
  ActionSourceType: () => ActionSourceType,
25
25
  ActionStatus: () => ActionStatus,
26
26
  ActionType: () => ActionType,
27
+ FIREBASE_WEB_API_KEYS: () => FIREBASE_WEB_API_KEYS,
28
+ FIREBASE_WEB_AUTH_API_ENDPOINTS: () => FIREBASE_WEB_AUTH_API_ENDPOINTS,
27
29
  MarketplacePaymentType: () => MarketplacePaymentType,
28
30
  NETWORK_HOSTS: () => NETWORK_HOSTS,
29
31
  Network: () => Network,
@@ -31,12 +33,20 @@ __export(index_exports, {
31
33
  convertToActionRecord: () => convertToActionRecord,
32
34
  convertToMultipleActionDefinitions: () => convertToMultipleActionDefinitions,
33
35
  convertToMultipleActionRecords: () => convertToMultipleActionRecords,
36
+ createApp: () => createApp,
34
37
  createAuthEnvelope: () => createAuthEnvelope,
35
38
  fetchAnymals: () => fetchAnymals,
39
+ flattenFirestoreData: () => flattenFirestoreData,
36
40
  generateAppSignature: () => generateAppSignature,
37
41
  generateBytes32Nonce: () => generateBytes32Nonce,
38
42
  generateJWT: () => generateJWT,
43
+ getFirebaseTokenForApp: () => getFirebaseTokenForApp,
39
44
  loadExistingSecp256k1PrivateKey: () => loadExistingSecp256k1PrivateKey,
45
+ processDirectKibbleApproval: () => processDirectKibbleApproval,
46
+ processDirectPartialPayment: () => processDirectPartialPayment,
47
+ processOrgKibbleApproval: () => processOrgKibbleApproval,
48
+ processOrgPartialPayment: () => processOrgPartialPayment,
49
+ sendUserOpWithRetries: () => sendUserOpWithRetries,
40
50
  serializePublicKeyCompressed: () => serializePublicKeyCompressed,
41
51
  submitAction: () => submitAction,
42
52
  useAddAnymalToDatabase: () => useAddAnymalToDatabase,
@@ -68,7 +78,9 @@ __export(index_exports, {
68
78
  useUpdateUserPid: () => useUpdateUserPid,
69
79
  useUploadAnymalImage: () => useUploadAnymalImage,
70
80
  useVerifyAccount: () => useVerifyAccount,
71
- useVerifyWeb3AuthSession: () => useVerifyWeb3AuthSession
81
+ useVerifyWeb3AuthSession: () => useVerifyWeb3AuthSession,
82
+ waitForAllowance: () => waitForAllowance,
83
+ waitForReceiptWithRetries: () => waitForReceiptWithRetries
72
84
  });
73
85
  module.exports = __toCommonJS(index_exports);
74
86
 
@@ -1274,35 +1286,36 @@ async function applyBundlerGasEstimator(account, bundlerClient, options) {
1274
1286
  verificationGasMultiplier = 1.2,
1275
1287
  preVerificationGasMultiplier = 2,
1276
1288
  maxCallGasPercentOfBlock = 0.1,
1277
- // 10% for now?
1278
1289
  debug = true
1279
1290
  } = options || {};
1280
1291
  const publicClient = bundlerClient.client;
1281
1292
  const blockGasLimit = (await publicClient.getBlock()).gasLimit;
1282
1293
  const dynamicCallGasCap = blockGasLimit * BigInt(Math.floor(maxCallGasPercentOfBlock * 100)) / 100n;
1283
1294
  account.userOperation = {
1295
+ ...account.userOperation,
1284
1296
  estimateGas: async (userOp) => {
1285
- const estimate = await bundlerClient.estimateUserOperationGas(userOp);
1286
- const paddedCallGasLimit = estimate.callGasLimit * BigInt(Math.ceil(callGasMultiplier * 100)) / 100n;
1287
- const cappedCallGasLimit = paddedCallGasLimit > dynamicCallGasCap ? dynamicCallGasCap : paddedCallGasLimit;
1288
- const paddedVerificationGasLimit = estimate.verificationGasLimit * BigInt(Math.ceil(verificationGasMultiplier * 100)) / 100n;
1289
- const paddedPreVerificationGas = estimate.preVerificationGas * BigInt(Math.ceil(preVerificationGasMultiplier * 100)) / 100n;
1290
- if (debug) {
1291
- console.log("\u{1F4E6} Bundler Gas Estimates:");
1292
- console.log(" blockGasLimit:", blockGasLimit.toString());
1293
- console.log(" maxCallGasLimit (% cap):", dynamicCallGasCap.toString());
1294
- console.log(" original callGasLimit:", estimate.callGasLimit.toString());
1295
- console.log(" padded callGasLimit:", paddedCallGasLimit.toString());
1296
- console.log(" capped callGasLimit:", cappedCallGasLimit.toString());
1297
- console.log(" verificationGasLimit:", paddedVerificationGasLimit.toString());
1298
- console.log(" preVerificationGas:", paddedPreVerificationGas.toString());
1297
+ try {
1298
+ const estimate = await bundlerClient.estimateUserOperationGas(userOp);
1299
+ const paddedCallGasLimit = estimate.callGasLimit * BigInt(Math.ceil(callGasMultiplier * 100)) / 100n;
1300
+ const cappedCallGasLimit = paddedCallGasLimit > dynamicCallGasCap ? dynamicCallGasCap : paddedCallGasLimit;
1301
+ const paddedVerificationGasLimit = estimate.verificationGasLimit * BigInt(Math.ceil(verificationGasMultiplier * 100)) / 100n;
1302
+ const paddedPreVerificationGas = estimate.preVerificationGas * BigInt(Math.ceil(preVerificationGasMultiplier * 100)) / 100n;
1303
+ if (debug) {
1304
+ console.log("\u2705 Gas Estimation Success:");
1305
+ console.log(" callGasLimit (capped):", cappedCallGasLimit.toString());
1306
+ console.log(" verificationGasLimit:", paddedVerificationGasLimit.toString());
1307
+ console.log(" preVerificationGas:", paddedPreVerificationGas.toString());
1308
+ }
1309
+ return {
1310
+ ...estimate,
1311
+ callGasLimit: cappedCallGasLimit,
1312
+ verificationGasLimit: paddedVerificationGasLimit,
1313
+ preVerificationGas: paddedPreVerificationGas
1314
+ };
1315
+ } catch (error) {
1316
+ console.error("\u274C Gas estimation failed!", error);
1317
+ throw error;
1299
1318
  }
1300
- return {
1301
- ...estimate,
1302
- callGasLimit: cappedCallGasLimit,
1303
- verificationGasLimit: paddedVerificationGasLimit,
1304
- preVerificationGas: paddedPreVerificationGas
1305
- };
1306
1319
  }
1307
1320
  };
1308
1321
  }
@@ -1722,8 +1735,94 @@ function useFetchAnymals() {
1722
1735
  }
1723
1736
 
1724
1737
  // src/utils/marketplace/useProcessPartialKibblePayment.ts
1725
- var import_viem2 = require("viem");
1726
1738
  var import_react17 = require("react");
1739
+
1740
+ // src/helpers/ProcessDirectPartialPayment.tsx
1741
+ var import_viem2 = require("viem");
1742
+
1743
+ // src/helpers/SendUserOpWithRetries.tsx
1744
+ async function sendUserOpWithRetries(bundlerClient, params, retries = 3, delay = 1e3) {
1745
+ let attempt = 0;
1746
+ let lastError;
1747
+ while (attempt < retries) {
1748
+ try {
1749
+ return await bundlerClient.sendUserOperation(params);
1750
+ } catch (err) {
1751
+ lastError = err;
1752
+ console.warn(`\u{1F6D1} sendUserOperation failed (attempt ${attempt + 1}):`, err);
1753
+ attempt++;
1754
+ if (attempt < retries) await new Promise((r) => setTimeout(r, delay));
1755
+ }
1756
+ }
1757
+ throw new Error(`sendUserOperation failed after ${retries} attempts: ${lastError}`);
1758
+ }
1759
+
1760
+ // src/helpers/WaitForReceiptWithRetries.tsx
1761
+ async function waitForReceiptWithRetries(bundlerClient, hash, retries = 3, delay = 2e3) {
1762
+ let attempt = 0;
1763
+ let lastError;
1764
+ while (attempt < retries) {
1765
+ try {
1766
+ const receipt = await bundlerClient.waitForUserOperationReceipt(
1767
+ {
1768
+ hash,
1769
+ timeout: 3e4,
1770
+ retryCount: 10
1771
+ }
1772
+ );
1773
+ if (!receipt.success) {
1774
+ throw new Error(`UserOperation reverted: ${receipt.reason || "unknown"}`);
1775
+ }
1776
+ return receipt;
1777
+ } catch (err) {
1778
+ lastError = err;
1779
+ console.warn(`\u{1F6D1} waitForUserOperationReceipt failed (attempt ${attempt + 1}):`, err);
1780
+ attempt++;
1781
+ if (attempt < retries) await new Promise((r) => setTimeout(r, delay));
1782
+ }
1783
+ }
1784
+ throw new Error(`waitForUserOperationReceipt failed after ${retries} attempts: ${lastError}`);
1785
+ }
1786
+
1787
+ // src/helpers/ProcessDirectPartialPayment.tsx
1788
+ async function processDirectPartialPayment(marketplaceContract, smartAccount, bundlerClient, orderId, anymalNftId, pid, amountInTokens, maxTokenPayment, nonce, deadline, backendSignature) {
1789
+ try {
1790
+ const partialPayCalldata = (0, import_viem2.encodeFunctionData)({
1791
+ abi: MARKETPLACE_ABI,
1792
+ functionName: "partialPay",
1793
+ args: [
1794
+ orderId,
1795
+ anymalNftId,
1796
+ pid,
1797
+ amountInTokens,
1798
+ maxTokenPayment,
1799
+ nonce,
1800
+ deadline,
1801
+ backendSignature
1802
+ ]
1803
+ });
1804
+ await applyBundlerGasEstimator(smartAccount, bundlerClient);
1805
+ const userOpHash = await sendUserOpWithRetries(bundlerClient, {
1806
+ account: smartAccount,
1807
+ calls: [{ to: marketplaceContract, data: partialPayCalldata }],
1808
+ paymaster: true
1809
+ });
1810
+ await waitForReceiptWithRetries(bundlerClient, userOpHash);
1811
+ return {
1812
+ success: true,
1813
+ message: "Direct partial payment UserOperation executed successfully.",
1814
+ opHash: userOpHash
1815
+ };
1816
+ } catch (error) {
1817
+ const errorMessage = error instanceof Error ? error.cause?.message || error.message : "An unknown error occurred.";
1818
+ return {
1819
+ success: false,
1820
+ message: `Error during direct payment processing: ${errorMessage}`
1821
+ };
1822
+ }
1823
+ }
1824
+
1825
+ // src/utils/marketplace/useProcessPartialKibblePayment.ts
1727
1826
  function useProcessPartialKibblePayment() {
1728
1827
  return (0, import_react17.useCallback)(
1729
1828
  async (pid, nftId, orderId, dbAuthToken, marketplaceContract, smartAccount, bundlerClient, amountInTokens, maxTokenPayment, nonce, deadline, backendSignature) => {
@@ -1751,31 +1850,25 @@ function useProcessPartialKibblePayment() {
1751
1850
  backendSignature
1752
1851
  // bytes
1753
1852
  ];
1754
- console.info({ args });
1755
- const callData = (0, import_viem2.encodeFunctionData)({
1756
- abi: MARKETPLACE_ABI,
1757
- functionName: "partialPay",
1758
- args
1759
- });
1760
- await applyBundlerGasEstimator(smartAccount, bundlerClient);
1761
- const userOpHash = await bundlerClient.sendUserOperation({
1762
- account: smartAccount,
1763
- calls: [
1764
- {
1765
- to: marketplaceContract,
1766
- data: callData
1767
- }
1768
- ],
1769
- paymaster: true
1770
- });
1771
- const receipt = await bundlerClient.waitForUserOperationReceipt({
1772
- hash: userOpHash,
1773
- timeout: 3e4,
1774
- retryCount: 10
1775
- });
1776
- return { success: true, message: receipt.userOpHash };
1853
+ const result = await processDirectPartialPayment(
1854
+ marketplaceContract,
1855
+ smartAccount,
1856
+ bundlerClient,
1857
+ orderId,
1858
+ nftId,
1859
+ pid,
1860
+ amountInTokens,
1861
+ maxTokenPayment,
1862
+ nonce,
1863
+ deadline,
1864
+ backendSignature
1865
+ );
1866
+ return {
1867
+ success: result.success,
1868
+ message: result.message
1869
+ };
1777
1870
  } catch (error) {
1778
- const errorMessage = error instanceof Error ? error.message : "An unknown error occurred";
1871
+ const errorMessage = error instanceof Error ? error.cause?.message || error.message : "An unknown error occurred.";
1779
1872
  return {
1780
1873
  success: false,
1781
1874
  message: `Error processing payment: ${errorMessage}`
@@ -1787,41 +1880,53 @@ function useProcessPartialKibblePayment() {
1787
1880
  }
1788
1881
 
1789
1882
  // src/utils/marketplace/useApproveKibbleToken.ts
1790
- var import_viem3 = require("viem");
1791
1883
  var import_react18 = require("react");
1884
+
1885
+ // src/helpers/ProcessDirectKibbleApproval.tsx
1886
+ var import_viem3 = require("viem");
1887
+ async function processDirectKibbleApproval(kibbleTokenAddress, spenderAddress, smartAccount, bundlerClient, approveAmount) {
1888
+ try {
1889
+ const approveCalldata = (0, import_viem3.encodeFunctionData)({
1890
+ abi: import_viem3.erc20Abi,
1891
+ functionName: "approve",
1892
+ args: [spenderAddress, approveAmount]
1893
+ });
1894
+ await applyBundlerGasEstimator(smartAccount, bundlerClient);
1895
+ const userOpHash = await sendUserOpWithRetries(bundlerClient, {
1896
+ account: smartAccount,
1897
+ calls: [{ to: kibbleTokenAddress, data: approveCalldata }],
1898
+ paymaster: true
1899
+ });
1900
+ await waitForReceiptWithRetries(bundlerClient, userOpHash);
1901
+ return {
1902
+ success: true,
1903
+ message: "Direct approval UserOperation executed successfully.",
1904
+ opHash: userOpHash
1905
+ };
1906
+ } catch (error) {
1907
+ const errorMessage = error instanceof Error ? error.cause?.message || error.message : "An unknown error occurred.";
1908
+ return {
1909
+ success: false,
1910
+ message: `Error during direct approval processing: ${errorMessage}`
1911
+ };
1912
+ }
1913
+ }
1914
+
1915
+ // src/utils/marketplace/useApproveKibbleToken.ts
1792
1916
  function useApproveKibbleToken() {
1793
1917
  return (0, import_react18.useCallback)(
1794
1918
  async (kibbleTokenAddress, marketplaceContract, amount, smartAccount, bundlerClient) => {
1795
1919
  try {
1796
- const callData = (0, import_viem3.encodeFunctionData)({
1797
- abi: import_viem3.erc20Abi,
1798
- functionName: "approve",
1799
- args: [
1800
- marketplaceContract,
1801
- // spender address
1802
- BigInt(amount)
1803
- // amount to approve
1804
- ]
1805
- });
1806
- await applyBundlerGasEstimator(smartAccount, bundlerClient);
1807
- const userOpHash = await bundlerClient.sendUserOperation({
1808
- account: smartAccount,
1809
- calls: [
1810
- {
1811
- to: kibbleTokenAddress,
1812
- data: callData
1813
- }
1814
- ],
1815
- paymaster: true
1816
- });
1817
- await bundlerClient.waitForUserOperationReceipt({
1818
- hash: userOpHash,
1819
- timeout: 3e4,
1820
- retryCount: 10
1821
- });
1920
+ const result = await processDirectKibbleApproval(
1921
+ kibbleTokenAddress,
1922
+ marketplaceContract,
1923
+ smartAccount,
1924
+ bundlerClient,
1925
+ amount
1926
+ );
1822
1927
  return {
1823
- success: true,
1824
- message: "Approval transaction completed successfully."
1928
+ success: result.success,
1929
+ message: result.message
1825
1930
  };
1826
1931
  } catch (error) {
1827
1932
  const errorMessage = error instanceof Error ? error.message : "An unknown error occurred";
@@ -1926,7 +2031,92 @@ function useCreateOrganizationBase() {
1926
2031
 
1927
2032
  // src/utils/organization/useApproveOrgKibbleToken.ts
1928
2033
  var import_react20 = require("react");
2034
+
2035
+ // src/helpers/ProcessOrgKibbleApproval.tsx
2036
+ var import_viem6 = require("viem");
2037
+
2038
+ // src/helpers/WaitForAllowance.tsx
1929
2039
  var import_viem5 = require("viem");
2040
+ async function waitForAllowance(publicClient, tokenAddress, ownerAddress, spenderAddress, expectedAmount) {
2041
+ const MAX_RETRIES = 10;
2042
+ const RETRY_INTERVAL = 2e3;
2043
+ console.log(` MDEBUG: Polling for allowance of ${expectedAmount} for spender ${spenderAddress}...`);
2044
+ for (let i = 0; i < MAX_RETRIES; i++) {
2045
+ try {
2046
+ const currentAllowance = await publicClient.readContract({
2047
+ address: tokenAddress,
2048
+ abi: import_viem5.erc20Abi,
2049
+ functionName: "allowance",
2050
+ args: [ownerAddress, spenderAddress]
2051
+ });
2052
+ console.log(` MDEBUG: (Attempt ${i + 1}) Current allowance is ${currentAllowance.toString()}`);
2053
+ if (currentAllowance >= expectedAmount) {
2054
+ console.log(` MDEBUG: \u2705 Allowance confirmed on-chain. ${currentAllowance}`);
2055
+ return true;
2056
+ }
2057
+ } catch (error) {
2058
+ const errorMessage = error instanceof Error ? error.cause?.message || error.message : "An unknown error occurred waiting for allowance.";
2059
+ console.log(` MDEBUG: Error polling for allowance: ${errorMessage}`);
2060
+ }
2061
+ await new Promise((res) => setTimeout(res, RETRY_INTERVAL));
2062
+ }
2063
+ console.log(" MDEBUG: \u274C Timed out waiting for allowance confirmation.");
2064
+ return false;
2065
+ }
2066
+
2067
+ // src/helpers/ProcessOrgKibbleApproval.tsx
2068
+ async function processOrgKibbleApproval(orgContractAddress, kibbleTokenAddress, partialPaymentModuleAddress, managerSmartAccount, bundlerClient, approveAmount) {
2069
+ try {
2070
+ if (approveAmount <= 0n) {
2071
+ return { success: false, message: "Approval amount must be greater than zero." };
2072
+ }
2073
+ const approveCalldata = (0, import_viem6.encodeFunctionData)({
2074
+ abi: import_viem6.erc20Abi,
2075
+ functionName: "approve",
2076
+ args: [partialPaymentModuleAddress, approveAmount]
2077
+ });
2078
+ const executeApproveCalldata = (0, import_viem6.encodeFunctionData)({
2079
+ abi: ORGANIZATION_IMPL_ABI,
2080
+ functionName: "executeCall",
2081
+ args: [kibbleTokenAddress, approveCalldata]
2082
+ });
2083
+ await applyBundlerGasEstimator(managerSmartAccount, bundlerClient);
2084
+ const userOpApproveHash = await sendUserOpWithRetries(bundlerClient, {
2085
+ account: managerSmartAccount,
2086
+ calls: [{ to: orgContractAddress, data: executeApproveCalldata }],
2087
+ paymaster: true
2088
+ });
2089
+ await waitForReceiptWithRetries(bundlerClient, userOpApproveHash);
2090
+ const publicClient = bundlerClient.client;
2091
+ const allowanceConfirmed = await waitForAllowance(
2092
+ publicClient,
2093
+ kibbleTokenAddress,
2094
+ orgContractAddress,
2095
+ partialPaymentModuleAddress,
2096
+ approveAmount
2097
+ );
2098
+ if (!allowanceConfirmed) {
2099
+ console.error("\u274C Halting iteration because on-chain allowance could not be confirmed.");
2100
+ return {
2101
+ success: false,
2102
+ message: `Error waiting for allowance`
2103
+ };
2104
+ }
2105
+ return {
2106
+ success: true,
2107
+ message: "Approval UserOperation executed successfully.",
2108
+ opHash: userOpApproveHash
2109
+ };
2110
+ } catch (error) {
2111
+ const errorMessage = error instanceof Error ? error.cause?.message || error.message : "An unknown error occurred.";
2112
+ return {
2113
+ success: false,
2114
+ message: `Error during approval processing: ${errorMessage}`
2115
+ };
2116
+ }
2117
+ }
2118
+
2119
+ // src/utils/organization/useApproveOrgKibbleToken.ts
1930
2120
  function useApproveOrgPartialPayment() {
1931
2121
  return (0, import_react20.useCallback)(
1932
2122
  async (orgContractAddress, kibbleTokenAddress, partialPaymentModuleAddress, managerSmartAccount, bundlerClient, approveAmount) => {
@@ -1937,37 +2127,22 @@ function useApproveOrgPartialPayment() {
1937
2127
  };
1938
2128
  }
1939
2129
  try {
1940
- const approveCalldata = (0, import_viem5.encodeFunctionData)({
1941
- abi: import_viem5.erc20Abi,
1942
- functionName: "approve",
1943
- args: [partialPaymentModuleAddress, approveAmount]
1944
- });
1945
- const executeApproveCalldata = (0, import_viem5.encodeFunctionData)({
1946
- abi: ORGANIZATION_IMPL_ABI,
1947
- functionName: "executeCall",
1948
- args: [kibbleTokenAddress, approveCalldata]
1949
- });
1950
- await applyBundlerGasEstimator(managerSmartAccount, bundlerClient);
1951
- const userOpApproveHash = await bundlerClient.sendUserOperation({
1952
- account: managerSmartAccount,
1953
- calls: [
1954
- {
1955
- to: orgContractAddress,
1956
- data: executeApproveCalldata
1957
- }
1958
- ],
1959
- paymaster: true
1960
- });
1961
- await bundlerClient.waitForUserOperationReceipt({
1962
- hash: userOpApproveHash
1963
- });
1964
- return { success: true, message: "Approval processed successfully." };
1965
- } catch (error) {
1966
- const errorMessage = error instanceof Error ? error.message : "An unknown error occurred.";
2130
+ const result = await processOrgKibbleApproval(
2131
+ orgContractAddress,
2132
+ kibbleTokenAddress,
2133
+ partialPaymentModuleAddress,
2134
+ managerSmartAccount,
2135
+ bundlerClient,
2136
+ approveAmount
2137
+ );
1967
2138
  return {
1968
- success: false,
1969
- message: `Error processing approval: ${errorMessage}`
2139
+ success: result.success,
2140
+ message: result.message
1970
2141
  };
2142
+ } catch (error) {
2143
+ console.error(" MDEBUG: Uncaught error in `useApproveOrgPartialPayment` hook:", error);
2144
+ const message = error instanceof Error ? error.cause?.message || error.message : "An unknown error occurred.";
2145
+ return { success: false, message: `Approval failed: ${message}` };
1971
2146
  }
1972
2147
  },
1973
2148
  []
@@ -1976,7 +2151,52 @@ function useApproveOrgPartialPayment() {
1976
2151
 
1977
2152
  // src/utils/organization/useProcessOrgPartialKibblePayment.ts
1978
2153
  var import_react21 = require("react");
1979
- var import_viem6 = require("viem");
2154
+
2155
+ // src/helpers/ProcessOrgPartialPayment.tsx
2156
+ var import_viem7 = require("viem");
2157
+ async function processOrgPartialPayment(orgContractAddress, partialPaymentModuleAddress, managerSmartAccount, bundlerClient, orderId, anymalNftId, pid, amountInTokens, maxTokenPayment, nonce, deadline, backendSignature) {
2158
+ try {
2159
+ const partialPayCalldata = (0, import_viem7.encodeFunctionData)({
2160
+ abi: MARKETPLACE_ABI,
2161
+ functionName: "partialPay",
2162
+ args: [
2163
+ orderId,
2164
+ anymalNftId,
2165
+ pid,
2166
+ amountInTokens,
2167
+ maxTokenPayment,
2168
+ nonce,
2169
+ deadline,
2170
+ backendSignature
2171
+ ]
2172
+ });
2173
+ const executePartialPayCalldata = (0, import_viem7.encodeFunctionData)({
2174
+ abi: ORGANIZATION_IMPL_ABI,
2175
+ functionName: "executeCall",
2176
+ args: [partialPaymentModuleAddress, partialPayCalldata]
2177
+ });
2178
+ await applyBundlerGasEstimator(managerSmartAccount, bundlerClient);
2179
+ const userOpHash = await sendUserOpWithRetries(bundlerClient, {
2180
+ account: managerSmartAccount,
2181
+ calls: [{ to: orgContractAddress, data: executePartialPayCalldata }],
2182
+ paymaster: true
2183
+ });
2184
+ await waitForReceiptWithRetries(bundlerClient, userOpHash);
2185
+ return {
2186
+ success: true,
2187
+ message: "Partial payment UserOperation executed successfully.",
2188
+ opHash: userOpHash
2189
+ };
2190
+ } catch (error) {
2191
+ const errorMessage = error instanceof Error ? error.cause?.message || error.message : "An unknown error occurred.";
2192
+ return {
2193
+ success: false,
2194
+ message: `Error during payment processing: ${errorMessage}`
2195
+ };
2196
+ }
2197
+ }
2198
+
2199
+ // src/utils/organization/useProcessOrgPartialKibblePayment.ts
1980
2200
  function useProcessOrgPartialKibblePayment() {
1981
2201
  return (0, import_react21.useCallback)(
1982
2202
  async (orgContractAddress, partialPaymentModuleAddress, managerSmartAccount, bundlerClient, orderId, anymalNftId, pid, amountInTokens, maxTokenPayment, nonce, deadline, backendSignature) => {
@@ -1987,46 +2207,28 @@ function useProcessOrgPartialKibblePayment() {
1987
2207
  };
1988
2208
  }
1989
2209
  try {
1990
- const partialPayCalldata = (0, import_viem6.encodeFunctionData)({
1991
- abi: MARKETPLACE_ABI,
1992
- functionName: "partialPay",
1993
- args: [
1994
- orderId,
1995
- anymalNftId,
1996
- pid,
1997
- amountInTokens,
1998
- maxTokenPayment,
1999
- nonce,
2000
- deadline,
2001
- backendSignature
2002
- ]
2003
- });
2004
- const executePartialPayCalldata = (0, import_viem6.encodeFunctionData)({
2005
- abi: ORGANIZATION_IMPL_ABI,
2006
- functionName: "executeCall",
2007
- args: [partialPaymentModuleAddress, partialPayCalldata]
2008
- });
2009
- await applyBundlerGasEstimator(managerSmartAccount, bundlerClient);
2010
- const userOpPartialPayHash = await bundlerClient.sendUserOperation({
2011
- account: managerSmartAccount,
2012
- calls: [
2013
- {
2014
- to: orgContractAddress,
2015
- data: executePartialPayCalldata
2016
- }
2017
- ],
2018
- paymaster: true
2019
- });
2020
- const receipt = await bundlerClient.waitForUserOperationReceipt({
2021
- hash: userOpPartialPayHash
2022
- });
2023
- return { success: true, message: receipt.userOpHash };
2024
- } catch (error) {
2025
- const errorMessage = error instanceof Error ? error.message : "An unknown error occurred.";
2210
+ const result = await processOrgPartialPayment(
2211
+ orgContractAddress,
2212
+ partialPaymentModuleAddress,
2213
+ managerSmartAccount,
2214
+ bundlerClient,
2215
+ orderId,
2216
+ anymalNftId,
2217
+ pid,
2218
+ amountInTokens,
2219
+ maxTokenPayment,
2220
+ nonce,
2221
+ deadline,
2222
+ backendSignature
2223
+ );
2026
2224
  return {
2027
- success: false,
2028
- message: `Error processing partial payment: ${errorMessage}`
2225
+ success: result.success,
2226
+ message: result.message
2029
2227
  };
2228
+ } catch (error) {
2229
+ console.error(" MDEBUG: Uncaught error in `useProcessOrgPartialKibblePayment`:", error);
2230
+ const errorMessage = error instanceof Error ? error.cause?.message || error.message : "An unknown error occurred.";
2231
+ return { success: false, message: `Partial payment failed: ${errorMessage}` };
2030
2232
  }
2031
2233
  },
2032
2234
  []
@@ -2076,10 +2278,10 @@ function useUpdateOrgWalletAddress() {
2076
2278
 
2077
2279
  // src/helpers/NonceHelper.tsx
2078
2280
  var import_uuid = require("uuid");
2079
- var import_viem7 = require("viem");
2281
+ var import_viem8 = require("viem");
2080
2282
  var generateBytes32Nonce = () => {
2081
2283
  const uuid3 = (0, import_uuid.v4)().replace(/-/g, "");
2082
- return (0, import_viem7.padHex)(`0x${uuid3}`, { size: 32 });
2284
+ return (0, import_viem8.padHex)(`0x${uuid3}`, { size: 32 });
2083
2285
  };
2084
2286
 
2085
2287
  // src/helpers/CryptoUtils.tsx
@@ -2098,6 +2300,14 @@ var AUTH_API_ENDPOINTS = {
2098
2300
  ["testnet" /* Testnet */]: "https://dev-auth-api.petastic.com",
2099
2301
  ["localnet" /* Localnet */]: "http://localhost:3005"
2100
2302
  };
2303
+ var FIREBASE_WEB_API_KEYS = {
2304
+ ["testnet" /* Testnet */]: "AIzaSyC7Q-uzAzNSx6-cj_-LyNkFCWzB6RsmYzI",
2305
+ ["localnet" /* Localnet */]: "AIzaSyC7Q-uzAzNSx6-cj_-LyNkFCWzB6RsmYzI"
2306
+ };
2307
+ var FIREBASE_WEB_AUTH_API_ENDPOINTS = {
2308
+ ["testnet" /* Testnet */]: "https://identitytoolkit.googleapis.com/v1/accounts",
2309
+ ["localnet" /* Localnet */]: "http://localhost:9099/identitytoolkit.googleapis.com/v1/accounts"
2310
+ };
2101
2311
  function loadExistingSecp256k1PrivateKey(hexKey) {
2102
2312
  if (!hexKey) {
2103
2313
  throw new Error("Private key hex must be provided");
@@ -2162,6 +2372,101 @@ async function generateAppSignature(privateKeyHex, clientId, redirectUri, state)
2162
2372
  return Buffer.from(signatureDER).toString("hex");
2163
2373
  }
2164
2374
 
2375
+ // src/helpers/AppHelpers.tsx
2376
+ async function createApp(privateKeyHex, name, metadataURI, ownerEmail, network = "testnet" /* Testnet */, options) {
2377
+ const { publicKey, token } = await createAuthEnvelope(
2378
+ privateKeyHex,
2379
+ network,
2380
+ options
2381
+ );
2382
+ const host = AUTH_API_ENDPOINTS[network];
2383
+ if (!host) {
2384
+ throw new Error(`Unsupported network: ${network}`);
2385
+ }
2386
+ const url = `${host}/create-app`;
2387
+ const response = await fetch(url, {
2388
+ method: "POST",
2389
+ headers: {
2390
+ "Content-Type": "application/json",
2391
+ Authorization: `Bearer ${token}`
2392
+ },
2393
+ body: JSON.stringify({
2394
+ name,
2395
+ publicKey,
2396
+ metadataURI,
2397
+ ownerEmail
2398
+ })
2399
+ });
2400
+ if (!response.ok) {
2401
+ const text = await response.text();
2402
+ throw new Error(`Error creating app (${response.status}): ${text}`);
2403
+ }
2404
+ return response.json();
2405
+ }
2406
+ async function getFirebaseTokenForApp(privateKeyHex, appId, network = "testnet" /* Testnet */) {
2407
+ const { token } = await createAuthEnvelope(privateKeyHex, network);
2408
+ const host = AUTH_API_ENDPOINTS[network];
2409
+ if (!host) {
2410
+ throw new Error(`Unsupported network: ${network}`);
2411
+ }
2412
+ const response = await fetch(`${host}/exchange-jwt-for-app-token`, {
2413
+ method: "POST",
2414
+ headers: {
2415
+ Authorization: `Bearer ${token}`
2416
+ },
2417
+ body: JSON.stringify({
2418
+ appId
2419
+ })
2420
+ });
2421
+ if (!response.ok) {
2422
+ const text = await response.text();
2423
+ throw new Error(`Failed to get Firebase token: ${response.status} ${text}`);
2424
+ }
2425
+ const { firebaseToken: customToken } = await response.json();
2426
+ const firebaseApiKey = FIREBASE_WEB_API_KEYS[network];
2427
+ if (!firebaseApiKey) {
2428
+ throw new Error("FIREBASE_WEB_API_KEY is not set");
2429
+ }
2430
+ const fbAuthEndpoint = FIREBASE_WEB_AUTH_API_ENDPOINTS[network];
2431
+ const firebaseResponse = await fetch(
2432
+ `${fbAuthEndpoint}:signInWithCustomToken?key=${firebaseApiKey}`,
2433
+ {
2434
+ method: "POST",
2435
+ headers: {
2436
+ "Content-Type": "application/json"
2437
+ },
2438
+ body: JSON.stringify({
2439
+ token: customToken,
2440
+ returnSecureToken: true
2441
+ })
2442
+ }
2443
+ );
2444
+ if (!firebaseResponse.ok) {
2445
+ const text = await firebaseResponse.text();
2446
+ throw new Error(`Firebase token exchange failed: ${firebaseResponse.status} ${text}`);
2447
+ }
2448
+ const { idToken } = await firebaseResponse.json();
2449
+ return { firebaseToken: idToken };
2450
+ }
2451
+ function flattenFirestoreData(fields) {
2452
+ const parseValue = (val) => {
2453
+ if (val === null || typeof val !== "object") return val;
2454
+ if ("stringValue" in val) return val.stringValue;
2455
+ if ("integerValue" in val) return parseInt(val.integerValue, 10);
2456
+ if ("doubleValue" in val) return parseFloat(val.doubleValue);
2457
+ if ("booleanValue" in val) return val.booleanValue;
2458
+ if ("timestampValue" in val) return val.timestampValue;
2459
+ if ("nullValue" in val) return null;
2460
+ if ("mapValue" in val) return flattenFirestoreData(val.mapValue.fields || {});
2461
+ if ("arrayValue" in val)
2462
+ return (val.arrayValue.values || []).map(parseValue);
2463
+ return val;
2464
+ };
2465
+ return Object.fromEntries(
2466
+ Object.entries(fields).map(([key, value]) => [key, parseValue(value)])
2467
+ );
2468
+ }
2469
+
2165
2470
  // src/helpers/ActionHelpers.tsx
2166
2471
  async function submitAction(idToken, pid, sourceType, payload, endpointBaseUrl) {
2167
2472
  const api = endpointBaseUrl + "/actions";
@@ -2432,16 +2737,16 @@ function useCreateOrganizationAppData() {
2432
2737
 
2433
2738
  // src/utils/balance/useFetchBalance.ts
2434
2739
  var import_react27 = require("react");
2435
- var import_viem8 = require("viem");
2740
+ var import_viem9 = require("viem");
2436
2741
  function useFetchBalance() {
2437
2742
  return (0, import_react27.useCallback)(
2438
2743
  async (publicClient, walletAddress, kibbleTokenAddress) => {
2439
2744
  try {
2440
2745
  const balance = await publicClient.readContract({
2441
- address: (0, import_viem8.getAddress)(kibbleTokenAddress),
2442
- abi: import_viem8.erc20Abi,
2746
+ address: (0, import_viem9.getAddress)(kibbleTokenAddress),
2747
+ abi: import_viem9.erc20Abi,
2443
2748
  functionName: "balanceOf",
2444
- args: [(0, import_viem8.getAddress)(walletAddress)]
2749
+ args: [(0, import_viem9.getAddress)(walletAddress)]
2445
2750
  });
2446
2751
  return Number(balance);
2447
2752
  } catch (error) {
@@ -2453,7 +2758,7 @@ function useFetchBalance() {
2453
2758
  }
2454
2759
 
2455
2760
  // src/utils/actions/useClaimActionReward.ts
2456
- var import_viem9 = require("viem");
2761
+ var import_viem10 = require("viem");
2457
2762
  var import_react28 = require("react");
2458
2763
  function useClaimActionReward() {
2459
2764
  return (0, import_react28.useCallback)(
@@ -2464,7 +2769,7 @@ function useClaimActionReward() {
2464
2769
  message: "Missing web3auth account info or contract address."
2465
2770
  };
2466
2771
  }
2467
- const callData = (0, import_viem9.encodeFunctionData)({
2772
+ const callData = (0, import_viem10.encodeFunctionData)({
2468
2773
  abi: REWARDABLE_ACTIONS_ABI,
2469
2774
  functionName: "claimByIndex",
2470
2775
  args: [actionId, claimIndex]
@@ -2492,7 +2797,7 @@ function useClaimActionReward() {
2492
2797
  }
2493
2798
 
2494
2799
  // src/utils/actions/useClaimOrgActionReward.ts
2495
- var import_viem10 = require("viem");
2800
+ var import_viem11 = require("viem");
2496
2801
  var import_react29 = require("react");
2497
2802
  function useClaimOrgActionReward() {
2498
2803
  return (0, import_react29.useCallback)(
@@ -2503,12 +2808,12 @@ function useClaimOrgActionReward() {
2503
2808
  message: "Missing web3auth account info or contract address."
2504
2809
  };
2505
2810
  }
2506
- const claimCallData = (0, import_viem10.encodeFunctionData)({
2811
+ const claimCallData = (0, import_viem11.encodeFunctionData)({
2507
2812
  abi: REWARDABLE_ACTIONS_ABI,
2508
2813
  functionName: "claimByIndex",
2509
2814
  args: [actionId, claimIndex]
2510
2815
  });
2511
- const executeClaimCalldata = (0, import_viem10.encodeFunctionData)({
2816
+ const executeClaimCalldata = (0, import_viem11.encodeFunctionData)({
2512
2817
  abi: ORGANIZATION_IMPL_ABI,
2513
2818
  functionName: "executeCall",
2514
2819
  args: [rewardableActionContractAddress, claimCallData]
@@ -2659,6 +2964,8 @@ function isMarketplacePurchaseAction(payload) {
2659
2964
  ActionSourceType,
2660
2965
  ActionStatus,
2661
2966
  ActionType,
2967
+ FIREBASE_WEB_API_KEYS,
2968
+ FIREBASE_WEB_AUTH_API_ENDPOINTS,
2662
2969
  MarketplacePaymentType,
2663
2970
  NETWORK_HOSTS,
2664
2971
  Network,
@@ -2666,12 +2973,20 @@ function isMarketplacePurchaseAction(payload) {
2666
2973
  convertToActionRecord,
2667
2974
  convertToMultipleActionDefinitions,
2668
2975
  convertToMultipleActionRecords,
2976
+ createApp,
2669
2977
  createAuthEnvelope,
2670
2978
  fetchAnymals,
2979
+ flattenFirestoreData,
2671
2980
  generateAppSignature,
2672
2981
  generateBytes32Nonce,
2673
2982
  generateJWT,
2983
+ getFirebaseTokenForApp,
2674
2984
  loadExistingSecp256k1PrivateKey,
2985
+ processDirectKibbleApproval,
2986
+ processDirectPartialPayment,
2987
+ processOrgKibbleApproval,
2988
+ processOrgPartialPayment,
2989
+ sendUserOpWithRetries,
2675
2990
  serializePublicKeyCompressed,
2676
2991
  submitAction,
2677
2992
  useAddAnymalToDatabase,
@@ -2703,5 +3018,7 @@ function isMarketplacePurchaseAction(payload) {
2703
3018
  useUpdateUserPid,
2704
3019
  useUploadAnymalImage,
2705
3020
  useVerifyAccount,
2706
- useVerifyWeb3AuthSession
3021
+ useVerifyWeb3AuthSession,
3022
+ waitForAllowance,
3023
+ waitForReceiptWithRetries
2707
3024
  });