anymal-protocol 1.0.59 → 1.0.61

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
@@ -20,7 +20,18 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ AUTH_API_ENDPOINTS: () => AUTH_API_ENDPOINTS,
24
+ ActionType: () => ActionType,
25
+ NETWORK_HOSTS: () => NETWORK_HOSTS,
26
+ Network: () => Network,
27
+ createAuthEnvelope: () => createAuthEnvelope,
28
+ fetchAnymals: () => fetchAnymals,
29
+ generateAppSignature: () => generateAppSignature,
23
30
  generateBytes32Nonce: () => generateBytes32Nonce,
31
+ generateJWT: () => generateJWT,
32
+ loadExistingSecp256k1PrivateKey: () => loadExistingSecp256k1PrivateKey,
33
+ serializePublicKeyCompressed: () => serializePublicKeyCompressed,
34
+ submitAction: () => submitAction,
24
35
  useAddAnymalToDatabase: () => useAddAnymalToDatabase,
25
36
  useApproveKibbleToken: () => useApproveKibbleToken,
26
37
  useApproveOrgPartialPayment: () => useApproveOrgPartialPayment,
@@ -29,6 +40,8 @@ __export(index_exports, {
29
40
  useCreateUserAppData: () => useCreateUserAppData,
30
41
  useCreateWeb3Account: () => useCreateWeb3Account,
31
42
  useDeleteAnymalFromDatabase: () => useDeleteAnymalFromDatabase,
43
+ useFetchActions: () => useFetchActions,
44
+ useFetchAnymals: () => useFetchAnymals,
32
45
  useFetchBalance: () => useFetchBalance,
33
46
  useFetchNotifications: () => useFetchNotifications,
34
47
  useFetchUserData: () => useFetchUserData,
@@ -1308,10 +1321,12 @@ function useAddAnymalToDatabase() {
1308
1321
  return {
1309
1322
  success: false,
1310
1323
  message: "Authentication token is missing.",
1311
- _docID: null
1324
+ _docID: null,
1325
+ dbCid: null
1312
1326
  };
1313
1327
  }
1314
1328
  let anymalDocID = null;
1329
+ let dbCid = null;
1315
1330
  try {
1316
1331
  const mutation = `
1317
1332
  mutation Create_Anymal($input: [AnymalMutationInputArg!]) {
@@ -1319,6 +1334,9 @@ function useAddAnymalToDatabase() {
1319
1334
  _docID
1320
1335
  name
1321
1336
  passportID
1337
+ _version {
1338
+ cid
1339
+ }
1322
1340
  }
1323
1341
  }
1324
1342
  `;
@@ -1349,15 +1367,18 @@ function useAddAnymalToDatabase() {
1349
1367
  throw new Error(`GraphQL error: ${errorMessage}`);
1350
1368
  }
1351
1369
  anymalDocID = data.create_Anymal[0]._docID;
1370
+ dbCid = data.create_Anymal[0]._version[0].cid;
1352
1371
  return {
1353
1372
  success: true,
1354
1373
  _docID: anymalDocID,
1374
+ dbCid,
1355
1375
  message: "Anymal added to account"
1356
1376
  };
1357
1377
  } catch (error) {
1358
1378
  return {
1359
1379
  success: false,
1360
1380
  _docID: null,
1381
+ dbCid: null,
1361
1382
  message: "Error adding anymal to account"
1362
1383
  };
1363
1384
  }
@@ -1598,11 +1619,68 @@ function useUploadAnymalImage() {
1598
1619
  );
1599
1620
  }
1600
1621
 
1622
+ // src/utils/anymals/useFetchAnymals.ts
1623
+ var import_react16 = require("react");
1624
+
1625
+ // src/utils/anymals/fetchAnymals.ts
1626
+ async function fetchAnymals({
1627
+ dbAuthToken,
1628
+ endpoint,
1629
+ userPid
1630
+ }) {
1631
+ const query = `
1632
+ query Anymal($filter: AnymalFilterArg, $order: [AnymalOrderArg]) {
1633
+ Anymal(filter: $filter, order: $order) {
1634
+ _docID
1635
+ name
1636
+ breed
1637
+ passportID
1638
+ profileImageUrl
1639
+ caregiverNearId
1640
+ caregiverId
1641
+ lifestage
1642
+ gender
1643
+ petType
1644
+ products
1645
+ timeAddedUtc
1646
+ }
1647
+ }
1648
+ `;
1649
+ const variables = {
1650
+ filter: {
1651
+ caregiverId: { _eq: userPid }
1652
+ },
1653
+ order: [
1654
+ {
1655
+ timeAddedUtc: "ASC"
1656
+ }
1657
+ ]
1658
+ };
1659
+ const response = await fetch(endpoint, {
1660
+ method: "POST",
1661
+ headers: {
1662
+ "Content-Type": "application/json",
1663
+ Authorization: `Bearer ${dbAuthToken}`
1664
+ },
1665
+ body: JSON.stringify({ query, variables })
1666
+ });
1667
+ if (!response.ok) {
1668
+ throw new Error(`HTTP error! Status: ${response.status}`);
1669
+ }
1670
+ const data = await response.json();
1671
+ return data?.data?.Anymal ?? [];
1672
+ }
1673
+
1674
+ // src/utils/anymals/useFetchAnymals.ts
1675
+ function useFetchAnymals() {
1676
+ return (0, import_react16.useCallback)(fetchAnymals, []);
1677
+ }
1678
+
1601
1679
  // src/utils/marketplace/useProcessPartialKibblePayment.ts
1602
1680
  var import_viem3 = require("viem");
1603
- var import_react16 = require("react");
1681
+ var import_react17 = require("react");
1604
1682
  function useProcessPartialKibblePayment() {
1605
- return (0, import_react16.useCallback)(
1683
+ return (0, import_react17.useCallback)(
1606
1684
  async (pid, nftId, orderId, dbAuthToken, marketplaceContract, smartAccount, bundlerClient, amountInTokens, maxTokenPayment, nonce, deadline, backendSignature) => {
1607
1685
  if (!orderId || !dbAuthToken || !nftId || !bundlerClient || !smartAccount || !pid || !marketplaceContract || !amountInTokens || !maxTokenPayment || !nonce || !deadline) {
1608
1686
  return {
@@ -1665,9 +1743,9 @@ function useProcessPartialKibblePayment() {
1665
1743
 
1666
1744
  // src/utils/marketplace/useApproveKibbleToken.ts
1667
1745
  var import_viem4 = require("viem");
1668
- var import_react17 = require("react");
1746
+ var import_react18 = require("react");
1669
1747
  function useApproveKibbleToken() {
1670
- return (0, import_react17.useCallback)(
1748
+ return (0, import_react18.useCallback)(
1671
1749
  async (kibbleTokenAddress, marketplaceContract, amount, smartAccount, bundlerClient) => {
1672
1750
  try {
1673
1751
  const callData = (0, import_viem4.encodeFunctionData)({
@@ -1717,10 +1795,10 @@ function useApproveKibbleToken() {
1717
1795
  }
1718
1796
 
1719
1797
  // src/utils/organization/useCreateOrganizationBase.ts
1720
- var import_react18 = require("react");
1798
+ var import_react19 = require("react");
1721
1799
  var import_viem5 = require("viem");
1722
1800
  function useCreateOrganizationBase() {
1723
- return (0, import_react18.useCallback)(
1801
+ return (0, import_react19.useCallback)(
1724
1802
  /**
1725
1803
  * Creates a new organization on-chain.
1726
1804
  *
@@ -1806,10 +1884,10 @@ function useCreateOrganizationBase() {
1806
1884
  }
1807
1885
 
1808
1886
  // src/utils/organization/useApproveOrgKibbleToken.ts
1809
- var import_react19 = require("react");
1887
+ var import_react20 = require("react");
1810
1888
  var import_viem6 = require("viem");
1811
1889
  function useApproveOrgPartialPayment() {
1812
- return (0, import_react19.useCallback)(
1890
+ return (0, import_react20.useCallback)(
1813
1891
  async (orgContractAddress, kibbleTokenAddress, partialPaymentModuleAddress, managerSmartAccount, bundlerClient, approveAmount) => {
1814
1892
  if (!orgContractAddress || !kibbleTokenAddress || !partialPaymentModuleAddress || !managerSmartAccount || !bundlerClient || !approveAmount) {
1815
1893
  return {
@@ -1851,10 +1929,10 @@ function useApproveOrgPartialPayment() {
1851
1929
  }
1852
1930
 
1853
1931
  // src/utils/organization/useProcessOrgPartialKibblePayment.ts
1854
- var import_react20 = require("react");
1932
+ var import_react21 = require("react");
1855
1933
  var import_viem7 = require("viem");
1856
1934
  function useProcessOrgPartialKibblePayment() {
1857
- return (0, import_react20.useCallback)(
1935
+ return (0, import_react21.useCallback)(
1858
1936
  async (orgContractAddress, partialPaymentModuleAddress, managerSmartAccount, bundlerClient, orderId, anymalNftId, pid, amountInTokens, maxTokenPayment, nonce, deadline, backendSignature) => {
1859
1937
  if (!orgContractAddress || !partialPaymentModuleAddress || !managerSmartAccount || !bundlerClient || !orderId || !pid || !nonce || !backendSignature) {
1860
1938
  return {
@@ -1905,9 +1983,9 @@ function useProcessOrgPartialKibblePayment() {
1905
1983
  }
1906
1984
 
1907
1985
  // src/utils/organization/useUpdateOrgWalletAddress.ts
1908
- var import_react21 = require("react");
1986
+ var import_react22 = require("react");
1909
1987
  function useUpdateOrgWalletAddress() {
1910
- return (0, import_react21.useCallback)(
1988
+ return (0, import_react22.useCallback)(
1911
1989
  async (dbAuthToken, docID, baseWalletAddress, endpoint) => {
1912
1990
  try {
1913
1991
  const mutation = `
@@ -1953,11 +2031,145 @@ var generateBytes32Nonce = () => {
1953
2031
  return (0, import_viem8.padHex)(`0x${uuid3}`, { size: 32 });
1954
2032
  };
1955
2033
 
2034
+ // src/helpers/CryptoUtils.tsx
2035
+ var import_elliptic = require("elliptic");
2036
+ var ec = new import_elliptic.ec("secp256k1");
2037
+ var Network = /* @__PURE__ */ ((Network2) => {
2038
+ Network2["Testnet"] = "testnet";
2039
+ Network2["Localnet"] = "localnet";
2040
+ return Network2;
2041
+ })(Network || {});
2042
+ var NETWORK_HOSTS = {
2043
+ ["testnet" /* Testnet */]: "dev-db.petastic.com",
2044
+ ["localnet" /* Localnet */]: "host.docker.internal:9181"
2045
+ };
2046
+ var AUTH_API_ENDPOINTS = {
2047
+ ["testnet" /* Testnet */]: "https://dev-auth-api.petastic.com",
2048
+ ["localnet" /* Localnet */]: "http://localhost:3005"
2049
+ };
2050
+ function loadExistingSecp256k1PrivateKey(hexKey) {
2051
+ if (!hexKey) {
2052
+ throw new Error("Private key hex must be provided");
2053
+ }
2054
+ return ec.keyFromPrivate(hexKey, "hex");
2055
+ }
2056
+ function serializePublicKeyCompressed(keyPair) {
2057
+ return keyPair.getPublic(true, "hex");
2058
+ }
2059
+ function base64url(input) {
2060
+ let buf;
2061
+ if (typeof input === "string") buf = Buffer.from(input);
2062
+ else if (input instanceof ArrayBuffer) buf = Buffer.from(input);
2063
+ else buf = input;
2064
+ return buf.toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
2065
+ }
2066
+ function sha256HashNode(data) {
2067
+ const { createHash } = require("crypto");
2068
+ return createHash("sha256").update(data).digest();
2069
+ }
2070
+ async function hashInput(data) {
2071
+ if (typeof window !== "undefined" && window.crypto?.subtle) {
2072
+ const encoder = new TextEncoder();
2073
+ const encoded = encoder.encode(data);
2074
+ const hashBuffer = await window.crypto.subtle.digest("SHA-256", encoded);
2075
+ return Buffer.from(hashBuffer);
2076
+ } else {
2077
+ return sha256HashNode(data);
2078
+ }
2079
+ }
2080
+ async function generateJWT(sub, aud, keyPair, expiresInSeconds = 24 * 60 * 60) {
2081
+ const iat = Math.floor(Date.now() / 1e3);
2082
+ const exp = iat + expiresInSeconds;
2083
+ const header = { alg: "ES256", typ: "JWT" };
2084
+ const payload = { sub, aud, iat, exp };
2085
+ const encodedHeader = base64url(JSON.stringify(header));
2086
+ const encodedPayload = base64url(JSON.stringify(payload));
2087
+ const signingInput = `${encodedHeader}.${encodedPayload}`;
2088
+ const hash = await hashInput(signingInput);
2089
+ const signature = keyPair.sign(hash, { canonical: true });
2090
+ const rBuf = signature.r.toArrayLike(Buffer, "be", 32);
2091
+ const sBuf = signature.s.toArrayLike(Buffer, "be", 32);
2092
+ const rawSig = Buffer.concat([rBuf, sBuf]);
2093
+ const encodedSig = base64url(rawSig);
2094
+ return `${signingInput}.${encodedSig}`;
2095
+ }
2096
+ async function createAuthEnvelope(privateKeyHex, network = "testnet" /* Testnet */, options) {
2097
+ const keyPair = loadExistingSecp256k1PrivateKey(privateKeyHex);
2098
+ const publicKey = serializePublicKeyCompressed(keyPair);
2099
+ const host = NETWORK_HOSTS[network];
2100
+ if (!host) {
2101
+ throw new Error(`Unsupported network: ${network}`);
2102
+ }
2103
+ const token = await generateJWT(publicKey, host, keyPair, options?.expiresInSeconds);
2104
+ return { publicKey, token };
2105
+ }
2106
+ async function generateAppSignature(privateKeyHex, clientId, redirectUri, state) {
2107
+ const keyPair = loadExistingSecp256k1PrivateKey(privateKeyHex);
2108
+ const message = `${clientId}:${redirectUri}:${state}`;
2109
+ const hash = await hashInput(message);
2110
+ const signatureDER = keyPair.sign(hash, { canonical: true }).toDER();
2111
+ return Buffer.from(signatureDER).toString("hex");
2112
+ }
2113
+
2114
+ // src/helpers/ActionHelpers.tsx
2115
+ async function submitAction(idToken, pid, payload, endpointBaseUrl) {
2116
+ const api = endpointBaseUrl + "/actions";
2117
+ const response = await fetch(api, {
2118
+ method: "POST",
2119
+ headers: { "Content-Type": "application/json", "Authorization": "Bearer " + idToken },
2120
+ body: JSON.stringify({ actionId: payload.actionId, pid, payload })
2121
+ });
2122
+ if (!response.ok) {
2123
+ const err = await response.json();
2124
+ throw new Error(err.error || "Failed to submit action");
2125
+ }
2126
+ return response.json();
2127
+ }
2128
+
2129
+ // src/utils/actions/useFetchActions.ts
2130
+ var import_react23 = require("react");
2131
+ function useFetchActions() {
2132
+ return (0, import_react23.useCallback)(
2133
+ async (idToken, actionsServiceBaseUrl, pid, status, limit, offset) => {
2134
+ const params = new URLSearchParams({ pid });
2135
+ if (status) params.set("status", status);
2136
+ if (limit != null) params.set("limit", `${limit}`);
2137
+ if (offset != null) params.set("offset", `${offset}`);
2138
+ try {
2139
+ const response = await fetch(
2140
+ `${actionsServiceBaseUrl}/actions?${params.toString()}`,
2141
+ {
2142
+ method: "GET",
2143
+ headers: {
2144
+ "Content-Type": "application/json",
2145
+ Authorization: "Bearer " + idToken
2146
+ }
2147
+ }
2148
+ );
2149
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
2150
+ return await response.json();
2151
+ } catch (error) {
2152
+ console.error("useFetchActions error:", error);
2153
+ return null;
2154
+ }
2155
+ },
2156
+ []
2157
+ );
2158
+ }
2159
+
2160
+ // src/types/Actions.ts
2161
+ var ActionType = /* @__PURE__ */ ((ActionType2) => {
2162
+ ActionType2["GRAPHQL"] = "GRAPHQL";
2163
+ ActionType2["CONTRACT"] = "CONTRACT";
2164
+ ActionType2["EXTERNAL"] = "EXTERNAL";
2165
+ return ActionType2;
2166
+ })(ActionType || {});
2167
+
1956
2168
  // src/utils/application/useCreateUserAppData.ts
1957
- var import_react22 = require("react");
2169
+ var import_react24 = require("react");
1958
2170
  var import_uuid2 = require("uuid");
1959
2171
  function useCreateUserAppData() {
1960
- return (0, import_react22.useCallback)(
2172
+ return (0, import_react24.useCallback)(
1961
2173
  async (appId, pid, dbAuthToken, endpoint) => {
1962
2174
  if (!dbAuthToken || !pid || !dbAuthToken || !endpoint) return;
1963
2175
  const appValues = {
@@ -2012,10 +2224,10 @@ function useCreateUserAppData() {
2012
2224
  }
2013
2225
 
2014
2226
  // src/utils/application/useCreateOrganizationAppData.ts
2015
- var import_react23 = require("react");
2227
+ var import_react25 = require("react");
2016
2228
  var import_uuid3 = require("uuid");
2017
2229
  function useCreateOrganizationAppData() {
2018
- return (0, import_react23.useCallback)(
2230
+ return (0, import_react25.useCallback)(
2019
2231
  async (appId, pid, dbAuthToken, endpoint) => {
2020
2232
  if (!dbAuthToken || !pid || !dbAuthToken || !endpoint) return;
2021
2233
  const appValues = {
@@ -2069,10 +2281,10 @@ function useCreateOrganizationAppData() {
2069
2281
  }
2070
2282
 
2071
2283
  // src/utils/balance/useFetchBalance.ts
2072
- var import_react24 = require("react");
2284
+ var import_react26 = require("react");
2073
2285
  var import_viem9 = require("viem");
2074
2286
  function useFetchBalance() {
2075
- return (0, import_react24.useCallback)(
2287
+ return (0, import_react26.useCallback)(
2076
2288
  async (publicClient, walletAddress, kibbleTokenAddress) => {
2077
2289
  try {
2078
2290
  const balance = await publicClient.readContract({
@@ -2091,7 +2303,18 @@ function useFetchBalance() {
2091
2303
  }
2092
2304
  // Annotate the CommonJS export names for ESM import in node:
2093
2305
  0 && (module.exports = {
2306
+ AUTH_API_ENDPOINTS,
2307
+ ActionType,
2308
+ NETWORK_HOSTS,
2309
+ Network,
2310
+ createAuthEnvelope,
2311
+ fetchAnymals,
2312
+ generateAppSignature,
2094
2313
  generateBytes32Nonce,
2314
+ generateJWT,
2315
+ loadExistingSecp256k1PrivateKey,
2316
+ serializePublicKeyCompressed,
2317
+ submitAction,
2095
2318
  useAddAnymalToDatabase,
2096
2319
  useApproveKibbleToken,
2097
2320
  useApproveOrgPartialPayment,
@@ -2100,6 +2323,8 @@ function useFetchBalance() {
2100
2323
  useCreateUserAppData,
2101
2324
  useCreateWeb3Account,
2102
2325
  useDeleteAnymalFromDatabase,
2326
+ useFetchActions,
2327
+ useFetchAnymals,
2103
2328
  useFetchBalance,
2104
2329
  useFetchNotifications,
2105
2330
  useFetchUserData,