@lifi/composer-sdk
Version:
Public Composer SDK for building and submitting flows
92 lines (91 loc) • 2.84 kB
JavaScript
//#region src/reachability.ts
const DEFAULT_MAX_HOPS = 2;
const tokenKey = (token) => `${token.chainId}:${token.address.toLowerCase()}`;
const isSync = (edge) => edge.availability === void 0;
const isProxyHeld = (edge) => isSync(edge) && edge.recipient !== "required";
const visitEdge = ({ edge, from, depth, sourceKey, isTerminal, found, expanded }) => {
const key = tokenKey(edge.out);
if (key === sourceKey) return void 0;
if (isTerminal(edge) && !found.has(key)) found.set(key, {
in: from,
out: edge.out,
hops: depth
});
if (!isProxyHeld(edge) || expanded.has(key)) return void 0;
expanded.add(key);
return edge.out;
};
const closureFrom = ({ byIn, from, maxHops, isTerminal }) => {
const sourceKey = tokenKey(from);
const found = /* @__PURE__ */ new Map();
const expanded = /* @__PURE__ */ new Set([sourceKey]);
let frontier = [from];
for (let depth = 1; depth <= maxHops && frontier.length > 0; depth++) {
const next = [];
for (const node of frontier) for (const edge of byIn.get(tokenKey(node)) ?? []) {
const out = visitEdge({
edge,
from,
depth,
sourceKey,
isTerminal,
found,
expanded
});
if (out) next.push(out);
}
frontier = next;
}
return found;
};
const indexByIn = (packs) => {
const byIn = /* @__PURE__ */ new Map();
for (const pack of packs) for (const edge of pack.edges) {
const key = tokenKey(edge.in);
const list = byIn.get(key);
if (list) list.push(edge);
else byIn.set(key, [edge]);
}
return byIn;
};
/**
* Builds a reachability index over the packs returned by
* {@link ComposeClient.getZapPacks}. Per-source closures are computed on
* first use and memoised, so `canRoute` on a handful of pairs stays cheap
* while `pairs()` enumerates everything.
*/
const buildReachability = (packs, options = {}) => {
const maxHops = options.maxHops ?? DEFAULT_MAX_HOPS;
const allowAsync = options.allowAsyncRoutes ?? false;
const isTerminal = (edge) => isSync(edge) || allowAsync && edge.availability === "future";
const byIn = indexByIn(packs);
const memo = /* @__PURE__ */ new Map();
const closure = (from) => {
const key = tokenKey(from);
const cached = memo.get(key);
if (cached) return cached;
const computed = closureFrom({
byIn,
from,
maxHops,
isTerminal
});
memo.set(key, computed);
return computed;
};
return {
maxHops,
canRoute: (from, to) => closure(from).has(tokenKey(to)),
routableFrom: (from) => [...closure(from).values()],
pairs: () => {
const sources = /* @__PURE__ */ new Map();
for (const pack of packs) for (const edge of pack.edges) sources.set(tokenKey(edge.in), edge.in);
const all = [];
for (const source of sources.values()) all.push(...closure(source).values());
return all;
}
};
};
//#endregion
export { buildReachability };
//# sourceMappingURL=reachability.js.map