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.

Verify marketplace platform-fee split on-chain and order legs for Solana Pay

nirholas808021efbe7b
diff --git a/api/_lib/purchase-confirm.js b/api/_lib/purchase-confirm.js
index 5f3ee5b3f..414a5531c 100644
--- a/api/_lib/purchase-confirm.js
+++ b/api/_lib/purchase-confirm.js
@@ -150,6 +150,31 @@ async function findReferencedTransferAmount(txSignature, recipient, splTokenMint
return null;
}
+// Verify the platform-fee leg: the treasury's token account for `splTokenMint`
+// must have increased by at least `minAtomics` in this transaction. The fee leg
+// carries no Solana-Pay reference of its own (the reference rides the seller
+// leg, which validateTransfer checks), so we confirm it by the same balance-
+// delta technique @solana/pay uses — matched on the parsed token balance's
+// `owner`, which is robust to versioned txs and ATA addressing.
+async function feeLegSatisfied(txSignature, feeWallet, splTokenMint, minAtomics) {
+ if (minAtomics <= 0n) return true;
+ const tx = await rpc().withFallback((conn) =>
+ conn.getParsedTransaction(txSignature, {
+ commitment: 'confirmed',
+ maxSupportedTransactionVersion: 0,
+ }),
+ );
+ if (!tx || tx.meta?.err) return false;
+
+ const mintStr = splTokenMint.toBase58();
+ const matches = (b) => b && b.mint === mintStr && b.owner === feeWallet;
+ const pre = tx.meta.preTokenBalances?.find(matches);
+ const post = tx.meta.postTokenBalances?.find(matches);
+ const preAmt = BigInt(pre?.uiTokenAmount?.amount ?? '0');
+ const postAmt = BigInt(post?.uiTokenAmount?.amount ?? '0');
+ return postAmt - preAmt >= minAtomics;
+}
+
/**
* Run confirm for a single skill_purchases row.
* @param {object} pur — the row, must include id, user_id, agent_id, skill,
@@ -225,8 +250,19 @@ async function confirmSolanaSkill(pur, payoutAddress) {
let lastErr = null;
for (const a of attempts) {
try {
+ // Seller leg: reference-bound, checked by @solana/pay (verifies the
+ // reference rides the FINAL instruction and the seller received ≥ leg).
await validateLeg(recipient, a.creator);
- if (a.feeTaken.gt(0)) await validateLeg(new PublicKey(a.feeWallet), a.feeTaken);
+ // Fee leg: balance-delta on the treasury's token account.
+ if (a.feeTaken.gt(0)) {
+ const ok = await feeLegSatisfied(
+ txSignature,
+ a.feeWallet,
+ splToken,
+ BigInt(a.feeTaken.toFixed(0)),
+ );
+ if (!ok) throw new Error('platform fee leg missing or short');
+ }
matched = a;
break;
} catch (e) {
diff --git a/prompts/monetization/12-platform-fee-implementation.md b/prompts/monetization/12-platform-fee-implementation.md
deleted file mode 100644
index 4740cc173..000000000
--- a/prompts/monetization/12-platform-fee-implementation.md
+++ /dev/null
@@ -1,58 +0,0 @@
----
-status: not-started
----
-
-# Prompt 12: Platform Fee Implementation
-
-## Objective
-Implement a platform fee on every skill purchase transaction.
-
-## Explanation
-To ensure the sustainability of the platform, a small percentage of each sale will be collected as a platform fee. This needs to be calculated and transferred during the payment process.
-
-## Instructions
-1. **Modify the Payment Transaction:**
- * In `src/marketplace.js`, when constructing the purchase transaction, add a second instruction.
- * The first instruction will transfer the creator's share of the payment to their wallet.
- * The second instruction will transfer the platform's fee to the platform's treasury wallet.
-
-2. **Configuration:**
- * The platform fee percentage should be configurable and stored in a secure location.
-
-## Code Example (Frontend - `src/marketplace.js`)
-
-```javascript
-// Inside the purchase logic
-const platformFee = price.amount * 0.05; // 5% fee
-const creatorGets = price.amount - platformFee;
-
-const transaction = new solanaWeb3.Transaction()
- .add(
- solanaWeb3.SystemProgram.transfer({
- fromPubkey: user.publicKey,
- toPubkey: new solanaWeb3.PublicKey(creatorWalletAddress),
- lamports: creatorGets,
- })
- )
- .add(
- solanaWeb3.SystemProgram.transfer({
- fromPubkey: user.publicKey,
- toPubkey: new solanaWeb3.PublicKey(platformTreasuryAddress),
- lamports: platformFee,
- })
- );
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization/12-platform-fee-implementation.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/src/marketplace.js b/src/marketplace.js
index a0c83b747..35f65fa83 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -6990,14 +6990,13 @@ async function buildSplTransferWithReference({ payer, recipient, mint, amount, r
const fromAta = await getAssociatedTokenAddress(mintKey, payer);
const toAta = await getAssociatedTokenAddress(mintKey, recipientKey);
- const ix = createTransferInstruction(fromAta, toAta, payer, amount);
- // Solana Pay: append the reference as a readonly, non-signer key so the
- // server can later locate this tx via getSignaturesForAddress(reference).
- ix.keys.push({ pubkey: referenceKey, isSigner: false, isWritable: false });
-
const { blockhash } = await (await getSolanaConnection()).getLatestBlockhash('confirmed');
- const tx = new Transaction({ feePayer: payer, recentBlockhash: blockhash }).add(ix);
+ const tx = new Transaction({ feePayer: payer, recentBlockhash: blockhash });
+ // Fee leg first (when present): the platform fee to the treasury. The seller
+ // leg goes LAST and carries the Solana-Pay reference — @solana/pay's
+ // validateTransfer only inspects the FINAL instruction for the reference
+ // binding, so the referenced transfer must be the last one in the tx.
if (fee && fee.amount > 0n) {
const feeOwner = new PublicKey(fee.recipient);
const feeAta = await getAssociatedTokenAddress(mintKey, feeOwner);
@@ -7007,6 +7006,12 @@ async function buildSplTransferWithReference({ payer, recipient, mint, amount, r
tx.add(createTransferInstruction(fromAta, feeAta, payer, fee.amount));
}
+ const ix = createTransferInstruction(fromAta, toAta, payer, amount);
+ // Solana Pay: append the reference as a readonly, non-signer key so the
+ // server can later locate this tx via getSignaturesForAddress(reference).
+ ix.keys.push({ pubkey: referenceKey, isSigner: false, isWritable: false });
+ tx.add(ix);
+
return tx;
}