第 3 阶段:B2B 发票13 项检查通过
- 0 · 路线图
- 1 · 收据与保修
- 2 · 创作者版税
- 3 · B2B 发票
- 4 · 支付桥
- 5 · 模拟器
- 6 · Devnet:亲自复现
- 7 · 收银台
- 7.1 · 安全
- ✓ · 信任链
- ★ · 益处与用途
- ✎ · 十篇导读
- ▶ · 视频
- ? · 读者发现

在企业间支付中,难的不是转移资金,而是正确地转移:转给正确的交易对手、带上正确的参考号、算好手续费。Token-2022 可以把这些规则放进代币。这个模型构建了一种结算代币,它会拒绝没有发票备注的付款,也会拒绝未经批准的交易对手。
任务
一组公司之间相互结算发票。每笔付款都必须引用一张发票,只有经过核实的公司才能收款,网络运营方收取一笔有上限的小额手续费。
模型
| 规则 | Token-2022 扩展 | 效果 |
|---|---|---|
| 平台手续费 0.25%,上限 50 个单位 | Transfer Fees | 代币在每次转移时预扣手续费 |
| 仅限获批公司 | Default Account State = Frozen | 新账户初始为冻结状态;发行方完成自己的 KYB 检查后再解冻 |
| 发票备注必填 | Required Memo(在收款账户上) | 紧邻其前没有备注的付款会被拒绝。备注文本本身不在链上检查:请在对账时核对发票号。 |
流程:发行方创建铸币;每家公司开设一个要求备注的收款账户;发行方批准(解冻)经核实的公司;付款方在同一笔交易中发送备注 invoice:INV-… 和转账。
代码
文件:lab/code/src/03-b2b-invoice.ts · Apache-2.0
// Model 3: B2B settlement token with built-in rules (Token-2022, not the WNS program itself):
// - Transfer Fees: a platform fee taken by the token itself;
// - Default Account State = Frozen: only accounts the issuer thaws (verified counterparties) can hold it;
// - Required Memo: the receiving account rejects any payment that carries no memo at all.
// Token-2022 checks THAT a memo exists, not WHAT it says: a wrong invoice number still passes on-chain.
// Matching the invoice number is done off-chain, at reconciliation (see matchInvoicePayment below).
// License: Apache-2.0. Example code, not audited. Devnet first. A real stablecoin issuer is a licensed entity.
import { Keypair, PublicKey, SystemProgram, Transaction, TransactionInstruction, sendAndConfirmTransaction } from '@solana/web3.js';
import {
AccountState, ExtensionType, TOKEN_2022_PROGRAM_ID,
createEnableRequiredMemoTransfersInstruction, createInitializeAccount3Instruction,
createInitializeDefaultAccountStateInstruction, createInitializeMintInstruction,
createInitializeTransferFeeConfigInstruction, createThawAccountInstruction,
createTransferCheckedWithFeeInstruction, getAccountLen, getMintLen,
} from '@solana/spl-token';
import { getConnection, loadKeypair } from './common.js';
export const DECIMALS = 6;
/** The canonical SPL Memo program that Token-2022 checks for "required memo" accounts.
* Note: newer @solana/spl-memo releases default to a different program ID, so we build the memo ourselves. */
export const SPL_MEMO_PROGRAM_ID = new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');
export function memoInstruction(text: string, signer: PublicKey): TransactionInstruction {
return new TransactionInstruction({
programId: SPL_MEMO_PROGRAM_ID,
keys: [{ pubkey: signer, isSigner: true, isWritable: false }],
data: Buffer.from(text, 'utf8'),
});
}
export const FEE_BPS: number = 25; // 0.25%
export const FEE_CAP = 50n * 10n ** BigInt(DECIMALS); // at most 50 units per transfer
export const settlementMintSpace = () => getMintLen([ExtensionType.TransferFeeConfig, ExtensionType.DefaultAccountState]);
export const invoiceAccountSpace = () => getAccountLen([ExtensionType.TransferFeeAmount, ExtensionType.MemoTransfer]);
/** Issuer creates the settlement mint. It keeps the freeze authority: thawing = approving a counterparty. */
export function buildSettlementMint(issuer: PublicKey, mint: PublicKey, rentLamports: number): TransactionInstruction[] {
return [
SystemProgram.createAccount({ fromPubkey: issuer, newAccountPubkey: mint, space: settlementMintSpace(), lamports: rentLamports, programId: TOKEN_2022_PROGRAM_ID }),
createInitializeTransferFeeConfigInstruction(mint, issuer, issuer, FEE_BPS, FEE_CAP, TOKEN_2022_PROGRAM_ID),
createInitializeDefaultAccountStateInstruction(mint, AccountState.Frozen, TOKEN_2022_PROGRAM_ID),
createInitializeMintInstruction(mint, DECIMALS, issuer, issuer, TOKEN_2022_PROGRAM_ID),
];
}
/** A company opens an account that demands an invoice memo on every incoming payment. */
export function buildInvoiceAccount(company: PublicKey, account: PublicKey, mint: PublicKey, rentLamports: number, requireMemo = true): TransactionInstruction[] {
return [
SystemProgram.createAccount({ fromPubkey: company, newAccountPubkey: account, space: invoiceAccountSpace(), lamports: rentLamports, programId: TOKEN_2022_PROGRAM_ID }),
createInitializeAccount3Instruction(account, mint, company, TOKEN_2022_PROGRAM_ID),
...(requireMemo ? [createEnableRequiredMemoTransfersInstruction(account, company, [], TOKEN_2022_PROGRAM_ID)] : []),
];
}
/** Issuer approves (thaws) an account after its own KYB checks off-chain. */
export function buildApproveCounterparty(issuer: PublicKey, mint: PublicKey, account: PublicKey): TransactionInstruction[] {
return [createThawAccountInstruction(account, mint, issuer, [], TOKEN_2022_PROGRAM_ID)];
}
/** Fee the token will take: 0.25% capped at 50 units. Must match the mint config exactly.
* Token-2022 rounds the fee UP (ceiling division), and TransferCheckedWithFee rejects any other value.
* Example: 401 base units at 25 bps = 1.0025 -> fee 2, not 1. (Fixed 2026-11-09, reported by a reader.) */
export function expectedFee(amount: bigint): bigint {
if (amount === 0n || FEE_BPS === 0) return 0n;
const raw = (amount * BigInt(FEE_BPS) + 9_999n) / 10_000n;
return raw > FEE_CAP ? FEE_CAP : raw;
}
export const invoiceMemo = (invoiceId: string) => `invoice:${invoiceId}`;
/** Memos written by the Memo program, read from transaction logs. The Memo program logs
* 'Program log: Memo (len N)' and then the text on the next line (older versions: 'Memo (len N): "text"'). */
export function memosFromLogs(logs: string[]): string[] {
const out: string[] = [];
logs.forEach((l, i) => {
const m = /Memo \(len (\d+)\)(?:: "(.*)")?$/.exec(l);
if (!m) return;
if (m[2] !== undefined) out.push(m[2]);
else if (logs[i + 1]?.startsWith('Program log: ')) out.push(logs[i + 1].slice('Program log: '.length));
});
return out;
}
/** Reconciliation (off-chain): the on-chain rule only proves that SOME memo was attached.
* Accept a payment for an invoice only if it carries exactly one invoice memo and it is the expected one. */
export function matchInvoicePayment(logs: string[], invoiceId: string): boolean {
const inv = memosFromLogs(logs).filter(m => m.startsWith('invoice:'));
return inv.length === 1 && inv[0] === invoiceMemo(invoiceId);
}
/** Pay an invoice: the memo instruction must come right before the transfer. */
export function buildPayInvoice(args: { mint: PublicKey; from: PublicKey; to: PublicKey; payer: PublicKey; invoiceId: string | null; amount: bigint }): TransactionInstruction[] {
return [
...(args.invoiceId ? [memoInstruction(invoiceMemo(args.invoiceId), args.payer)] : []),
createTransferCheckedWithFeeInstruction(args.from, args.mint, args.to, args.payer, args.amount, DECIMALS, expectedFee(args.amount), [], TOKEN_2022_PROGRAM_ID),
];
}
/** Example of sending one step on a real cluster (devnet by default). */
export async function createSettlementMint() {
const connection = getConnection();
const issuer = loadKeypair();
const mint = Keypair.generate();
const rent = await connection.getMinimumBalanceForRentExemption(settlementMintSpace());
await sendAndConfirmTransaction(connection, new Transaction().add(...buildSettlementMint(issuer.publicKey, mint.publicKey, rent)), [issuer, mint]);
return mint.publicKey;
}
测试中发现的真实陷阱:@solana/spl-memo 的新版本默认使用不同的程序 ID。Token-2022 检查的是规范的 SPL Memo 程序(MemoSq4g…),所以代码自己构造备注指令。务必核对程序 ID,而不只是包名。
已验证的内容
在 LiteSVM 中:创建带手续费和默认冻结规则的铸币;卖方账户要求备注;发行方为买方注资;没有发票备注的付款被拒绝("No memo in previous instruction");付给未获批公司的款项被拒绝("Account is frozen");发票 INV-2026-0042 已支付;发票号记录在链上;卖方从 1,000 中收到 997.5,2.5 作为手续费被预扣;对 100,000 的付款,手续费上限稳定在 50。自 11 月 9 日起:手续费与 Token-2022 完全一样向上取整(401 个基本单位支付 2 的手续费),发票号错误的付款在链上通过,但会被对账拒绝。
用在哪里
- 有大量小额发票的供应商网络和交易市场。
- 需要清晰审计轨迹的跨境 B2B 支付。
- 使用代币化存款或稳定币的企业资金管理试点(如新韩案例)。
局限与风险
- 发行稳定的结算代币受到监管;这里只是技术层。
- 发行方的冻结权限很大。请使用多签和清晰的治理。
- 备注是公开的。只写发票号,绝不写发票内容。
- Token-2022 只检查备注是否存在,不检查内容。错误的发票号在链上照样通过;请始终将付款与你的发票清单对账(
matchInvoicePayment)。 - 手续费向上取整。请用与 Token-2022 相同的公式计算,或从铸币读取,绝不要用简单的整数除法。
- 留存在账户中的手续费必须由手续费权限方收取;请规划这项操作。
图说 Wen
Wen 在此模型中的位置
这里的结算代币是由受监管方发行的稳定单位;WEN 并不打算作为发票货币。Wen 的角色是故事:WNS——WEN 诗歌 NFT 背后的标准——让很多人第一次接触到这个模型所用的 Token-2022 机制。社区或商业网络仍可以在发票流程之外,用 WEN 结算成员之间的小额服务费或小费。
Wen 的主线:一个合约,处处可见
实验室的每个模型都免费且开放,并带着同一个签名:$WEN 代币合约。复制它,在你自己的文档中重复它,使用前务必在浏览器上核验。
WENWENvqqNya429ubCdR81ZmD69brwQaaBYY6p3LCpk
核验:Solana Explorer · 如何找到合约 ID
开放使用政策
- 免费且开放。实验室的全部代码以 Apache License 2.0 发布,与 Wen Program Library 相同。无论是否商用,都可以使用、修改、发布;请保留许可声明。
- 只用开放工具。基于公开且有文档的工具构建:Solana SPL Token-2022(Token Extensions)、Wen New Standard(WNS)的代币布局、Solana Pay,以及用于本地测试的 LiteSVM。
- 规则:始终核验你自己的模型。运行测试,从 devnet 开始,阅读官方文档,检查每个账户和金额,并在任何主网使用之前获得独立审计。未经核验的模型不是模型,而是猜测。
- 未经审计,不构成建议。这些是教学示例,不构成金融、法律或税务建议,也不是持牌的支付或银行产品。在大多数国家,支付、稳定币和收单都是受监管的活动。
- 安全。切勿把私钥粘贴到任何网站。不要安装 npm 包
@wen-community/wen-new-standard:npm 已因恶意将其移除。请从官方来源构建。
由 Wen 为社区讲述。更多内容见我们的编辑与数据政策。
Wen Open Lab · 路线图 · 全部代码 · GitHub 上的 Wen Program Library





