@alcorexchange/alcor-swap-sdk
Version:
**npm** ``` npm i @alcorexchange/alcor-swap-sdk ``` **yarn** ``` yarn add @alcorexchange/alcor-swap-sdk ``` ## Usage ### Import:
139 lines (128 loc) • 5.16 kB
JavaScript
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import { Route } from '../entities';
// WASM imports - lazy loaded
let wasmModule = null;
async function loadWasmModule() {
if (!wasmModule) {
try {
wasmModule = await import('../../wasm-route-finder/pkg/wasm_route_finder.js');
} catch (error) {
console.error('Failed to load WASM module:', error);
throw new Error('WASM module not available');
}
}
return wasmModule;
}
/**
* Ultra-fast WASM route finder with persistent pool storage
* Loads pools once and reuses for multiple queries
*/
export let WASMRouteFast = /*#__PURE__*/function () {
function WASMRouteFast() {
_classCallCheck(this, WASMRouteFast);
_defineProperty(this, "initialized", false);
_defineProperty(this, "pools", []);
_defineProperty(this, "poolsMap", new Map());
}
return _createClass(WASMRouteFast, [{
key: "initialize",
value: async function initialize(pools) {
await loadWasmModule();
this.pools = pools;
this.poolsMap.clear();
// Build pool map for fast lookup
for (const pool of pools) {
this.poolsMap.set(String(pool.id), pool);
}
// Convert pools to minimal format for WASM
const wasmPools = pools.map(pool => ({
id: String(pool.id),
token_a: {
id: pool.tokenA.id
},
token_b: {
id: pool.tokenB.id
}
}));
// Initialize pools in WASM memory once
wasmModule.init_pools_fast(wasmPools);
this.initialized = true;
}
}, {
key: "computeAllRoutes",
value: function computeAllRoutes(tokenIn, tokenOut, maxHops) {
if (!this.initialized) {
throw new Error('WASMRouteFast not initialized. Call initialize() first.');
}
// Call WASM with just token IDs - no pool serialization
const routePoolIds = wasmModule.compute_routes_fast(tokenIn.id, tokenOut.id, maxHops);
// Convert pool IDs back to Route objects
return routePoolIds.map(poolIds => {
const routePools = poolIds.map(poolId => {
const pool = this.poolsMap.get(poolId);
if (!pool) {
throw new Error(`Pool not found: ${poolId}`);
}
return pool;
});
return new Route(routePools, tokenIn, tokenOut);
});
}
/**
* Update specific pools without full reinitialization
*/
}, {
key: "updatePools",
value: async function updatePools(updatedPools) {
// For now, reinitialize with all pools
// In future, could implement partial updates
const poolIds = new Set(updatedPools.map(p => String(p.id)));
// Merge updated pools with existing ones
const newPools = [...this.pools];
for (let i = 0; i < newPools.length; i++) {
if (poolIds.has(String(newPools[i].id))) {
const updated = updatedPools.find(p => String(p.id) === String(newPools[i].id));
if (updated) {
newPools[i] = updated;
}
}
}
await this.initialize(newPools);
}
/**
* Benchmark function to measure pure computation time
*/
}, {
key: "benchmarkCompute",
value: function benchmarkCompute(tokenIn, tokenOut, maxHops, iterations = 100) {
if (!this.initialized) {
throw new Error('WASMRouteFast not initialized. Call initialize() first.');
}
const start = performance.now();
let routesFound = 0;
for (let i = 0; i < iterations; i++) {
const routes = wasmModule.compute_routes_fast(tokenIn.id, tokenOut.id, maxHops);
routesFound = routes.length;
}
const totalTime = performance.now() - start;
return {
totalTime,
avgTime: totalTime / iterations,
routesFound
};
}
}]);
}();
/**
* Standalone fast computation for one-off use
*/
export async function computeAllRoutesFast(tokenIn, tokenOut, pools, maxHops) {
const finder = new WASMRouteFast();
await finder.initialize(pools);
return finder.computeAllRoutes(tokenIn, tokenOut, maxHops);
}