@gardenfi/orderbook 2.5.3-beta.0 → 2.5.3-beta.10

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.
Files changed (43) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.js +52 -41
  3. package/dist/index10.cjs +1 -0
  4. package/dist/index10.js +225 -0
  5. package/dist/index11.cjs +1 -0
  6. package/dist/index11.js +226 -0
  7. package/dist/index12.cjs +1 -0
  8. package/dist/index12.js +21 -0
  9. package/dist/index2.cjs +1 -1
  10. package/dist/index2.js +35 -20
  11. package/dist/index3.cjs +1 -1
  12. package/dist/index3.js +2 -642
  13. package/dist/index4.cjs +1 -1
  14. package/dist/index4.js +950 -135
  15. package/dist/index5.cjs +1 -1
  16. package/dist/index5.js +92 -32
  17. package/dist/index6.cjs +1 -1
  18. package/dist/index6.js +15 -58
  19. package/dist/index7.cjs +1 -0
  20. package/dist/index7.js +46 -0
  21. package/dist/index8.cjs +1 -0
  22. package/dist/index8.js +28 -0
  23. package/dist/index9.cjs +1 -0
  24. package/dist/index9.js +31 -0
  25. package/dist/src/index.d.ts +11 -4
  26. package/dist/src/lib/asset.d.ts +0 -210
  27. package/dist/src/lib/assetManager/AssetManager.d.ts +94 -0
  28. package/dist/src/lib/assetManager/index.d.ts +2 -0
  29. package/dist/src/lib/assetManager/routeValidator/routeValidator.d.ts +90 -0
  30. package/dist/src/lib/assetManager/types.d.ts +39 -0
  31. package/dist/src/lib/assetManager/utils.d.ts +6 -0
  32. package/dist/src/lib/chainAsset/chainAsset.d.ts +10 -11
  33. package/dist/src/lib/constants/asset.d.ts +2012 -0
  34. package/dist/src/lib/constants/asset.types.d.ts +43 -0
  35. package/dist/src/lib/constants/localnetConstants.d.ts +47 -0
  36. package/dist/src/lib/constants/utils.d.ts +15 -0
  37. package/dist/src/lib/orderStatus/orderStatus.d.ts +14 -0
  38. package/dist/src/lib/orderStatus/status.d.ts +0 -0
  39. package/dist/src/lib/orderbook/orderbook.d.ts +6 -5
  40. package/dist/src/lib/orderbook/orderbook.types.d.ts +24 -18
  41. package/dist/src/lib/utils.d.ts +2 -2
  42. package/package.json +4 -3
  43. package/dist/src/lib/constants.d.ts +0 -827
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("./index2.cjs"),s=require("./index3.cjs"),e=require("./index4.cjs"),t=require("./index5.cjs"),n=require("./index6.cjs");exports.Orderbook=i.Orderbook;exports.ArbitrumLocalnet=s.ArbitrumLocalnet;exports.Assets=s.Assets;exports.ETHStarknetLocalnetAsset=s.ETHStarknetLocalnetAsset;exports.EthereumLocalnet=s.EthereumLocalnet;exports.SOLSolanaLocalnetAsset=s.SOLSolanaLocalnetAsset;exports.STRKStarknetLocalnetAsset=s.STRKStarknetLocalnetAsset;exports.StarknetLocalnet=s.StarknetLocalnet;exports.SupportedAssets=s.SupportedAssets;exports.WBTCArbitrumLocalnetAsset=s.WBTCArbitrumLocalnetAsset;exports.WBTCEthereumLocalnetAsset=s.WBTCEthereumLocalnetAsset;exports.bitcoinRegtestAsset=s.bitcoinRegtestAsset;exports.BlockchainType=e.BlockchainType;exports.Chains=e.Chains;exports.ChainsConfig=e.ChainsConfig;exports.NATIVE_TOKENS=e.NATIVE_TOKENS;exports.NativeTokenAddress=e.NativeTokenAddress;exports.NetworkType=e.NetworkType;exports.OrderLifecycle=e.OrderLifecycle;exports.getBlockchainType=e.getBlockchainType;exports.getChainTypeFromAssetChain=e.getChainTypeFromAssetChain;exports.getChainsFromOrder=e.getChainsFromOrder;exports.isBitcoin=e.isBitcoin;exports.isEVM=e.isEVM;exports.isEvmNativeToken=e.isEvmNativeToken;exports.isMainnet=e.isMainnet;exports.isNativeToken=e.isNativeToken;exports.isSolana=e.isSolana;exports.isSolanaNativeToken=e.isSolanaNativeToken;exports.isStarknet=e.isStarknet;exports.isSui=e.isSui;exports.isSuiNativeToken=e.isSuiNativeToken;exports.ConstructUrl=t.ConstructUrl;exports.discriminateOrderResponse=t.discriminateOrderResponse;exports.getOrderResponseType=t.getOrderResponseType;exports.isBitcoinOrderResponse=t.isBitcoinOrderResponse;exports.isEvmOrderResponse=t.isEvmOrderResponse;exports.isOrder=t.isOrder;exports.isSolanaOrderResponse=t.isSolanaOrderResponse;exports.isStarknetOrderResponse=t.isStarknetOrderResponse;exports.isSuiOrderResponse=t.isSuiOrderResponse;exports.ChainAsset=n.ChainAsset;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./index2.cjs"),a=require("./index3.cjs"),e=require("./index4.cjs"),s=require("./index5.cjs"),o=require("./index6.cjs"),t=require("./index7.cjs"),c=require("./index8.cjs"),i=require("./index9.cjs"),l=require("./index10.cjs"),r=require("./index11.cjs");exports.Orderbook=n.Orderbook;exports.BlockchainType=a.BlockchainType;exports.Assets=e.Assets;exports.Chains=e.Chains;exports.Config=e.Config;exports.NATIVE_TOKENS=e.NATIVE_TOKENS;exports.OrderLifecycle=e.OrderLifecycle;exports.OrderStatus=e.OrderStatus;exports.getBlockchainType=e.getBlockchainType;exports.is=e.is;exports.isBitcoin=e.isBitcoin;exports.isEVM=e.isEVM;exports.isEvmNativeToken=e.isEvmNativeToken;exports.isMainnet=e.isMainnet;exports.isNativeToken=e.isNativeToken;exports.isSolana=e.isSolana;exports.isSolanaNativeToken=e.isSolanaNativeToken;exports.isStarknet=e.isStarknet;exports.isSui=e.isSui;exports.isSuiNativeToken=e.isSuiNativeToken;exports.ArbitrumLocalnet=s.ArbitrumLocalnet;exports.ETHStarknetLocalnetAsset=s.ETHStarknetLocalnetAsset;exports.EthereumLocalnet=s.EthereumLocalnet;exports.SOLSolanaLocalnetAsset=s.SOLSolanaLocalnetAsset;exports.STRKStarknetLocalnetAsset=s.STRKStarknetLocalnetAsset;exports.StarknetLocalnet=s.StarknetLocalnet;exports.WBTCArbitrumLocalnetAsset=s.WBTCArbitrumLocalnetAsset;exports.WBTCEthereumLocalnetAsset=s.WBTCEthereumLocalnetAsset;exports.bitcoinRegtestAsset=s.bitcoinRegtestAsset;exports.buildAssetsWithChain=o.buildAssetsWithChain;exports.ConstructUrl=t.ConstructUrl;exports.discriminateOrderResponse=t.discriminateOrderResponse;exports.getOrderResponseType=t.getOrderResponseType;exports.isBitcoinOrderResponse=t.isBitcoinOrderResponse;exports.isEvmOrderResponse=t.isEvmOrderResponse;exports.isOrder=t.isOrder;exports.isSolanaOrderResponse=t.isSolanaOrderResponse;exports.isStarknetOrderResponse=t.isStarknetOrderResponse;exports.isSuiOrderResponse=t.isSuiOrderResponse;exports.ChainAsset=c.ChainAsset;exports.OrderAction=i.OrderAction;exports.ParseOrderStatus=i.ParseOrderStatus;exports.isCompleted=i.isCompleted;exports.isDeadlinePassed=i.isDeadlinePassed;exports.parseAction=i.parseAction;exports.AssetManager=l.AssetManager;exports.RouteValidator=r.RouteValidator;exports.buildRouteMatrix=r.buildRouteMatrix;
package/dist/index.js CHANGED
@@ -1,49 +1,60 @@
1
- import { Orderbook as t } from "./index2.js";
2
- import { ArbitrumLocalnet as o, Assets as i, ETHStarknetLocalnetAsset as n, EthereumLocalnet as a, SOLSolanaLocalnetAsset as c, STRKStarknetLocalnetAsset as p, StarknetLocalnet as l, SupportedAssets as S, WBTCArbitrumLocalnetAsset as T, WBTCEthereumLocalnetAsset as d, bitcoinRegtestAsset as k } from "./index3.js";
3
- import { BlockchainType as A, Chains as O, ChainsConfig as h, NATIVE_TOKENS as C, NativeTokenAddress as L, NetworkType as u, OrderLifecycle as R, getBlockchainType as E, getChainTypeFromAssetChain as N, getChainsFromOrder as f, isBitcoin as v, isEVM as g, isEvmNativeToken as y, isMainnet as B, isNativeToken as x, isSolana as b, isSolanaNativeToken as F, isStarknet as K, isSui as M, isSuiNativeToken as V } from "./index4.js";
4
- import { ConstructUrl as w, discriminateOrderResponse as H, getOrderResponseType as I, isBitcoinOrderResponse as U, isEvmOrderResponse as _, isOrder as j, isSolanaOrderResponse as q, isStarknetOrderResponse as z, isSuiOrderResponse as D } from "./index5.js";
5
- import { ChainAsset as J } from "./index6.js";
1
+ import { Orderbook as r } from "./index2.js";
2
+ import { BlockchainType as o } from "./index3.js";
3
+ import { Assets as n, Chains as a, Config as p, NATIVE_TOKENS as c, OrderLifecycle as l, OrderStatus as d, getBlockchainType as m, is as S, isBitcoin as A, isEVM as O, isEvmNativeToken as u, isMainnet as T, isNativeToken as f, isSolana as k, isSolanaNativeToken as x, isStarknet as R, isSui as L, isSuiNativeToken as h } from "./index4.js";
4
+ import { ArbitrumLocalnet as E, ETHStarknetLocalnetAsset as b, EthereumLocalnet as v, SOLSolanaLocalnetAsset as B, STRKStarknetLocalnetAsset as N, StarknetLocalnet as g, WBTCArbitrumLocalnetAsset as y, WBTCEthereumLocalnetAsset as M, bitcoinRegtestAsset as V } from "./index5.js";
5
+ import { buildAssetsWithChain as K } from "./index6.js";
6
+ import { ConstructUrl as D, discriminateOrderResponse as H, getOrderResponseType as I, isBitcoinOrderResponse as U, isEvmOrderResponse as _, isOrder as j, isSolanaOrderResponse as q, isStarknetOrderResponse as w, isSuiOrderResponse as z } from "./index7.js";
7
+ import { ChainAsset as G } from "./index8.js";
8
+ import { OrderAction as Q, ParseOrderStatus as X, isCompleted as Y, isDeadlinePassed as Z, parseAction as $ } from "./index9.js";
9
+ import { AssetManager as te } from "./index10.js";
10
+ import { RouteValidator as se, buildRouteMatrix as oe } from "./index11.js";
6
11
  export {
7
- o as ArbitrumLocalnet,
8
- i as Assets,
9
- A as BlockchainType,
10
- J as ChainAsset,
11
- O as Chains,
12
- h as ChainsConfig,
13
- w as ConstructUrl,
14
- n as ETHStarknetLocalnetAsset,
15
- a as EthereumLocalnet,
16
- C as NATIVE_TOKENS,
17
- L as NativeTokenAddress,
18
- u as NetworkType,
19
- R as OrderLifecycle,
20
- t as Orderbook,
21
- c as SOLSolanaLocalnetAsset,
22
- p as STRKStarknetLocalnetAsset,
23
- l as StarknetLocalnet,
24
- S as SupportedAssets,
25
- T as WBTCArbitrumLocalnetAsset,
26
- d as WBTCEthereumLocalnetAsset,
27
- k as bitcoinRegtestAsset,
12
+ E as ArbitrumLocalnet,
13
+ te as AssetManager,
14
+ n as Assets,
15
+ o as BlockchainType,
16
+ G as ChainAsset,
17
+ a as Chains,
18
+ p as Config,
19
+ D as ConstructUrl,
20
+ b as ETHStarknetLocalnetAsset,
21
+ v as EthereumLocalnet,
22
+ c as NATIVE_TOKENS,
23
+ Q as OrderAction,
24
+ l as OrderLifecycle,
25
+ d as OrderStatus,
26
+ r as Orderbook,
27
+ X as ParseOrderStatus,
28
+ se as RouteValidator,
29
+ B as SOLSolanaLocalnetAsset,
30
+ N as STRKStarknetLocalnetAsset,
31
+ g as StarknetLocalnet,
32
+ y as WBTCArbitrumLocalnetAsset,
33
+ M as WBTCEthereumLocalnetAsset,
34
+ V as bitcoinRegtestAsset,
35
+ K as buildAssetsWithChain,
36
+ oe as buildRouteMatrix,
28
37
  H as discriminateOrderResponse,
29
- E as getBlockchainType,
30
- N as getChainTypeFromAssetChain,
31
- f as getChainsFromOrder,
38
+ m as getBlockchainType,
32
39
  I as getOrderResponseType,
33
- v as isBitcoin,
40
+ S as is,
41
+ A as isBitcoin,
34
42
  U as isBitcoinOrderResponse,
35
- g as isEVM,
36
- y as isEvmNativeToken,
43
+ Y as isCompleted,
44
+ Z as isDeadlinePassed,
45
+ O as isEVM,
46
+ u as isEvmNativeToken,
37
47
  _ as isEvmOrderResponse,
38
- B as isMainnet,
39
- x as isNativeToken,
48
+ T as isMainnet,
49
+ f as isNativeToken,
40
50
  j as isOrder,
41
- b as isSolana,
42
- F as isSolanaNativeToken,
51
+ k as isSolana,
52
+ x as isSolanaNativeToken,
43
53
  q as isSolanaOrderResponse,
44
- K as isStarknet,
45
- z as isStarknetOrderResponse,
46
- M as isSui,
47
- V as isSuiNativeToken,
48
- D as isSuiOrderResponse
54
+ R as isStarknet,
55
+ w as isStarknetOrderResponse,
56
+ L as isSui,
57
+ h as isSuiNativeToken,
58
+ z as isSuiOrderResponse,
59
+ $ as parseAction
49
60
  };
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("@gardenfi/utils"),_=require("./index11.cjs"),C=require("./index4.cjs"),a=require("./index8.cjs"),y=require("./index12.cjs"),f=Object.keys(C.Config);class m{constructor(s,t){this._allChains=null,this._allAssets=null,this._assets=null,this._chains=null,this._routeValidator=null,this._routeMatrix=null,this._isLoading=!1,this._error=null,this.url=new o.Url(s),this.apiKey=t}get allChains(){return this._allChains}get allAssets(){return this._allAssets}get assets(){return this._assets}get chains(){return this._chains}get routeValidator(){return this._routeValidator}get routeMatrix(){return this._routeMatrix}get isLoading(){return this._isLoading}get error(){return this._error}async initialize(){await this.fetchAndSetAssetsAndChains()}async fetchAndSetAssetsAndChains(){try{this._isLoading=!0,this._error=null,await this.initializeRouteValidator();const s=this.url.endpoint("/v2/chains"),t=await o.Fetcher.get(s);if(t.error)return o.Err(t.error);if(!t.result)return o.Err("Failed to fetch chains data");const{allChains:i,allAssets:e,assets:n,chains:r}=this.processApiData(t.result);return this._allChains=i,this._allAssets=e,this._assets=n,this._chains=r,await this.buildRouteMatrix(),o.Ok("AssetManager initialized successfully")}catch(s){return o.Err(`Failed to fetch assets data: ${s}`)}finally{this._isLoading=!1}}async isRouteValid(s,t){if(!this._routeValidator||!s||!t||!s.id||!t.id)return console.warn("Missing routeValidator, from, or to. Returning true."),!0;try{const i=a.ChainAsset.from(s.id),e=a.ChainAsset.from(t.id);return await this._routeValidator.isValidRoute(i,e)}catch(i){return console.error("Error in isRouteValid:",i),!0}}getValidDestinations(s){if(!this._routeMatrix||!this._assets||!s.id)return Object.values(this._assets||{});try{const t=this._routeMatrix[s.id.toString()];return t?t.map(i=>{const e=i.toString();return Object.values(this._assets).find(n=>a.ChainAsset.from(n).toString()===e)}).filter(Boolean):Object.values(this._assets)}catch(t){return console.error("Error in getValidDestinations:",t),Object.values(this._assets||{})}}getAsset(s){if(!this._assets)return;const t=a.ChainAsset.from(s).toString();return this._assets[t]}getAssetsByChain(s){return this._assets?Object.values(this._assets).filter(t=>t.chain===s):[]}searchAssets(s){if(!this._assets)return[];const t=s.toLowerCase();return Object.values(this._assets).filter(i=>i.symbol.toLowerCase().includes(t)||i.name.toLowerCase().includes(t))}getChain(s){if(this._chains)return this._chains[s]}async initializeRouteValidator(){this._routeValidator=new _.RouteValidator(this.url.toString(),this.apiKey),await this._routeValidator.loadPolicy()}async buildRouteMatrix(){if(!this._allAssets||!this._routeValidator)return;const s=Object.values(this._allAssets).map(t=>{if(!t.id)return null;try{return a.ChainAsset.from(t.id)}catch{return null}}).filter(t=>t!==null);this._routeMatrix=await _.buildRouteMatrix(s,this._routeValidator)}processApiData(s){const t={},i={},e={},n={};for(const r of s){const l=this.parseChainIdentifier(r.chain);if(!l||!f.includes(l))continue;const u={...r,name:this.formatChainName(r.chain),chain:l};t[l]=u;for(const h of r.assets){const c=a.ChainAsset.from(h.id).toString(),{name:A,symbol:g}=y.parseAssetNameSymbol(h.name,h.id),d={...h,id:a.ChainAsset.from(h.id),chain:l,name:A,symbol:g};i[c]=d,e[c]=d}n[l]=u}return{allChains:t,allAssets:i,assets:e,chains:n}}parseChainIdentifier(s){return f.includes(s)?s:null}formatChainName(s){return s.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}async refresh(){await this.initialize()}clear(){this._allChains=null,this._allAssets=null,this._assets=null,this._chains=null,this._routeValidator=null,this._routeMatrix=null,this._error=null}}exports.AssetManager=m;
@@ -0,0 +1,225 @@
1
+ import { Url as g, Fetcher as m, Err as h, Ok as C } from "@gardenfi/utils";
2
+ import { RouteValidator as p, buildRouteMatrix as y } from "./index11.js";
3
+ import { Config as V } from "./index4.js";
4
+ import { ChainAsset as a } from "./index8.js";
5
+ import { parseAssetNameSymbol as b } from "./index12.js";
6
+ const _ = Object.keys(V);
7
+ class O {
8
+ constructor(s, t) {
9
+ this._allChains = null, this._allAssets = null, this._assets = null, this._chains = null, this._routeValidator = null, this._routeMatrix = null, this._isLoading = !1, this._error = null, this.url = new g(s), this.apiKey = t;
10
+ }
11
+ // ============================================
12
+ // Getters
13
+ // ============================================
14
+ get allChains() {
15
+ return this._allChains;
16
+ }
17
+ get allAssets() {
18
+ return this._allAssets;
19
+ }
20
+ get assets() {
21
+ return this._assets;
22
+ }
23
+ get chains() {
24
+ return this._chains;
25
+ }
26
+ get routeValidator() {
27
+ return this._routeValidator;
28
+ }
29
+ get routeMatrix() {
30
+ return this._routeMatrix;
31
+ }
32
+ get isLoading() {
33
+ return this._isLoading;
34
+ }
35
+ get error() {
36
+ return this._error;
37
+ }
38
+ // ============================================
39
+ // Initialization Methods
40
+ // ============================================
41
+ /**
42
+ * Initialize the AssetManager by fetching all required data
43
+ */
44
+ async initialize() {
45
+ await this.fetchAndSetAssetsAndChains();
46
+ }
47
+ /**
48
+ * Fetch and cache asset and chain data from API
49
+ */
50
+ async fetchAndSetAssetsAndChains() {
51
+ try {
52
+ this._isLoading = !0, this._error = null, await this.initializeRouteValidator();
53
+ const s = this.url.endpoint("/v2/chains"), t = await m.get(s);
54
+ if (t.error) return h(t.error);
55
+ if (!t.result) return h("Failed to fetch chains data");
56
+ const { allChains: i, allAssets: e, assets: n, chains: r } = this.processApiData(
57
+ t.result
58
+ );
59
+ return this._allChains = i, this._allAssets = e, this._assets = n, this._chains = r, await this.buildRouteMatrix(), C("AssetManager initialized successfully");
60
+ } catch (s) {
61
+ return h(`Failed to fetch assets data: ${s}`);
62
+ } finally {
63
+ this._isLoading = !1;
64
+ }
65
+ }
66
+ // ============================================
67
+ // Route Validation Methods
68
+ // ============================================
69
+ /**
70
+ * Check if a swap route from one asset to another is valid
71
+ */
72
+ async isRouteValid(s, t) {
73
+ if (!this._routeValidator || !s || !t || !s.id || !t.id)
74
+ return console.warn("Missing routeValidator, from, or to. Returning true."), !0;
75
+ try {
76
+ const i = a.from(s.id), e = a.from(t.id);
77
+ return await this._routeValidator.isValidRoute(
78
+ i,
79
+ e
80
+ );
81
+ } catch (i) {
82
+ return console.error("Error in isRouteValid:", i), !0;
83
+ }
84
+ }
85
+ /**
86
+ * Get all valid destination assets for a given source asset
87
+ */
88
+ getValidDestinations(s) {
89
+ if (!this._routeMatrix || !this._assets || !s.id)
90
+ return Object.values(this._assets || {});
91
+ try {
92
+ const t = this._routeMatrix[s.id.toString()];
93
+ return t ? t.map((i) => {
94
+ const e = i.toString();
95
+ return Object.values(this._assets).find((n) => a.from(n).toString() === e);
96
+ }).filter(Boolean) : Object.values(this._assets);
97
+ } catch (t) {
98
+ return console.error("Error in getValidDestinations:", t), Object.values(this._assets || {});
99
+ }
100
+ }
101
+ // ============================================
102
+ // Asset Query Methods
103
+ // ============================================
104
+ /**
105
+ * Get asset by chain and token address
106
+ */
107
+ getAsset(s) {
108
+ if (!this._assets) return;
109
+ const t = a.from(s).toString();
110
+ return this._assets[t];
111
+ }
112
+ /**
113
+ * Get all assets for a specific chain
114
+ */
115
+ getAssetsByChain(s) {
116
+ return this._assets ? Object.values(this._assets).filter((t) => t.chain === s) : [];
117
+ }
118
+ /**
119
+ * Search assets by symbol or name
120
+ */
121
+ searchAssets(s) {
122
+ if (!this._assets) return [];
123
+ const t = s.toLowerCase();
124
+ return Object.values(this._assets).filter(
125
+ (i) => i.symbol.toLowerCase().includes(t) || i.name.toLowerCase().includes(t)
126
+ );
127
+ }
128
+ /**
129
+ * Get chain data by chain identifier
130
+ */
131
+ getChain(s) {
132
+ if (this._chains)
133
+ return this._chains[s];
134
+ }
135
+ // ============================================
136
+ // Private Helper Methods
137
+ // ============================================
138
+ /**
139
+ * Initialize the route validator
140
+ */
141
+ async initializeRouteValidator() {
142
+ this._routeValidator = new p(this.url.toString(), this.apiKey), await this._routeValidator.loadPolicy();
143
+ }
144
+ /**
145
+ * Build route matrix for fast O(1) route lookups
146
+ */
147
+ async buildRouteMatrix() {
148
+ if (!this._allAssets || !this._routeValidator)
149
+ return;
150
+ const s = Object.values(this._allAssets).map((t) => {
151
+ if (!t.id) return null;
152
+ try {
153
+ return a.from(t.id);
154
+ } catch {
155
+ return null;
156
+ }
157
+ }).filter((t) => t !== null);
158
+ this._routeMatrix = await y(
159
+ s,
160
+ this._routeValidator
161
+ );
162
+ }
163
+ /**
164
+ * Process raw API data into structured format
165
+ */
166
+ processApiData(s) {
167
+ const t = {}, i = {}, e = {}, n = {};
168
+ for (const r of s) {
169
+ const o = this.parseChainIdentifier(r.chain);
170
+ if (!o || !_.includes(o))
171
+ continue;
172
+ const u = {
173
+ ...r,
174
+ name: this.formatChainName(r.chain),
175
+ chain: o
176
+ };
177
+ t[o] = u;
178
+ for (const l of r.assets) {
179
+ const c = a.from(l.id).toString(), { name: f, symbol: A } = b(
180
+ l.name,
181
+ l.id
182
+ ), d = {
183
+ ...l,
184
+ id: a.from(l.id),
185
+ chain: o,
186
+ name: f,
187
+ symbol: A
188
+ };
189
+ i[c] = d, e[c] = d;
190
+ }
191
+ n[o] = u;
192
+ }
193
+ return { allChains: t, allAssets: i, assets: e, chains: n };
194
+ }
195
+ /**
196
+ * Parse chain identifier from string
197
+ */
198
+ parseChainIdentifier(s) {
199
+ return _.includes(s) ? s : null;
200
+ }
201
+ /**
202
+ * Format chain name for display
203
+ */
204
+ formatChainName(s) {
205
+ return s.split("_").map((t) => t.charAt(0).toUpperCase() + t.slice(1)).join(" ");
206
+ }
207
+ // ============================================
208
+ // Data Refresh Methods
209
+ // ============================================
210
+ /**
211
+ * Refresh all data
212
+ */
213
+ async refresh() {
214
+ await this.initialize();
215
+ }
216
+ /**
217
+ * Clear all cached data
218
+ */
219
+ clear() {
220
+ this._allChains = null, this._allAssets = null, this._assets = null, this._chains = null, this._routeValidator = null, this._routeMatrix = null, this._error = null;
221
+ }
222
+ }
223
+ export {
224
+ O as AssetManager
225
+ };
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("@gardenfi/utils"),d=require("node-cache"),n=class n{constructor(t,e){this.apiBaseUrl=t,this.apiKey=e,typeof this.apiKey=="string"?this.auth=new o.ApiKey(this.apiKey):this.auth=this.apiKey}async loadPolicy(){const t=n.cache.get(n.POLICY_CACHE_KEY);if(t)return o.Ok(t);try{if(!this.auth)return o.Err("Authentication not configured");const e=await this.auth.getAuthHeaders();if(e.error)return o.Err(`Failed to get auth headers: ${e.error}`);const s=await(await fetch(`${this.apiBaseUrl}/v2/policy`,{headers:{...e.val,accept:"application/json"}})).json();return s.status!=="Ok"?o.Err(`API Error: ${s.error}`):(n.cache.set(n.POLICY_CACHE_KEY,s.result),o.Ok(s.result))}catch(e){return o.Err(`Failed to load policy: ${e}`)}}async isValidRoute(t,e){const r=await this.loadPolicy();if(!r.ok)return!1;const{sortedIsolationRules:s,sortedBlacklistRules:i,sortedWhitelistRules:a}=this.preprocessRules(r.val);if(t.toString()===e.toString())return!1;if(this.matchesRuleList(t,e,a))return!0;const u=this.findMatchingRule(t,s,"from");if(u&&!this.matchesRuleDestination(e,u))return!1;const h=this.findMatchingRule(e,s,"to");return h&&!this.matchesRuleSource(t,h)||this.matchesRuleList(t,e,i)?!1:r.val.default==="open"}async isAssetInIsolationGroup(t){const e=await this.loadPolicy();if(!e.ok)return!1;const{sortedIsolationRules:r}=this.preprocessRules(e.val);return r.some(s=>this.matchesAssetPattern(t,s.fromPattern)||this.matchesAssetPattern(t,s.toPattern))}async getValidDestinations(t,e){if(!(await this.loadPolicy()).ok)return[];const s=[];for(const i of e)await this.isValidRoute(t,i)&&s.push(i);return s}async getAllValidRoutes(t){const e=[];for(const r of t)for(const s of t)await this.isValidRoute(r,s)&&e.push({from:r,to:s});return e}static clearCache(){n.cache.del(n.POLICY_CACHE_KEY)}static getCacheStats(){return n.cache.getStats()}preprocessRules(t){const e=t.isolation_groups.map(i=>this.parseRule(i)).sort((i,a)=>a.specificity-i.specificity),r=t.blacklist_pairs.map(i=>this.parseRule(i)).sort((i,a)=>a.specificity-i.specificity),s=t.whitelist_overrides.map(i=>this.parseRule(i)).sort((i,a)=>a.specificity-i.specificity);return{sortedIsolationRules:e,sortedBlacklistRules:r,sortedWhitelistRules:s}}parseRule(t){const r=t.includes("<->")?"<->":"->",[s,i]=t.split(r).map(a=>a.trim());return{pattern:t,fromPattern:s,toPattern:i,direction:r,specificity:this.calculateSpecificity(s,i)}}calculateSpecificity(t,e){const r=s=>{const i=s.toLowerCase();return i==="*"?0:i.includes("*")?1:2};return r(t)*10+r(e)}findMatchingRule(t,e,r){for(const s of e){const i=r==="from"?s.fromPattern:s.toPattern;if(this.matchesAssetPattern(t,i))return s;if(s.direction==="<->"){const a=r==="from"?s.toPattern:s.fromPattern;if(this.matchesAssetPattern(t,a))return s}}return null}matchesRuleDestination(t,e){return!!(this.matchesAssetPattern(t,e.toPattern)||e.direction==="<->"&&this.matchesAssetPattern(t,e.fromPattern))}matchesRuleSource(t,e){return!!(this.matchesAssetPattern(t,e.fromPattern)||e.direction==="<->"&&this.matchesAssetPattern(t,e.toPattern))}matchesRuleList(t,e,r){return r.some(s=>this.matchesRule(t,e,s))}matchesRule(t,e,r){const s=this.matchesAssetPattern(t,r.fromPattern)&&this.matchesAssetPattern(e,r.toPattern);if(r.direction==="<->"){const i=this.matchesAssetPattern(t,r.toPattern)&&this.matchesAssetPattern(e,r.fromPattern);return s||i}return s}matchesAssetPattern(t,e){const r=t.toString().toLowerCase(),s=e.toLowerCase();if(s==="*")return!0;if(s.endsWith(":*")){const i=s.slice(0,-1);return r.startsWith(i)}if(s.startsWith("*:")){const i=s.slice(1);return r.endsWith(i)}return r===s}};n.cache=new d({stdTTL:36e3,checkperiod:3600}),n.POLICY_CACHE_KEY="route_policy";let c=n;async function p(l,t){const e={};for(const r of l)e[r.toString()]=await t.getValidDestinations(r,l);return e}exports.RouteValidator=c;exports.buildRouteMatrix=p;
@@ -0,0 +1,226 @@
1
+ import { ApiKey as d, Ok as u, Err as o } from "@gardenfi/utils";
2
+ import m from "node-cache";
3
+ const n = class n {
4
+ constructor(t, e) {
5
+ this.apiBaseUrl = t, this.apiKey = e, typeof this.apiKey == "string" ? this.auth = new d(this.apiKey) : this.auth = this.apiKey;
6
+ }
7
+ /**
8
+ * Loads the current route policy, cached or via API.
9
+ */
10
+ async loadPolicy() {
11
+ const t = n.cache.get(
12
+ n.POLICY_CACHE_KEY
13
+ );
14
+ if (t)
15
+ return u(t);
16
+ try {
17
+ if (!this.auth)
18
+ return o("Authentication not configured");
19
+ const e = await this.auth.getAuthHeaders();
20
+ if (e.error)
21
+ return o(`Failed to get auth headers: ${e.error}`);
22
+ const s = await (await fetch(`${this.apiBaseUrl}/v2/policy`, {
23
+ headers: {
24
+ ...e.val,
25
+ accept: "application/json"
26
+ }
27
+ })).json();
28
+ return s.status !== "Ok" ? o(`API Error: ${s.error}`) : (n.cache.set(n.POLICY_CACHE_KEY, s.result), u(s.result));
29
+ } catch (e) {
30
+ return o(`Failed to load policy: ${e}`);
31
+ }
32
+ }
33
+ /**
34
+ * Checks if a given route is valid based on all route rules.
35
+ */
36
+ async isValidRoute(t, e) {
37
+ const i = await this.loadPolicy();
38
+ if (!i.ok)
39
+ return !1;
40
+ const { sortedIsolationRules: s, sortedBlacklistRules: r, sortedWhitelistRules: a } = this.preprocessRules(i.val);
41
+ if (t.toString() === e.toString()) return !1;
42
+ if (this.matchesRuleList(t, e, a))
43
+ return !0;
44
+ const l = this.findMatchingRule(
45
+ t,
46
+ s,
47
+ "from"
48
+ );
49
+ if (l && !this.matchesRuleDestination(e, l))
50
+ return !1;
51
+ const h = this.findMatchingRule(
52
+ e,
53
+ s,
54
+ "to"
55
+ );
56
+ return h && !this.matchesRuleSource(t, h) || this.matchesRuleList(t, e, r) ? !1 : i.val.default === "open";
57
+ }
58
+ /**
59
+ * Returns true if asset is part of any isolation group rule.
60
+ */
61
+ async isAssetInIsolationGroup(t) {
62
+ const e = await this.loadPolicy();
63
+ if (!e.ok)
64
+ return !1;
65
+ const { sortedIsolationRules: i } = this.preprocessRules(e.val);
66
+ return i.some(
67
+ (s) => this.matchesAssetPattern(t, s.fromPattern) || this.matchesAssetPattern(t, s.toPattern)
68
+ );
69
+ }
70
+ /**
71
+ * Returns all valid destinations for a given source asset.
72
+ */
73
+ async getValidDestinations(t, e) {
74
+ if (!(await this.loadPolicy()).ok)
75
+ return [];
76
+ const s = [];
77
+ for (const r of e)
78
+ await this.isValidRoute(t, r) && s.push(r);
79
+ return s;
80
+ }
81
+ /**
82
+ * Returns every valid route (from-to pair) among the provided assets.
83
+ */
84
+ async getAllValidRoutes(t) {
85
+ const e = [];
86
+ for (const i of t)
87
+ for (const s of t)
88
+ await this.isValidRoute(i, s) && e.push({ from: i, to: s });
89
+ return e;
90
+ }
91
+ /**
92
+ * Manually clear the cached route policy.
93
+ */
94
+ static clearCache() {
95
+ n.cache.del(n.POLICY_CACHE_KEY);
96
+ }
97
+ /**
98
+ * Returns cache library statistics.
99
+ */
100
+ static getCacheStats() {
101
+ return n.cache.getStats();
102
+ }
103
+ /**
104
+ * Turns policy string rules into sorted ParsedRule objects.
105
+ */
106
+ preprocessRules(t) {
107
+ const e = t.isolation_groups.map((r) => this.parseRule(r)).sort((r, a) => a.specificity - r.specificity), i = t.blacklist_pairs.map((r) => this.parseRule(r)).sort((r, a) => a.specificity - r.specificity), s = t.whitelist_overrides.map((r) => this.parseRule(r)).sort((r, a) => a.specificity - r.specificity);
108
+ return { sortedIsolationRules: e, sortedBlacklistRules: i, sortedWhitelistRules: s };
109
+ }
110
+ /**
111
+ * Parses a rule string (e.g. "eth:usdc->avalanche:usdt") into parts.
112
+ */
113
+ parseRule(t) {
114
+ const i = t.includes(
115
+ "<->"
116
+ /* Bidirectional */
117
+ ) ? "<->" : "->", [s, r] = t.split(i).map((a) => a.trim());
118
+ return {
119
+ pattern: t,
120
+ fromPattern: s,
121
+ toPattern: r,
122
+ direction: i,
123
+ specificity: this.calculateSpecificity(s, r)
124
+ };
125
+ }
126
+ /**
127
+ * Gives a specificity score to a rule pattern for prioritizing.
128
+ */
129
+ calculateSpecificity(t, e) {
130
+ const i = (s) => {
131
+ const r = s.toLowerCase();
132
+ return r === "*" ? 0 : r.includes(
133
+ "*"
134
+ /* WildCard */
135
+ ) ? 1 : 2;
136
+ };
137
+ return i(t) * 10 + i(e);
138
+ }
139
+ /**
140
+ * Finds the first matching rule for an asset given the rule "side".
141
+ */
142
+ findMatchingRule(t, e, i) {
143
+ for (const s of e) {
144
+ const r = i === "from" ? s.fromPattern : s.toPattern;
145
+ if (this.matchesAssetPattern(t, r))
146
+ return s;
147
+ if (s.direction === "<->") {
148
+ const a = i === "from" ? s.toPattern : s.fromPattern;
149
+ if (this.matchesAssetPattern(t, a))
150
+ return s;
151
+ }
152
+ }
153
+ return null;
154
+ }
155
+ /**
156
+ * Checks if a given toAsset matches the rule's destination side.
157
+ */
158
+ matchesRuleDestination(t, e) {
159
+ return !!(this.matchesAssetPattern(t, e.toPattern) || e.direction === "<->" && this.matchesAssetPattern(t, e.fromPattern));
160
+ }
161
+ /**
162
+ * Checks if a given fromAsset matches the rule's source side.
163
+ */
164
+ matchesRuleSource(t, e) {
165
+ return !!(this.matchesAssetPattern(t, e.fromPattern) || e.direction === "<->" && this.matchesAssetPattern(t, e.toPattern));
166
+ }
167
+ /**
168
+ * Checks if any rule in a list matches fromAsset and toAsset.
169
+ */
170
+ matchesRuleList(t, e, i) {
171
+ return i.some((s) => this.matchesRule(t, e, s));
172
+ }
173
+ /**
174
+ * Checks if a rule matches fromAsset and toAsset (forward or backward if bidirectional).
175
+ */
176
+ matchesRule(t, e, i) {
177
+ const s = this.matchesAssetPattern(t, i.fromPattern) && this.matchesAssetPattern(e, i.toPattern);
178
+ if (i.direction === "<->") {
179
+ const r = this.matchesAssetPattern(t, i.toPattern) && this.matchesAssetPattern(e, i.fromPattern);
180
+ return s || r;
181
+ }
182
+ return s;
183
+ }
184
+ /**
185
+ * Checks if an asset string matches a rule's pattern (wildcards supported).
186
+ */
187
+ matchesAssetPattern(t, e) {
188
+ const i = t.toString().toLowerCase(), s = e.toLowerCase();
189
+ if (s === "*") return !0;
190
+ if (s.endsWith(
191
+ ":*"
192
+ /* TokenWildcard */
193
+ )) {
194
+ const r = s.slice(0, -1);
195
+ return i.startsWith(r);
196
+ }
197
+ if (s.startsWith(
198
+ "*:"
199
+ /* ChainWildcard */
200
+ )) {
201
+ const r = s.slice(1);
202
+ return i.endsWith(r);
203
+ }
204
+ return i === s;
205
+ }
206
+ };
207
+ n.cache = new m({
208
+ stdTTL: 36e3,
209
+ // 10 hours in seconds
210
+ checkperiod: 3600
211
+ // Check for expired keys every hour
212
+ }), n.POLICY_CACHE_KEY = "route_policy";
213
+ let f = n;
214
+ async function R(c, t) {
215
+ const e = {};
216
+ for (const i of c)
217
+ e[i.toString()] = await t.getValidDestinations(
218
+ i,
219
+ c
220
+ );
221
+ return e;
222
+ }
223
+ export {
224
+ f as RouteValidator,
225
+ R as buildRouteMatrix
226
+ };
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("./index8.cjs");function c(m,e,t){var i;const r=(m??"").trim();if(!r)return{name:"",symbol:""};const s=r.split(":");if(s.length>=2){const o=((i=s[0])==null?void 0:i.trim())||"",p=s.slice(1).join(":").trim()||(t==null?void 0:t.trim())||"";return{name:o,symbol:p}}let n="";if(e)try{n=(typeof e=="string"?u.ChainAsset.from(e):e).symbol.toUpperCase()}catch{}return{name:r,symbol:n||(t==null?void 0:t.trim())||""}}exports.parseAssetNameSymbol=c;
@@ -0,0 +1,21 @@
1
+ import { ChainAsset as h } from "./index8.js";
2
+ function A(m, r, t) {
3
+ var s;
4
+ const n = (m ?? "").trim();
5
+ if (!n) return { name: "", symbol: "" };
6
+ const e = n.split(":");
7
+ if (e.length >= 2) {
8
+ const o = ((s = e[0]) == null ? void 0 : s.trim()) || "", p = e.slice(1).join(":").trim() || (t == null ? void 0 : t.trim()) || "";
9
+ return { name: o, symbol: p };
10
+ }
11
+ let i = "";
12
+ if (r)
13
+ try {
14
+ i = (typeof r == "string" ? h.from(r) : r).symbol.toUpperCase();
15
+ } catch {
16
+ }
17
+ return { name: n, symbol: i || (t == null ? void 0 : t.trim()) || "" };
18
+ }
19
+ export {
20
+ A as parseAssetNameSymbol
21
+ };
package/dist/index2.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("@gardenfi/utils"),a=require("./index5.cjs");class d{constructor(n){this.url=n}async createOrder(n,o){try{const t=await o.getAuthHeaders();if(t.error)return r.Err(t.error);const s=await r.Fetcher.post(this.url.endpoint("/v2/orders"),{body:JSON.stringify(n),headers:{...t.val,"Content-Type":"application/json"}});if(s.error)return r.Err(s.error);if(!s.result)return r.Err("CreateOrder: Unexpected error, result is undefined");const e=a.discriminateOrderResponse(s.result);return e?r.Ok(e):r.Err("CreateOrder: Unable to determine order type from response")}catch(t){return r.Err("CreateOrder Err:",String(t))}}async getOrder(n,o){try{const t=this.url.endpoint("/v2/orders").endpoint(n),s=await r.Fetcher.get(t,{...o});return s.error?r.Err(s.error):s.result?r.Ok(s.result):r.Err("GetOrder: Unexpected error, result is undefined")}catch(t){return r.Err(`GetOrder: ${t instanceof Error?t.message:String(t)}`)}}async getOrders(n,o){const s=a.ConstructUrl(this.url,"/v2/orders",n);try{const e=await r.Fetcher.get(s,{...o});return e.error?r.Err(e.error):e.result?r.Ok(e.result):r.Err("GetAllOrders: Unexpected error, result is undefined")}catch(e){return r.Err(`GetAllOrders: ${e instanceof Error?e.message:String(e)}`)}}async subscribeOrders(n,o,t,s){let e=!1;const c=async()=>{if(!e){e=!0;try{const i=await this.getOrders(n,s);i.ok?await o(i.val):console.error("Error fetching orders:",i.error)}catch(i){console.error("Error fetching orders:",i)}finally{e=!1}}};await c();const u=setInterval(c,t);return()=>{clearInterval(u)}}}exports.Orderbook=d;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("@gardenfi/utils"),c=require("./index7.cjs"),d=require("./index9.cjs");class l{constructor(n){this.url=n}async createOrder(n,o){try{const t=await o.getAuthHeaders();if(t.error)return e.Err(t.error);const s=await e.Fetcher.post(this.url.endpoint("/v2/orders"),{body:JSON.stringify(n),headers:{...t.val,"Content-Type":"application/json"}});if(s.error)return e.Err(s.error);if(!s.result)return e.Err("CreateOrder: Unexpected error, result is undefined");const r=c.discriminateOrderResponse(s.result);return r?e.Ok(r):e.Err("CreateOrder: Unable to determine order type from response")}catch(t){return e.Err("CreateOrder Err:",String(t))}}async getOrder(n,o){try{const t=this.url.endpoint("/v2/orders").endpoint(n),s=await e.Fetcher.get(t,{...o});if(s.error)return e.Err(s.error);if(!s.result)return e.Err("GetOrder: Unexpected error, result is undefined");const r=d.ParseOrderStatus(s.result);return e.Ok({...s.result,status:r})}catch(t){return e.Err(`GetOrder: ${t instanceof Error?t.message:String(t)}`)}}async getOrders(n,o){const s=c.ConstructUrl(this.url,"/v2/orders",n);try{const r=await e.Fetcher.get(s,{...o});if(r.error)return e.Err(r.error);if(!r.result)return e.Err("GetAllOrders: Unexpected error, result is undefined");const i=r.result.data.map(u=>({...u,status:d.ParseOrderStatus(u)}));return e.Ok({...r.result,data:i})}catch(r){return e.Err(`GetAllOrders: ${r instanceof Error?r.message:String(r)}`)}}async subscribeOrders(n,o,t,s){let r=!1;const i=async()=>{if(!r){r=!0;try{const a=await this.getOrders(n,s);a.ok?await o(a.val):console.error("Error fetching orders:",a.error)}catch(a){console.error("Error fetching orders:",a)}finally{r=!1}}};await i();const u=setInterval(i,t);return()=>{clearInterval(u)}}}exports.Orderbook=l;