@gardenfi/react-hooks 3.0.7 → 3.1.0-beta.2

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/index2.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("react"),g=require("./index3.cjs"),d=require("@gardenfi/core"),v=require("./index4.cjs"),k=require("./index5.cjs"),p=require("@gardenfi/utils"),q=require("./index6.cjs"),w=a.createContext({pendingOrders:[]}),E=({children:i,config:e,store:l,setRedeemServiceEnabled:n=!0})=>{const[s,G]=a.useState(),{digestKey:c}=k.useDigestKey(n),{pendingOrders:O}=g.useOrderbook(s,l),h=a.useMemo(()=>{const{api:t}=d.resolveApiConfig(e.environment);return e.quote??new d.Quote(t.baseurl,v.resolveAuth(e.apiKey))},[e.environment,e.quote,e.apiKey]),_=a.useMemo(()=>async({fromAsset:t,toAsset:r,amount:u,isExactOut:o=!1,options:y})=>await(s?s.quote:h).getQuoteFromAssets({fromAsset:t,toAsset:r,amount:u,isExactOut:o,options:y}),[s,h]),m=async t=>{if(!s)return p.Err("Garden not initialized");const r=await s.createSwap(t);if(!r.val)return p.Err(r.error||"Unknown error occurred");if(n)try{const u=l.getItem(q.PENDING_ORDERS_STORE),o=u?JSON.parse(u):[];typeof r.val=="string"?o.includes(r.val)||o.push(r.val):r.val&&typeof r.val.order_id=="string"&&(o.includes(r.val.order_id)||o.push(r.val.order_id));const y=Array.from(new Set(o));l.setItem(q.PENDING_ORDERS_STORE,JSON.stringify(y))}catch(u){console.error("Failed to persist pending order id",u)}return p.Ok(r.val)};return a.useEffect(()=>{if(!("wallets"in e)&&!("htlc"in e))return;let t;if("wallets"in e&&Object.keys(e.wallets??{}).length>0&&v.hasAnyValidValue(e.wallets??{}))t=d.Garden.fromWallets({...e,digestKey:n?void 0:c}).setRedeemServiceEnabled(n);else if("htlc"in e&&Object.keys(e.htlc??{}).length>0&&v.hasAnyValidValue(e.htlc??{}))t=new d.Garden({...e,digestKey:n?void 0:c}).setRedeemServiceEnabled(n);else return;G(t)},[e,c,n]),a.createElement(w.Provider,{value:{swap:m,pendingOrders:O,getQuote:_,garden:s,orderBook:s}},i)},K=()=>{const i=a.useContext(w);if(!i)throw new Error("useGarden must be used within a GardenProvider");return i};exports.GardenContext=w;exports.GardenProvider=E;exports.useGarden=K;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react"),k=require("./index3.cjs"),a=require("@gardenfi/core"),c=require("./index4.cjs"),u=require("@gardenfi/utils"),b=require("./index5.cjs"),v=n.createContext({pendingOrders:[]}),M=({children:d,config:e,store:l})=>{const[s,y]=n.useState(),w=n.useMemo(()=>{const{network:r}=a.resolveApiConfig(e.environment);return r},[e.environment]),m=n.useMemo(()=>new b.PendingOrdersManager(l,u.StoreKeys.PENDING_ORDERS),[l]),{pendingOrders:G}=k.useOrderbook(s,l,w),p=n.useMemo(()=>{const{api:r}=a.resolveApiConfig(e.environment);return e.quote??new a.Quote(r.baseurl,c.resolveAuth(e.apiKey))},[e.environment,e.quote,e.apiKey]),h=n.useMemo(()=>async({fromAsset:r,toAsset:i,amount:t,isExactOut:o=!1,options:O})=>await(s?s.quote:p).getQuoteFromAssets({fromAsset:r,toAsset:i,amount:t,isExactOut:o,options:O}),[s,p]),q=async(r,i)=>{if(!s)return u.Err("Garden not initialized");const t=await s.createSwap(r,i);if(!t.val)return u.Err(t.error||"Unknown error occurred");try{let o;typeof t.val=="string"?o=t.val:t.val&&typeof t.val.order_id=="string"&&(o=t.val.order_id),o&&m.add(w,o)}catch(o){console.error("Failed to persist pending order id",o)}return u.Ok(t.val)};return n.useEffect(()=>{if(!("wallets"in e)&&!("htlc"in e))return;let r;if("wallets"in e&&Object.keys(e.wallets??{}).length>0&&c.hasAnyValidValue(e.wallets??{}))r=a.Garden.fromWallets({...e});else if("htlc"in e&&Object.keys(e.htlc??{}).length>0&&c.hasAnyValidValue(e.htlc??{}))r=new a.Garden({...e});else return;y(r)},[e]),n.createElement(v.Provider,{value:{swap:q,pendingOrders:G,getQuote:h,garden:s,orderBook:s}},d)},E=()=>{const d=n.useContext(v);if(!d)throw new Error("useGarden must be used within a GardenProvider");return d};exports.GardenContext=v;exports.GardenProvider=M;exports.useGarden=E;
package/dist/index2.js CHANGED
@@ -1,88 +1,87 @@
1
- import h, { useState as k, useMemo as m, useEffect as K, createContext as x } from "react";
2
- import { useOrderbook as A } from "./index3.js";
3
- import { resolveApiConfig as g, Quote as C, Garden as c } from "@gardenfi/core";
4
- import { resolveAuth as I, hasAnyValidValue as y } from "./index4.js";
5
- import { useDigestKey as N } from "./index5.js";
6
- import { Err as v, Ok as P } from "@gardenfi/utils";
7
- import { PENDING_ORDERS_STORE as w } from "./index6.js";
8
- const f = x({
1
+ import c, { useState as b, useMemo as a, useEffect as P, createContext as _ } from "react";
2
+ import { useOrderbook as f } from "./index3.js";
3
+ import { resolveApiConfig as m, Quote as x, Garden as p } from "@gardenfi/core";
4
+ import { resolveAuth as A, hasAnyValidValue as v } from "./index4.js";
5
+ import { StoreKeys as C, Err as w, Ok as S } from "@gardenfi/utils";
6
+ import { PendingOrdersManager as K } from "./index5.js";
7
+ const h = _({
9
8
  pendingOrders: []
10
- }), b = ({
11
- children: i,
9
+ }), I = ({
10
+ children: s,
12
11
  config: e,
13
- store: u,
14
- setRedeemServiceEnabled: o = !0
12
+ store: d
15
13
  }) => {
16
- const [s, O] = k(), { digestKey: l } = N(o), { pendingOrders: G } = A(s, u), p = m(() => {
17
- const { api: t } = g(e.environment);
18
- return e.quote ?? new C(t.baseurl, I(e.apiKey));
19
- }, [e.environment, e.quote, e.apiKey]), q = m(
14
+ const [n, y] = b(), i = a(() => {
15
+ const { network: r } = m(e.environment);
16
+ return r;
17
+ }, [e.environment]), k = a(
18
+ () => new K(d, C.PENDING_ORDERS),
19
+ [d]
20
+ ), { pendingOrders: G } = f(n, d, i), u = a(() => {
21
+ const { api: r } = m(e.environment);
22
+ return e.quote ?? new x(r.baseurl, A(e.apiKey));
23
+ }, [e.environment, e.quote, e.apiKey]), O = a(
20
24
  () => async ({
21
- fromAsset: t,
22
- toAsset: r,
23
- amount: a,
24
- isExactOut: n = !1,
25
- options: d
26
- }) => await (s ? s.quote : p).getQuoteFromAssets({
27
- fromAsset: t,
28
- toAsset: r,
29
- amount: a,
30
- isExactOut: n,
31
- options: d
25
+ fromAsset: r,
26
+ toAsset: l,
27
+ amount: t,
28
+ isExactOut: o = !1,
29
+ options: E
30
+ }) => await (n ? n.quote : u).getQuoteFromAssets({
31
+ fromAsset: r,
32
+ toAsset: l,
33
+ amount: t,
34
+ isExactOut: o,
35
+ options: E
32
36
  }),
33
- [s, p]
34
- ), _ = async (t) => {
35
- if (!s) return v("Garden not initialized");
36
- const r = await s.createSwap(t);
37
- if (!r.val) return v(r.error || "Unknown error occurred");
38
- if (o)
39
- try {
40
- const a = u.getItem(w), n = a ? JSON.parse(a) : [];
41
- typeof r.val == "string" ? n.includes(r.val) || n.push(r.val) : r.val && typeof r.val.order_id == "string" && (n.includes(r.val.order_id) || n.push(r.val.order_id));
42
- const d = Array.from(new Set(n));
43
- u.setItem(w, JSON.stringify(d));
44
- } catch (a) {
45
- console.error("Failed to persist pending order id", a);
46
- }
47
- return P(r.val);
37
+ [n, u]
38
+ ), q = async (r, l) => {
39
+ if (!n) return w("Garden not initialized");
40
+ const t = await n.createSwap(r, l);
41
+ if (!t.val) return w(t.error || "Unknown error occurred");
42
+ try {
43
+ let o;
44
+ typeof t.val == "string" ? o = t.val : t.val && typeof t.val.order_id == "string" && (o = t.val.order_id), o && k.add(i, o);
45
+ } catch (o) {
46
+ console.error("Failed to persist pending order id", o);
47
+ }
48
+ return S(t.val);
48
49
  };
49
- return K(() => {
50
+ return P(() => {
50
51
  if (!("wallets" in e) && !("htlc" in e)) return;
51
- let t;
52
- if ("wallets" in e && Object.keys(e.wallets ?? {}).length > 0 && y(e.wallets ?? {}))
53
- t = c.fromWallets({
54
- ...e,
55
- digestKey: o ? void 0 : l
56
- }).setRedeemServiceEnabled(o);
57
- else if ("htlc" in e && Object.keys(e.htlc ?? {}).length > 0 && y(e.htlc ?? {}))
58
- t = new c({
59
- ...e,
60
- digestKey: o ? void 0 : l
61
- }).setRedeemServiceEnabled(o);
52
+ let r;
53
+ if ("wallets" in e && Object.keys(e.wallets ?? {}).length > 0 && v(e.wallets ?? {}))
54
+ r = p.fromWallets({
55
+ ...e
56
+ });
57
+ else if ("htlc" in e && Object.keys(e.htlc ?? {}).length > 0 && v(e.htlc ?? {}))
58
+ r = new p({
59
+ ...e
60
+ });
62
61
  else
63
62
  return;
64
- O(t);
65
- }, [e, l, o]), /* @__PURE__ */ h.createElement(
66
- f.Provider,
63
+ y(r);
64
+ }, [e]), /* @__PURE__ */ c.createElement(
65
+ h.Provider,
67
66
  {
68
67
  value: {
69
- swap: _,
68
+ swap: q,
70
69
  pendingOrders: G,
71
- getQuote: q,
72
- garden: s,
73
- orderBook: s
70
+ getQuote: O,
71
+ garden: n,
72
+ orderBook: n
74
73
  }
75
74
  },
76
- i
75
+ s
77
76
  );
78
- }, z = () => {
79
- const i = h.useContext(f);
80
- if (!i)
77
+ }, V = () => {
78
+ const s = c.useContext(h);
79
+ if (!s)
81
80
  throw new Error("useGarden must be used within a GardenProvider");
82
- return i;
81
+ return s;
83
82
  };
84
83
  export {
85
- f as GardenContext,
86
- b as GardenProvider,
87
- z as useGarden
84
+ h as GardenContext,
85
+ I as GardenProvider,
86
+ V as useGarden
88
87
  };
package/dist/index3.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("@gardenfi/orderbook"),i=require("react"),R=require("./index6.cjs"),v=(e,u)=>{const[k,y]=i.useState([]),O=i.useRef(null),E=i.useRef(!1),A=i.useRef(!1),_=5e3,m=i.useCallback(()=>{var n,o,f,a,d,s,t,l,c,S,b,N;if(!e)return[];const r=new Set;try{[(o=(n=e.htlcs)==null?void 0:n.evm)==null?void 0:o.htlcActorAddress,(a=(f=e.htlcs)==null?void 0:f.sui)==null?void 0:a.htlcActorAddress,(s=(d=e.htlcs)==null?void 0:d.solana)==null?void 0:s.htlcActorAddress,(l=(t=e.htlcs)==null?void 0:t.starknet)==null?void 0:l.htlcActorAddress,(S=(c=e.htlcs)==null?void 0:c.bitcoin)==null?void 0:S.htlcActorAddress,(N=(b=e.htlcs)==null?void 0:b.tron)==null?void 0:N.htlcActorAddress].filter(g=>!!g&&g.length>0).forEach(g=>r.add(g.toLowerCase()))}catch(T){console.error("Error getting HTLC addresses:",T)}return Array.from(r)},[e]),C=i.useCallback(async()=>{if(e)try{const r=m();if(r.length===0){console.log("No HTLC addresses found for initial pending orders fetch");return}const n=r.map(async s=>{try{const[t,l]=await Promise.all([e.getOrders({address:s,status:h.OrderLifecycle.pending,per_page:500}),e.getOrders({address:s,status:h.OrderLifecycle.notInitiated,per_page:500})]),c=[];return t.ok?c.push(...t.val.data):console.error(`Failed to fetch pending orders for address ${s}:`,t.error),l.ok?c.push(...l.val.data):console.error(`Failed to fetch notInitiated orders for address ${s}:`,l.error),c}catch(t){return console.error(`Error fetching orders for address ${s}:`,t),[]}}),a=(await Promise.all(n)).flat().map(s=>s.order_id),d=Array.from(new Set(a));if(d.length>0)try{u.setItem(R.PENDING_ORDERS_STORE,JSON.stringify(d))}catch(s){console.error("Error saving initial pending order IDs to localStorage",s)}}catch(r){console.error("Error fetching initial pending orders:",r)}},[e,u,m]),I=i.useCallback(async()=>{if(e)try{const r=u.getItem(R.PENDING_ORDERS_STORE),n=r?JSON.parse(r):[],o=Array.from(new Set(n));if(o.length===0){y([]);return}const f=await Promise.all(o.map(t=>e.getOrder(t))),a=[],d=[];f.forEach((t,l)=>{if(!t.ok){d.push(o[l]);return}const c=t.val;c.status===h.OrderStatus.Redeemed||c.status===h.OrderStatus.Refunded||c.status===h.OrderStatus.Expired||(a.push(c),d.push(o[l]))});const s=Array.from(new Set(d));try{u.setItem(R.PENDING_ORDERS_STORE,JSON.stringify(s))}catch(t){console.error("Error persisting remaining pending order ids",t)}y(a)}catch(r){console.error("Error fetching pending orders:",r)}},[e,u]),p=i.useMemo(()=>{try{return m().join(",")}catch(r){return console.error("Error computing HTLC addresses:",r),""}},[m]),P=i.useRef("");return i.useEffect(()=>{if(!e||!e.redeemServiceEnabled||!p)return;P.current!==p&&(A.current=!1,P.current=p),A.current||(C(),A.current=!0)},[e,p,C]),i.useEffect(()=>{if(e)if(e.redeemServiceEnabled){let r=!1;const n=()=>{r||(O.current=setTimeout(o,_))},o=async()=>{if(!r){if(E.current){n();return}E.current=!0;try{await I()}finally{E.current=!1}n()}};return o(),()=>{r=!0,O.current&&(clearTimeout(O.current),O.current=null)}}else{const r=n=>y(n);return e.on("onPendingOrdersChanged",r),()=>{e.off("onPendingOrdersChanged",r)}}},[e,I]),{pendingOrders:k}};exports.useOrderbook=v;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("@gardenfi/orderbook"),w=require("@gardenfi/utils"),n=require("react"),H=require("./index5.cjs"),_=(e,S,a)=>{const[M,g]=n.useState([]),O=n.useRef(null),C=n.useRef(!1),E=n.useRef(!1),k=5e3,h=n.useMemo(()=>new H.PendingOrdersManager(S,w.StoreKeys.PENDING_ORDERS),[S]),m=n.useCallback(()=>{var t,d,f,i,l,s,o,c,u,I,v,L,T,q;if(!e)return[];const r=new Set;try{[(d=(t=e.htlcs)==null?void 0:t.evm)==null?void 0:d.htlcActorAddress,(i=(f=e.htlcs)==null?void 0:f.sui)==null?void 0:i.htlcActorAddress,(s=(l=e.htlcs)==null?void 0:l.solana)==null?void 0:s.htlcActorAddress,(c=(o=e.htlcs)==null?void 0:o.starknet)==null?void 0:c.htlcActorAddress,(I=(u=e.htlcs)==null?void 0:u.bitcoin)==null?void 0:I.htlcActorAddress,(L=(v=e.htlcs)==null?void 0:v.tron)==null?void 0:L.htlcActorAddress,(q=(T=e.htlcs)==null?void 0:T.xrpl)==null?void 0:q.htlcActorAddress].filter(y=>!!y&&y.length>0).forEach(y=>r.add(y.toLowerCase()))}catch(F){console.error("Error getting HTLC addresses:",F)}return Array.from(r)},[e]),R=n.useCallback(async()=>{if(e)try{const r=m();if(r.length===0){console.log("No HTLC addresses found for initial pending orders fetch");return}const t=r.map(async s=>{try{const[o,c]=await Promise.all([e.getOrders({address:s,status:p.OrderLifecycle.pending,per_page:500}),e.getOrders({address:s,status:p.OrderLifecycle.notInitiated,per_page:500})]),u=[];return o.ok?u.push(...o.val.data):console.error(`Failed to fetch pending orders for address ${s}:`,o.error),c.ok?u.push(...c.val.data):console.error(`Failed to fetch notInitiated orders for address ${s}:`,c.error),u}catch(o){return console.error(`Error fetching orders for address ${s}:`,o),[]}}),i=(await Promise.all(t)).flat().map(s=>s.order_id),l=Array.from(new Set(i));l.length>0&&h.set(a,l)}catch(r){console.error("Error fetching initial pending orders:",r)}},[e,h,m,a]),P=n.useCallback(async()=>{if(e)try{const r=h.get(a),t=Array.from(new Set(r));if(t.length===0){g([]);return}const d=await Promise.all(t.map(s=>e.getOrder(s))),f=[],i=[];d.forEach((s,o)=>{if(!s.ok){i.push(t[o]);return}const c=s.val;c.status===p.OrderStatus.Redeemed||c.status===p.OrderStatus.Refunded||c.status===p.OrderStatus.Expired||(f.push(c),i.push(t[o]))});const l=Array.from(new Set(i));h.set(a,l),g(f)}catch(r){console.error("Error fetching pending orders:",r)}},[e,h,a]),A=n.useMemo(()=>{try{return m().join(",")}catch(r){return console.error("Error computing HTLC addresses:",r),""}},[m]),b=n.useRef("");return n.useEffect(()=>{if(!e||!e.redeemServiceEnabled||!A)return;b.current!==A&&(E.current=!1,b.current=A),E.current||(R(),E.current=!0)},[e,A,R,a]),n.useEffect(()=>{if(e)if(e.redeemServiceEnabled){let r=!1;const t=()=>{r||(O.current=setTimeout(d,k))},d=async()=>{if(!r){if(C.current){t();return}C.current=!0;try{await P()}finally{C.current=!1}t()}};return d(),()=>{r=!0,O.current&&(clearTimeout(O.current),O.current=null)}}else{const r=t=>g(t);return e.on("onPendingOrdersChanged",r),()=>{e.off("onPendingOrdersChanged",r)}}},[e,P]),{pendingOrders:M}};exports.useOrderbook=_;
package/dist/index3.js CHANGED
@@ -1,140 +1,132 @@
1
- import { OrderLifecycle as N, OrderStatus as S } from "@gardenfi/orderbook";
2
- import { useState as _, useRef as g, useCallback as C, useMemo as D, useEffect as b } from "react";
3
- import { PENDING_ORDERS_STORE as I } from "./index6.js";
4
- const J = (r, a) => {
5
- const [k, O] = _([]), f = g(null), y = g(!1), A = g(!1), F = 5e3, h = C(() => {
6
- var n, o, u, l, i, s, t, d, c, E, v, T;
1
+ import { OrderLifecycle as _, OrderStatus as C } from "@gardenfi/orderbook";
2
+ import { StoreKeys as M } from "@gardenfi/utils";
3
+ import { useState as $, useRef as O, useMemo as D, useCallback as P, useEffect as N } from "react";
4
+ import { PendingOrdersManager as j } from "./index5.js";
5
+ const z = (r, S, a) => {
6
+ const [q, y] = $([]), h = O(null), g = O(!1), E = O(!1), x = 5e3, f = D(
7
+ () => new j(S, M.PENDING_ORDERS),
8
+ [S]
9
+ ), m = P(() => {
10
+ var t, c, u, i, d, s, o, n, l, L, T, b, F, w;
7
11
  if (!r) return [];
8
12
  const e = /* @__PURE__ */ new Set();
9
13
  try {
10
14
  [
11
- (o = (n = r.htlcs) == null ? void 0 : n.evm) == null ? void 0 : o.htlcActorAddress,
12
- (l = (u = r.htlcs) == null ? void 0 : u.sui) == null ? void 0 : l.htlcActorAddress,
13
- (s = (i = r.htlcs) == null ? void 0 : i.solana) == null ? void 0 : s.htlcActorAddress,
14
- (d = (t = r.htlcs) == null ? void 0 : t.starknet) == null ? void 0 : d.htlcActorAddress,
15
- (E = (c = r.htlcs) == null ? void 0 : c.bitcoin) == null ? void 0 : E.htlcActorAddress,
16
- (T = (v = r.htlcs) == null ? void 0 : v.tron) == null ? void 0 : T.htlcActorAddress
17
- ].filter((p) => !!p && p.length > 0).forEach((p) => e.add(p.toLowerCase()));
18
- } catch (L) {
19
- console.error("Error getting HTLC addresses:", L);
15
+ (c = (t = r.htlcs) == null ? void 0 : t.evm) == null ? void 0 : c.htlcActorAddress,
16
+ (i = (u = r.htlcs) == null ? void 0 : u.sui) == null ? void 0 : i.htlcActorAddress,
17
+ (s = (d = r.htlcs) == null ? void 0 : d.solana) == null ? void 0 : s.htlcActorAddress,
18
+ (n = (o = r.htlcs) == null ? void 0 : o.starknet) == null ? void 0 : n.htlcActorAddress,
19
+ (L = (l = r.htlcs) == null ? void 0 : l.bitcoin) == null ? void 0 : L.htlcActorAddress,
20
+ (b = (T = r.htlcs) == null ? void 0 : T.tron) == null ? void 0 : b.htlcActorAddress,
21
+ (w = (F = r.htlcs) == null ? void 0 : F.xrpl) == null ? void 0 : w.htlcActorAddress
22
+ ].filter((A) => !!A && A.length > 0).forEach((A) => e.add(A.toLowerCase()));
23
+ } catch (H) {
24
+ console.error("Error getting HTLC addresses:", H);
20
25
  }
21
26
  return Array.from(e);
22
- }, [r]), P = C(async () => {
27
+ }, [r]), I = P(async () => {
23
28
  if (r)
24
29
  try {
25
- const e = h();
30
+ const e = m();
26
31
  if (e.length === 0) {
27
32
  console.log("No HTLC addresses found for initial pending orders fetch");
28
33
  return;
29
34
  }
30
- const n = e.map(async (s) => {
35
+ const t = e.map(async (s) => {
31
36
  try {
32
- const [t, d] = await Promise.all([
37
+ const [o, n] = await Promise.all([
33
38
  r.getOrders({
34
39
  address: s,
35
- status: N.pending,
40
+ status: _.pending,
36
41
  per_page: 500
37
42
  }),
38
43
  r.getOrders({
39
44
  address: s,
40
- status: N.notInitiated,
45
+ status: _.notInitiated,
41
46
  per_page: 500
42
47
  })
43
- ]), c = [];
44
- return t.ok ? c.push(...t.val.data) : console.error(
48
+ ]), l = [];
49
+ return o.ok ? l.push(...o.val.data) : console.error(
45
50
  `Failed to fetch pending orders for address ${s}:`,
46
- t.error
47
- ), d.ok ? c.push(...d.val.data) : console.error(
51
+ o.error
52
+ ), n.ok ? l.push(...n.val.data) : console.error(
48
53
  `Failed to fetch notInitiated orders for address ${s}:`,
49
- d.error
50
- ), c;
51
- } catch (t) {
52
- return console.error(`Error fetching orders for address ${s}:`, t), [];
53
- }
54
- }), l = (await Promise.all(n)).flat().map((s) => s.order_id), i = Array.from(new Set(l));
55
- if (i.length > 0)
56
- try {
57
- a.setItem(I, JSON.stringify(i));
58
- } catch (s) {
59
- console.error(
60
- "Error saving initial pending order IDs to localStorage",
61
- s
62
- );
54
+ n.error
55
+ ), l;
56
+ } catch (o) {
57
+ return console.error(`Error fetching orders for address ${s}:`, o), [];
63
58
  }
59
+ }), i = (await Promise.all(t)).flat().map((s) => s.order_id), d = Array.from(new Set(i));
60
+ d.length > 0 && f.set(a, d);
64
61
  } catch (e) {
65
62
  console.error("Error fetching initial pending orders:", e);
66
63
  }
67
- }, [r, a, h]), R = C(async () => {
64
+ }, [r, f, m, a]), R = P(async () => {
68
65
  if (r)
69
66
  try {
70
- const e = a.getItem(I), n = e ? JSON.parse(e) : [], o = Array.from(new Set(n));
71
- if (o.length === 0) {
72
- O([]);
67
+ const e = f.get(a), t = Array.from(new Set(e));
68
+ if (t.length === 0) {
69
+ y([]);
73
70
  return;
74
71
  }
75
- const u = await Promise.all(
76
- o.map((t) => r.getOrder(t))
77
- ), l = [], i = [];
78
- u.forEach((t, d) => {
79
- if (!t.ok) {
80
- i.push(o[d]);
72
+ const c = await Promise.all(
73
+ t.map((s) => r.getOrder(s))
74
+ ), u = [], i = [];
75
+ c.forEach((s, o) => {
76
+ if (!s.ok) {
77
+ i.push(t[o]);
81
78
  return;
82
79
  }
83
- const c = t.val;
84
- c.status === S.Redeemed || c.status === S.Refunded || c.status === S.Expired || (l.push(c), i.push(o[d]));
80
+ const n = s.val;
81
+ n.status === C.Redeemed || n.status === C.Refunded || n.status === C.Expired || (u.push(n), i.push(t[o]));
85
82
  });
86
- const s = Array.from(new Set(i));
87
- try {
88
- a.setItem(I, JSON.stringify(s));
89
- } catch (t) {
90
- console.error("Error persisting remaining pending order ids", t);
91
- }
92
- O(l);
83
+ const d = Array.from(new Set(i));
84
+ f.set(a, d), y(u);
93
85
  } catch (e) {
94
86
  console.error("Error fetching pending orders:", e);
95
87
  }
96
- }, [r, a]), m = D(() => {
88
+ }, [r, f, a]), p = D(() => {
97
89
  try {
98
- return h().join(",");
90
+ return m().join(",");
99
91
  } catch (e) {
100
92
  return console.error("Error computing HTLC addresses:", e), "";
101
93
  }
102
- }, [h]), w = g("");
103
- return b(() => {
104
- if (!r || !r.redeemServiceEnabled || !m) return;
105
- w.current !== m && (A.current = !1, w.current = m), A.current || (P(), A.current = !0);
106
- }, [r, m, P]), b(() => {
94
+ }, [m]), v = O("");
95
+ return N(() => {
96
+ if (!r || !r.redeemServiceEnabled || !p) return;
97
+ v.current !== p && (E.current = !1, v.current = p), E.current || (I(), E.current = !0);
98
+ }, [r, p, I, a]), N(() => {
107
99
  if (r)
108
100
  if (r.redeemServiceEnabled) {
109
101
  let e = !1;
110
- const n = () => {
111
- e || (f.current = setTimeout(o, F));
112
- }, o = async () => {
102
+ const t = () => {
103
+ e || (h.current = setTimeout(c, x));
104
+ }, c = async () => {
113
105
  if (!e) {
114
- if (y.current) {
115
- n();
106
+ if (g.current) {
107
+ t();
116
108
  return;
117
109
  }
118
- y.current = !0;
110
+ g.current = !0;
119
111
  try {
120
112
  await R();
121
113
  } finally {
122
- y.current = !1;
114
+ g.current = !1;
123
115
  }
124
- n();
116
+ t();
125
117
  }
126
118
  };
127
- return o(), () => {
128
- e = !0, f.current && (clearTimeout(f.current), f.current = null);
119
+ return c(), () => {
120
+ e = !0, h.current && (clearTimeout(h.current), h.current = null);
129
121
  };
130
122
  } else {
131
- const e = (n) => O(n);
123
+ const e = (t) => y(t);
132
124
  return r.on("onPendingOrdersChanged", e), () => {
133
125
  r.off("onPendingOrdersChanged", e);
134
126
  };
135
127
  }
136
- }, [r, R]), { pendingOrders: k };
128
+ }, [r, R]), { pendingOrders: q };
137
129
  };
138
130
  export {
139
- J as useOrderbook
131
+ z as useOrderbook
140
132
  };
package/dist/index5.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("@gardenfi/utils"),e=require("./index6.cjs"),y=require("react"),f=(a=!0)=>{const[E,g]=y.useState();return y.useEffect(()=>{if(a)return;if(!indexedDB){console.error("IndexedDB is not supported in this browser");return}let o;const d=indexedDB.open(e.DB_NAME,e.VERSION);d.onerror=s=>{console.error("IndexedDB error:",s.target.error)},d.onupgradeneeded=s=>{const n=s.target.result;n.objectStoreNames.contains(e.STORE_NAME)||n.createObjectStore(e.STORE_NAME,{keyPath:"id"})},d.onsuccess=s=>{if(o=s.target.result,!o.objectStoreNames.contains(e.STORE_NAME)){o.close();const r=indexedDB.open(e.DB_NAME,o.version+1);r.onupgradeneeded=n=>{n.target.result.createObjectStore(e.STORE_NAME,{keyPath:"id"})},r.onsuccess=()=>{l(r.result)};return}l(o)};function l(s){try{const r=s.transaction(e.STORE_NAME,"readwrite"),n=r.objectStore(e.STORE_NAME),c=n.get(e.DIGEST_KEY);c.onsuccess=()=>{if(c.result){const i=u.DigestKey.from(c.result.value);if(!i.error){g(i.val);return}}const t=u.DigestKey.generateRandom();if(!t.ok){console.error("Error generating new digest key:",t.error);return}if(a)g(u.DigestKey.from(t.val.digestKey).val);else{const i=n.put({id:e.DIGEST_KEY,value:t.val.digestKey});i.onsuccess=()=>{g(u.DigestKey.from(t.val.digestKey).val)},i.onerror=D=>{console.error("Error storing new digest key:",D)}}},c.onerror=t=>{console.error("Error retrieving digest key:",t)},r.oncomplete=()=>{},r.onerror=t=>{console.error("Error in digestKey transaction:",t)}}catch(r){console.error("Transaction error:",r)}}return()=>{o&&o.close()}},[a]),{digestKey:E}};exports.useDigestKey=f;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("@gardenfi/utils");class i{constructor(t,e){this.store=t,this.storeKey=e,this.defaultStorage={mainnet:[],testnet:[],staging:[]}}getNetworkKey(t){if(!t)return"mainnet";const e=String(t).toLowerCase();return e.includes("staging")?"staging":e===a.Network.TESTNET?"testnet":(e===a.Network.MAINNET||e===a.Network.LOCALNET,"mainnet")}getStorageData(){try{const t=this.store.getItem(this.storeKey);return t?JSON.parse(t):{...this.defaultStorage}}catch{return{...this.defaultStorage}}}saveStorageData(t){try{this.store.setItem(this.storeKey,JSON.stringify(t))}catch(e){console.error("Error saving pending orders to storage:",e)}}get(t){const e=this.getStorageData(),r=this.getNetworkKey(t);return e[r]||[]}set(t,e){const r=this.getStorageData(),s=this.getNetworkKey(t);r[s]=Array.from(new Set(e)),this.saveStorageData(r)}add(t,e){const r=this.get(t);r.includes(e)||this.set(t,[...r,e])}remove(t,e){const r=this.get(t);this.set(t,r.filter(s=>s!==e))}clear(t){t?this.set(t,[]):this.saveStorageData({...this.defaultStorage})}}exports.PendingOrdersManager=i;
package/dist/index5.js CHANGED
@@ -1,82 +1,55 @@
1
- import { DigestKey as a } from "@gardenfi/utils";
2
- import { DB_NAME as f, VERSION as m, STORE_NAME as n, DIGEST_KEY as y } from "./index6.js";
3
- import { useState as K, useEffect as E } from "react";
4
- const S = (u = !0) => {
5
- const [p, d] = K();
6
- return E(() => {
7
- if (u)
8
- return;
9
- if (!indexedDB) {
10
- console.error("IndexedDB is not supported in this browser");
11
- return;
12
- }
13
- let t;
14
- const g = indexedDB.open(f, m);
15
- g.onerror = (o) => {
16
- console.error(
17
- "IndexedDB error:",
18
- o.target.error
19
- );
20
- }, g.onupgradeneeded = (o) => {
21
- const s = o.target.result;
22
- s.objectStoreNames.contains(n) || s.createObjectStore(n, { keyPath: "id" });
23
- }, g.onsuccess = (o) => {
24
- if (t = o.target.result, !t.objectStoreNames.contains(n)) {
25
- t.close();
26
- const e = indexedDB.open(f, t.version + 1);
27
- e.onupgradeneeded = (s) => {
28
- s.target.result.createObjectStore(n, { keyPath: "id" });
29
- }, e.onsuccess = () => {
30
- l(e.result);
31
- };
32
- return;
33
- }
34
- l(t);
1
+ import { Network as a } from "@gardenfi/utils";
2
+ class o {
3
+ constructor(t, e) {
4
+ this.store = t, this.storeKey = e, this.defaultStorage = {
5
+ mainnet: [],
6
+ testnet: [],
7
+ staging: []
35
8
  };
36
- function l(o) {
37
- try {
38
- const e = o.transaction(n, "readwrite"), s = e.objectStore(n), c = s.get(y);
39
- c.onsuccess = () => {
40
- if (c.result) {
41
- const i = a.from(c.result.value);
42
- if (!i.error) {
43
- d(i.val);
44
- return;
45
- }
46
- }
47
- const r = a.generateRandom();
48
- if (!r.ok) {
49
- console.error("Error generating new digest key:", r.error);
50
- return;
51
- }
52
- if (u)
53
- d(a.from(r.val.digestKey).val);
54
- else {
55
- const i = s.put({
56
- id: y,
57
- value: r.val.digestKey
58
- });
59
- i.onsuccess = () => {
60
- d(a.from(r.val.digestKey).val);
61
- }, i.onerror = (D) => {
62
- console.error("Error storing new digest key:", D);
63
- };
64
- }
65
- }, c.onerror = (r) => {
66
- console.error("Error retrieving digest key:", r);
67
- }, e.oncomplete = () => {
68
- }, e.onerror = (r) => {
69
- console.error("Error in digestKey transaction:", r);
70
- };
71
- } catch (e) {
72
- console.error("Transaction error:", e);
73
- }
9
+ }
10
+ getNetworkKey(t) {
11
+ if (!t) return "mainnet";
12
+ const e = String(t).toLowerCase();
13
+ return e.includes("staging") ? "staging" : e === a.TESTNET ? "testnet" : (e === a.MAINNET || e === a.LOCALNET, "mainnet");
14
+ }
15
+ getStorageData() {
16
+ try {
17
+ const t = this.store.getItem(this.storeKey);
18
+ return t ? JSON.parse(t) : { ...this.defaultStorage };
19
+ } catch {
20
+ return { ...this.defaultStorage };
74
21
  }
75
- return () => {
76
- t && t.close();
77
- };
78
- }, [u]), { digestKey: p };
79
- };
22
+ }
23
+ saveStorageData(t) {
24
+ try {
25
+ this.store.setItem(this.storeKey, JSON.stringify(t));
26
+ } catch (e) {
27
+ console.error("Error saving pending orders to storage:", e);
28
+ }
29
+ }
30
+ get(t) {
31
+ const e = this.getStorageData(), r = this.getNetworkKey(t);
32
+ return e[r] || [];
33
+ }
34
+ set(t, e) {
35
+ const r = this.getStorageData(), s = this.getNetworkKey(t);
36
+ r[s] = Array.from(new Set(e)), this.saveStorageData(r);
37
+ }
38
+ add(t, e) {
39
+ const r = this.get(t);
40
+ r.includes(e) || this.set(t, [...r, e]);
41
+ }
42
+ remove(t, e) {
43
+ const r = this.get(t);
44
+ this.set(
45
+ t,
46
+ r.filter((s) => s !== e)
47
+ );
48
+ }
49
+ clear(t) {
50
+ t ? this.set(t, []) : this.saveStorageData({ ...this.defaultStorage });
51
+ }
52
+ }
80
53
  export {
81
- S as useDigestKey
54
+ o as PendingOrdersManager
82
55
  };
@@ -2,4 +2,3 @@ export declare const DB_NAME = "garden-finance-db";
2
2
  export declare const STORE_NAME = "garden-finance-store";
3
3
  export declare const DIGEST_KEY = "digest-key";
4
4
  export declare const VERSION = 1;
5
- export declare const PENDING_ORDERS_STORE = "orders-in-progress";
@@ -1,4 +1,4 @@
1
- import { OrderWithStatus, QuoteParamsForAssets, IGardenJS, QuoteResponse, SwapParams, GardenConfigWithHTLCs, GardenConfigWithWallets } from '@gardenfi/core';
1
+ import { OrderWithStatus, QuoteParamsForAssets, OrderCreationStatus, IGardenJS, QuoteResponse, SwapParams, GardenConfigWithHTLCs, GardenConfigWithWallets } from '@gardenfi/core';
2
2
  import { CreateOrderResponse, IOrderbook } from '@gardenfi/orderbook';
3
3
  import { AsyncResult, IStore } from '@gardenfi/utils';
4
4
 
@@ -11,9 +11,10 @@ export type GardenContextType = {
11
11
  /**
12
12
  * Create an order and wait until its matched and then initiates if source chain is EVM.
13
13
  * @params {SwapParams} - The parameters for creating the order.
14
+ * @params onProgress - Optional callback for progress messages: 'order created', 'order initiating', 'order initiated'.
14
15
  * @returns {AsyncResult<string, string>} - create order ID.
15
16
  */
16
- swap?: (params: SwapParams) => AsyncResult<CreateOrderResponse | string, string>;
17
+ swap?: (params: SwapParams, onProgress?: (status: OrderCreationStatus) => void) => AsyncResult<CreateOrderResponse | string, string>;
17
18
  /**
18
19
  * Get all the pending orders of the user. This will return all the orders that are yet to be initiated, redeemed, or refunded.
19
20
  * It will not return orders that have expired (deadline expiry).
@@ -36,11 +37,4 @@ export type GardenProviderProps = {
36
37
  children: React.ReactNode;
37
38
  config: Omit<GardenConfigWithHTLCs, 'digestKey'> | Omit<GardenConfigWithWallets, 'digestKey'>;
38
39
  store: IStore;
39
- /**
40
- * Controls whether the redeem service is enabled.
41
- * - When `true` (default): Manual order fetching with digestKey required
42
- * - When `false`: Event-based order updates, no digestKey required
43
- * @default true
44
- */
45
- setRedeemServiceEnabled?: boolean;
46
40
  };
@@ -1,6 +1,6 @@
1
1
  import { IGardenJS, OrderWithStatus } from '@gardenfi/core';
2
- import { IStore } from '@gardenfi/utils';
2
+ import { IStore, Network } from '@gardenfi/utils';
3
3
 
4
- export declare const useOrderbook: (garden: IGardenJS | undefined, store: IStore) => {
4
+ export declare const useOrderbook: (garden: IGardenJS | undefined, store: IStore, network?: Network | string) => {
5
5
  pendingOrders: OrderWithStatus[];
6
6
  };
@@ -0,0 +1,16 @@
1
+ import { Network, IStore, StoreKeys } from '@gardenfi/utils';
2
+
3
+ export declare class PendingOrdersManager {
4
+ private readonly store;
5
+ private readonly storeKey;
6
+ private readonly defaultStorage;
7
+ constructor(store: IStore, storeKey: StoreKeys);
8
+ private getNetworkKey;
9
+ private getStorageData;
10
+ private saveStorageData;
11
+ get(network?: Network | string): string[];
12
+ set(network: Network | string | undefined, orderIds: string[]): void;
13
+ add(network: Network | string | undefined, orderId: string): void;
14
+ remove(network: Network | string | undefined, orderId: string): void;
15
+ clear(network?: Network | string): void;
16
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gardenfi/react-hooks",
3
- "version": "3.0.7",
3
+ "version": "3.1.0-beta.2",
4
4
  "type": "module",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
@@ -27,11 +27,11 @@
27
27
  "registry": "https://registry.npmjs.org/"
28
28
  },
29
29
  "dependencies": {
30
- "@gardenfi/core": "3.0.8",
31
- "@gardenfi/orderbook": "3.0.6",
32
- "@gardenfi/utils": "3.0.0",
30
+ "@gardenfi/core": "3.1.0-beta.2",
31
+ "@gardenfi/orderbook": "3.1.0-beta.2",
32
+ "@gardenfi/utils": "3.1.0-beta.2",
33
33
  "react": "^18.3.1",
34
- "starknet": "7.6.4"
34
+ "starknet": "8.0.0"
35
35
  },
36
36
  "devDependencies": {
37
37
  "@types/react": "^18",
package/dist/index6.cjs DELETED
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const E="garden-finance-db",e="garden-finance-store",n="digest-key",t=1,o="orders-in-progress";exports.DB_NAME=E;exports.DIGEST_KEY=n;exports.PENDING_ORDERS_STORE=o;exports.STORE_NAME=e;exports.VERSION=t;
package/dist/index6.js DELETED
@@ -1,8 +0,0 @@
1
- const n = "garden-finance-db", e = "garden-finance-store", s = "digest-key", o = 1, E = "orders-in-progress";
2
- export {
3
- n as DB_NAME,
4
- s as DIGEST_KEY,
5
- E as PENDING_ORDERS_STORE,
6
- e as STORE_NAME,
7
- o as VERSION
8
- };