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의 역할은 이야기입니다. WEN 시 NFT 뒤의 표준인 WNS가 많은 사람에게 이 모델이 쓰는 Token-2022 장치를 처음 알렸습니다. 그래도 커뮤니티나 비즈니스 네트워크는 인보이스 흐름 밖에서 회원 간 소액 서비스 수수료나 팁을 WEN으로 정산할 수 있습니다.
Wen의 실: 하나의 컨트랙트, 어디에나
랩의 모든 모델은 무료이고 공개되어 있으며, 모두 같은 서명을 지닙니다. 바로 $WEN 토큰 컨트랙트입니다. 복사해 내 문서에도 적어 두고, 쓰기 전에는 반드시 익스플로러에서 확인하세요.
WENWENvqqNya429ubCdR81ZmD69brwQaaBYY6p3LCpk
확인: Solana Explorer · 컨트랙트 ID 찾는 법
오픈 사용 정책
- 무료이고 공개. 랩의 모든 코드는 Wen Program Library와 같은 Apache License 2.0으로 공개됩니다. 상업적이든 아니든 쓰고, 고치고, 배포하세요. 라이선스 고지만 유지하면 됩니다.
- 오픈 도구만. 공개되어 있고 문서화된 도구로 만듭니다: 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





