Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(agent-orders): order the work set by last seen and scale a percentage sell
nirholas4667d2a98c27
diff --git a/tests/agent-orders-sweep.test.js b/tests/agent-orders-sweep.test.jsindex ab013d386..926f28521 100644--- a/tests/agent-orders-sweep.test.js+++ b/tests/agent-orders-sweep.test.js@@ -359,6 +359,76 @@ describe('runOrderSweep: DCA / TWAP slices', () => {expect(tradeState.calls).toHaveLength(0);});++ // A TWAP sell divides the owner's TOTAL percentage across the slices, so its+ // sell_pct is a share of the bag at creation time, not of whatever is left.+ const twapSell = (over = {}) => order({+ type: 'twap', side: 'sell', size_sol: null, sell_pct: 25,+ schedule: { interval_seconds: 300, slices: 4, filled_slices: 0, total_pct: 100 },+ next_fire_at: new Date(Date.now() - 1_000).toISOString(),+ ...over,+ });++ it('sells the promised share of the ORIGINAL bag on a later TWAP slice, not of what is left', async () => {+ // Slice 3 of 4 on a "sell 100%" TWAP: 50% of the bag is already gone, so the+ // remaining 25 points of the original are 50% of what is still held. Applying+ // the raw 25% here would leave a third of the position stranded.+ dbState.activeOrders = [twapSell({+ schedule: { interval_seconds: 300, slices: 4, filled_slices: 2, total_pct: 100 },+ fill_count: 2, status: 'partial',+ })];+ priceAt(41_000);+ marketState.holding = { whole: 500, raw: 500_000_000n, decimals: 6 };++ await runOrderSweep(cfg);++ expect(tradeState.calls).toHaveLength(1);+ expect(tradeState.calls[0].input.amount).toBeCloseTo(250, 6);+ });++ it('closes the position with a max sell on the final slice of a full-exit TWAP', async () => {+ dbState.activeOrders = [twapSell({+ schedule: { interval_seconds: 300, slices: 4, filled_slices: 3, total_pct: 100 },+ fill_count: 3, status: 'partial',+ })];+ priceAt(41_000);+ marketState.holding = { whole: 250, raw: 250_000_000n, decimals: 6 };++ await runOrderSweep(cfg);++ expect(tradeState.calls).toHaveLength(1);+ // parseTradeInput turns a "max" sell into the isMax flag with a null amount,+ // so the executor dusts out the whole balance it reads at fire time.+ expect(tradeState.calls[0].input.isMax).toBe(true);+ expect(tradeState.calls[0].input.amount).toBeNull();+ expect(call('advance').values[0]).toBe('filled');+ });++ it('leaves the first TWAP slice sized straight off the total percentage', async () => {+ dbState.activeOrders = [twapSell()];+ priceAt(41_000);+ marketState.holding = { whole: 1_000, raw: 1_000_000_000n, decimals: 6 };++ await runOrderSweep(cfg);++ expect(tradeState.calls[0].input.amount).toBe(250);+ });++ it('keeps a DCA percentage sell measured against the live bag', async () => {+ // The opposite convention on purpose: "DCA out 10% an hour" means 10% of+ // whatever is left each time, so a later slice must NOT be re-based.+ dbState.activeOrders = [dca({+ side: 'sell', size_sol: null, sell_pct: 10,+ schedule: { interval_seconds: 3600, slices: 5, filled_slices: 3 },+ fill_count: 3, status: 'partial',+ })];+ priceAt(41_000);+ marketState.holding = { whole: 700, raw: 700_000_000n, decimals: 6 };++ await runOrderSweep(cfg);++ expect(tradeState.calls[0].input.amount).toBeCloseTo(70, 6);+ });});// ── conditional + trailing ───────────────────────────────────────────────────diff --git a/workers/agent-orders/store.js b/workers/agent-orders/store.jsindex 796bacae0..ddf581d17 100644--- a/workers/agent-orders/store.js+++ b/workers/agent-orders/store.js@@ -7,13 +7,23 @@import { sql } from '../../api/_lib/db.js';-/** Active/partial orders on this network — the sweep's work set. */+/**+ * Active/partial orders on this network: the sweep's work set, least-recently-seen+ * first.+ *+ * A price or conditional order has no next_fire_at, so ordering by that column+ * alone with NULLS LAST parked every one of them behind every scheduled order:+ * once the table held more than `limit` orders, the price side of the book would+ * never be evaluated again. COALESCE rotates the work set instead (last_eval_at+ * is stamped on every sweep), while a due slice still sorts ahead of an order+ * that was evaluated a moment ago.+ */export async function getActiveOrders(network, limit = 500) {return sql`SELECT * FROM ordersWHERE network = ${network}AND status IN ('active', 'partial')- ORDER BY next_fire_at ASC NULLS LAST, created_at ASC+ ORDER BY COALESCE(next_fire_at, last_eval_at, created_at) ASCLIMIT ${limit}`;}diff --git a/workers/agent-orders/sweep.js b/workers/agent-orders/sweep.jsindex 84422103d..8fffe2c13 100644--- a/workers/agent-orders/sweep.js+++ b/workers/agent-orders/sweep.js@@ -100,8 +100,34 @@ async function evaluate(order, now) {return { reason, triggerPrice: metricVal, sliceIndex: 0, terminal: true, nextFireAt: null };}+/**+ * The share of the CURRENT holding a percentage sell disposes on this slice.+ *+ * A DCA sell's sell_pct is deliberately a percentage of the live bag every time:+ * "DCA out 10% an hour" means 10% of whatever is left. A TWAP sell is the+ * opposite. The API divides the owner's TOTAL percentage across the slices+ * (api/_lib/orders.js), so sell_pct is a share of the bag AS IT WAS when the+ * order was created, and every earlier slice already shrank that bag. Applying+ * it to the live holding each time compounds downward: "sell 100% over 4 slices"+ * would dispose 25 / 18.75 / 14.06 / 10.55%, leave ~31.6% of the bag behind, and+ * still mark the order filled. Re-base onto what is left of the promised total,+ * which lands the final slice on the whole remainder.+ */+function sellFractionPct(order, sliceIndex) {+ const pct = Number(order.sell_pct);+ const i = Number(sliceIndex) || 0;+ const slices = Number(order.schedule?.slices ?? 1);+ if (order.type !== 'twap' || i <= 0 || !(slices > 0)) return pct;+ // Derive from the owner's total rather than the rounded per-slice figure, so+ // the last slice lands on exactly 100 instead of leaving rounding dust behind.+ const perSlice = Number(order.schedule?.total_pct ?? pct * slices) / slices;+ const bagLeft = 100 - perSlice * i; // percent of the original bag still held+ if (!(bagLeft > 0)) return 0;+ return (perSlice / bagLeft) * 100;+}+/** Build the executeAgentTrade `body` for a fire, or null if it can't be sized. */-async function buildBody(order, agent) {+async function buildBody(order, agent, sliceIndex = 0) {const base = { mint: order.mint, slippageBps: order.slippage_bps, network: order.network, side: order.side };if (order.side === 'buy') {if (!(Number(order.size_sol) > 0)) return null;@@ -109,10 +135,12 @@ async function buildBody(order, agent) {}// sellif (order.sell_pct != null) {- if (order.sell_pct >= 100) return { ...base, amount: 'max' };+ const pct = sellFractionPct(order, sliceIndex);+ if (!(pct > 0)) return null;+ if (pct >= 100) return { ...base, amount: 'max' };const holding = await getHolding({ network: order.network, mint: order.mint, owner: agent.meta.solana_address });if (!holding || holding.whole <= 0) return null;- const amt = holding.whole * (order.sell_pct / 100);+ const amt = holding.whole * (pct / 100);return amt > 0 ? { ...base, amount: amt } : null;}if (Number(order.size_tokens) > 0) {@@ -179,7 +207,7 @@ async function settle(order, fire, result, mode) {async function fireOne(order, agent, fire, cfg) {if (!(await claimFire(order.id))) return; // another sweep owns ittry {- const body = await buildBody(order, agent);+ const body = await buildBody(order, agent, fire.sliceIndex);if (!body) { await releaseFire(order.id, order.fill_count > 0 ? 'partial' : 'active', 'no_balance_or_size'); return; }const tradeLimits = getTradeLimits(agent.meta);