Skip to content

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.

fix(vaults): quote shares before moving funds and refund deposits that would mint zero shares

nirholas2ecf6c61dcec
diff --git a/api/_lib/vault-transfer.js b/api/_lib/vault-transfer.js
index 9534a117e..5638fb4d2 100644
--- a/api/_lib/vault-transfer.js
+++ b/api/_lib/vault-transfer.js
@@ -82,7 +82,7 @@ async function payoutUsdc({ vault, toAddress, atomics, userId, reason }) {
*
* @returns {Promise<object>} result envelope
*/
-export async function depositToVault({ vault, backerAgent, userId, usdcAtomics, idempotencyKey }) {
+export async function depositToVault({ vault, backerAgent, userId, usdcAtomics, minSharesOut, idempotencyKey }) {
const network = netOf(vault.network);
const amount = toBig(usdcAtomics);
if (amount <= 0n) return { status: 'failed', code: 'zero_amount', message: 'deposit must be positive' };
@@ -95,6 +95,17 @@ export async function depositToVault({ vault, backerAgent, userId, usdcAtomics,
return { status: 'blocked', code: 'backer_cap', message: 'this deposit would exceed the per-backer cap for this vault', detail: { cap_atomics: String(vault.per_backer_cap_atomics), contributed_atomics: String(contributed) } };
}
+ // Quote BEFORE any funds move. The vault NAV includes the live USDC balance of
+ // a public address, so an outside donation can inflate it until a deposit
+ // floors to zero shares. Refuse a deposit that would mint nothing, or fewer
+ // shares than the caller's min_shares_out.
+ const minOut = minSharesOut == null ? 1n : toBig(minSharesOut);
+ const floorShares = minOut > 1n ? minOut : 1n;
+ const quoteNav = await computeVaultNav(vault, await getOpenPositions(vault.id));
+ const quoted = sharesForDeposit(amount, quoteNav.navAtomics, vault.total_shares);
+ if (quoted <= 0n) return { status: 'blocked', code: 'zero_shares', message: 'this deposit is too small to mint any shares at the current vault price' };
+ if (quoted < floorShares) return { status: 'blocked', code: 'min_shares_out', message: 'this deposit would mint fewer shares than your minimum', detail: { quoted_shares: String(quoted), min_shares_out: String(floorShares) } };
+
// Real, guarded USDC transfer from the backer's agent wallet → vault wallet.
const transfer = await transferUsdcGuarded({
fromAgentId: backerAgent.id, fromUserId: userId, fromMeta: backerAgent.meta || {},
@@ -113,6 +124,21 @@ export async function depositToVault({ vault, backerAgent, userId, usdcAtomics,
const nav = await computeVaultNav(vault, positions);
const navBefore = nav.navAtomics > amount ? nav.navAtomics - amount : 0n;
const minted = sharesForDeposit(amount, navBefore, vault.total_shares);
+ if (minted < floorShares) {
+ // NAV moved between the quote and the mint: hand the funds back rather than keep them for no shares.
+ const secretVault = await getVaultWithSecret(vault.id);
+ let refund = null;
+ try {
+ refund = await payoutUsdc({ vault: secretVault, toAddress: backerAgent.meta.solana_address, atomics: amount, userId, reason: 'deposit_refund' });
+ } catch (e) {
+ logAudit({ userId, action: 'vault.deposit_refund_failed', resourceId: vault.id, meta: { usdc_atomics: String(amount), signature, error: String(e?.message || e) } });
+ }
+ return {
+ status: 'failed', code: 'min_shares_out', signature,
+ message: refund ? 'the vault price moved and the deposit would have minted too few shares; it was refunded' : 'the vault price moved and the deposit would have minted too few shares; the refund needs manual settlement',
+ detail: { refund_signature: refund?.signature || null },
+ };
+ }
const eventId = await recordVaultEvent({
vaultId: vault.id, type: 'deposit', userId, backerAgentId: backerAgent.id,
diff --git a/api/vaults/deposit.js b/api/vaults/deposit.js
index 9b723df75..fdc6ec8e6 100644
--- a/api/vaults/deposit.js
+++ b/api/vaults/deposit.js
@@ -38,6 +38,8 @@ export default wrap(async (req, res) => {
if (!isUuid(backerAgentId)) return error(res, 400, 'validation_error', 'backerAgentId must be an agent id');
if (!(usdc > 0)) return error(res, 400, 'validation_error', 'usdc must be a positive number');
+ let minSharesOut = body.min_shares_out ?? body.minSharesOut ?? null;
+ if (minSharesOut != null && !/^\d+$/.test(String(minSharesOut))) return error(res, 400, 'validation_error', 'min_shares_out must be a non-negative integer');
const vault = await getVault(vaultId);
if (!vault) return error(res, 404, 'not_found', 'vault not found');
@@ -52,6 +54,7 @@ export default wrap(async (req, res) => {
const result = await depositToVault({
vault, backerAgent, userId,
usdcAtomics: usdcToAtomics(usdc),
+ minSharesOut,
idempotencyKey: String(body.idempotency_key || `vault-deposit:${vaultId}:${backerAgentId}:${randomUUID()}`).slice(0, 128),
});
diff --git a/tests/vault-deposit-zero-share.test.js b/tests/vault-deposit-zero-share.test.js
new file mode 100644
index 000000000..9d02e6bf5
--- /dev/null
+++ b/tests/vault-deposit-zero-share.test.js
@@ -0,0 +1,68 @@
+// A vault deposit must never move funds for zero shares. Donating USDC straight
+// to the public vault address inflates NAV, so a later small deposit would floor
+// to 0 shares and be kept by existing holders. The quote is checked BEFORE the
+// transfer, honours the caller's min_shares_out, and a post-transfer shortfall
+// refunds the backer.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const VAULT = { id: 'v1', network: 'mainnet', status: 'open', total_shares: '1', per_backer_cap_atomics: null, vault_address: 'VaultAddr', agent_id: 'a1', encrypted_secret: 'enc', peak_share_price_e6: '1000000' };
+const navs = [];
+const store = {
+ getVaultWithSecret: vi.fn(async () => ({ ...VAULT })),
+ getBacker: vi.fn(async () => null),
+ getOpenPositions: vi.fn(async () => []),
+ recordVaultEvent: vi.fn(async () => 7),
+ updateVaultEvent: vi.fn(async () => {}),
+ applyBackerDelta: vi.fn(async () => ({})),
+ applyVaultShareDelta: vi.fn(async () => ({ total_shares: '2' })),
+ applyAccruedFee: vi.fn(async () => '0'),
+ reserveBackerShares: vi.fn(),
+ releaseBackerShares: vi.fn(),
+ reserveAccruedFee: vi.fn(),
+};
+vi.mock('../api/_lib/vault-store.js', () => store);
+vi.mock('../api/_lib/vault-wallet.js', () => ({
+ recoverVaultKeypair: vi.fn(async () => { const { Keypair } = await import('@solana/web3.js'); return Keypair.generate(); }),
+ computeVaultNav: vi.fn(async () => ({ navAtomics: navs.shift(), priced: true })),
+ readVaultUsdcAtomics: vi.fn(),
+}));
+const submitProtected = vi.fn(async () => ({ signature: 'refundSig' }));
+vi.mock('../api/_lib/execution-engine.js', () => ({ submitProtected: (...a) => submitProtected(...a) }));
+vi.mock('../api/_lib/agent-pumpfun.js', () => ({ solanaConnection: vi.fn(() => ({})) }));
+const transfer = vi.fn(async () => ({ status: 'ok', signature: 'depSig' }));
+vi.mock('../api/_lib/agent-usdc-transfer.js', () => ({ transferUsdcGuarded: (...a) => transfer(...a) }));
+vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));
+
+const { depositToVault } = await import('../api/_lib/vault-transfer.js');
+const { Keypair } = await import('@solana/web3.js');
+const backerAgent = { id: 'b1', meta: { solana_address: Keypair.generate().publicKey.toBase58() } };
+
+beforeEach(() => { vi.clearAllMocks(); navs.length = 0; });
+
+describe('depositToVault zero-share guard', () => {
+ it('refuses before moving funds when the quote is zero shares', async () => {
+ navs.push(1_000_000_000n); // donation-inflated NAV, 1 share outstanding
+ const r = await depositToVault({ vault: VAULT, backerAgent, userId: 'u', usdcAtomics: 500n, idempotencyKey: 'k' });
+ expect(r.status).toBe('blocked');
+ expect(r.code).toBe('zero_shares');
+ expect(transfer).not.toHaveBeenCalled();
+ });
+
+ it('refuses before moving funds when the quote is below min_shares_out', async () => {
+ navs.push(1_000_000n);
+ const r = await depositToVault({ vault: { ...VAULT, total_shares: '1000000' }, backerAgent, userId: 'u', usdcAtomics: 1_000_000n, minSharesOut: 2_000_000n, idempotencyKey: 'k' });
+ expect(r.code).toBe('min_shares_out');
+ expect(transfer).not.toHaveBeenCalled();
+ });
+
+ it('refunds the backer when NAV moves between quote and mint', async () => {
+ navs.push(1_000_000n, 1_000_000_000_000n); // quote ok, then donation lands
+ const r = await depositToVault({ vault: { ...VAULT, total_shares: '1000000' }, backerAgent, userId: 'u', usdcAtomics: 500_000n, idempotencyKey: 'k' });
+ expect(transfer).toHaveBeenCalled();
+ expect(submitProtected).toHaveBeenCalled();
+ expect(r.status).toBe('failed');
+ expect(r.code).toBe('min_shares_out');
+ expect(store.applyBackerDelta).not.toHaveBeenCalled();
+ });
+});