CPG-Core FSD SmartContract

FSD — Core

A. Document controlA. Kiểm soát tài liệu

Doc IDCPG-FSD-CPG-Core_FSD_SmartContract
VersionPhiên bản1.1
StatusTrạng tháiDraft
OwnerCPG BA / Architecture
AudienceĐối tượngBackend, QA, Product, Security, Load-test engineering
ClassificationPhân loạiInternal
Effective dateNgày hiệu lực01/12/2026
Related docs Core Index · BR/NFR Catalog

B. Version historyB. Lịch sử phiên bản

Version Date Author ChangesThay đổi
1.0 15/07/2026 Khoa Trinh Version 1.0, Initial FSD-SmartContract (Doc02) from BR-09/BR-10
1.1 14/08/2026 Khoa Trinh Version 1.1: update UC-GOV-02, FEAT-VA-04, Actors (ADMIN_ROLE)

C. Table of contentsC. Mục lục

D. ContentD. Nội dung

1. Scope

The Smart Contract module is the on-chain custody and fund-movement layer for CPG on EVM (BSC, Ethereum, Polygon). Identical Solidity logic is deployed on all three networks. It answers: where customer and merchant funds sit on-chain, who may move them, what fees apply at settlement, and how operators stop or reverse movements under incident and compliance rules.

1.1 In scope

  • Two-tier EVM custody: Virtual Account (ingress) → Forwarder (settlement / fee split)
  • Per-customer / per-merchant CREATE2 + EIP-1167 clone deployment and address prediction
  • Deposit lifecycle: register → mark pending / flush / refund (VA)
  • Settlement lifecycle: register → mark ready / settle / cancel (Forwarder)
  • BR-09: refund to verified owner (destination policy, exchange-source block, manual approval)
  • BR-10: emergency stop of fund movement (incl. scale ≤5 min @ \~100k addresses), unsupported-token recovery via approval, ≥2 approvals for fund-destination wallet changes at every tier
  • Role / signer access control, pause matrices, events for reconciliation
  • JSON-RPC / ethers contract call payloads for load testing (no HTTP API owned by this module)

1.2 Out of scope

  • Ledger journal, Numscript, over-book prevention (FSD-Ledger)
  • Chain scanning / finality / reorg un-credit (FSD-Sync)
  • Full Doc03 restatement (application security baseline is referenced only)
  • Custody key ceremony / HSM / MPC depth (A4: cross-linked)
  • Merchant Portal / CRM UI
  • TRON dedicated-address rail detail (A2 / B1): noted only where pause/refund policy must remain consistent
  • Professional audit execution (audit plan is a sibling deliverable per BR-10)

1.3 Actors

Actor Role
OPERATOR_ROLE (VA) / operator (FW) Deposit / transaction lifecycle (register, pending, flush, refund, cancel)
ADMIN_ROLE (VA, 3 fixed) Pause; 2-of-3 governance: (setBeneficiary, setRefundWallet, setTokenSupport), unpause
Forwarder signers (3 fixed) 2-of-3 governance: beneficiary, fee wallets, fee schedule, roles, pause
settlementManager (FW) settleTransaction / settleBatch
Ops backend Off-chain KYT/KYC, exchange detection, dual-control workflow, batch pause orchestration
Platform audit / security Incident trigger, post-pause investigation, bytecode freeze gate

Fig 1: Contract main flow

Contract Role Upgradeable?
CloneFactory EIP-1167 deploy helper N/A
VirtualAccountFactoryV1 CREATE2 + predictVirtualAccountAddress No: implementationAddress immutable
ForwarderFactoryV4 CREATE2 + predictForwarderAddress No: immutable
VirtualAccountV1 Per-customer ingress custody No: clone logic fixed at deploy
ForwarderV4 Per-merchant hot wallet + fee routing No

Immutability constraint (BR-10): pause, rescue, and multi-approval destination controls must be in design before final bytecode. They cannot be patched after same-address mainnet deploy.

2. Business Requirement

Governing requirements are defined in BR-09-10. This FSD does not rewrite the BR; it maps each requirement to design artifacts below.

BR section Need (summary) Solution location in this FSD
BR-09 (§5.9) Refunds to KYC-verified / whitelisted wallet; block refund-to-source when source is an exchange; manual refund requires approval Flow §3.2; FEAT-REF-; UC-REF-; §7.2
BR-10 (§5.10) Stop all fund movement ≤5 min @ 100k addresses; recover unsupported tokens via approval; ≥2 approvals for beneficiary / refund wallet changes at every tier Flow §3.4–§3.6; FEAT-IR-; FEAT-GOV-; UC-PAUSE / UC-RESCUE / UC-GOV; §6; §7.2

2.1 BR → FSD coverage matrix

ID Level Coverage in this FSD
BR-09 AC1 Refund destination \= KYC-verified / whitelisted wallet HARD FEAT-REF-01; §3.2; UC-REF-01
BR-09 AC2 Block refund-to-source when source is exchange HARD FEAT-REF-02; §3.2; UC-REF-02
BR-09 AC3 Manual refund requires approval HARD FEAT-REF-03; UC-REF-03
BR-10 AC1 Emergency stop all fund movement ≤5 min @ 100k addresses HARD FEAT-IR-01; §3.4; UC-PAUSE-01; §6 load notes
BR-10 AC2 Unsupported token rescue via approval process HARD FEAT-IR-02; §3.5; UC-RESCUE-01
BR-10 AC3 ≥2 approvals to change beneficiary / refund wallets at every tier HARD FEAT-GOV-01; §3.6; UC-GOV-01/02

2.2 Contract requirements (pre-audit)

Requirement BR Baseline chosen in this FSD
Scale pause BR-10 AC1 Factory-level / shared pause authority plus ops batch orchestrator calling per-clone pause (or a new registry-linked pause) so ≤5 min @ 100k is demonstrable; single-tx global pause preferred if bytecode allows without breaking CREATE2 same-address strategy
rescueToken(token, to, amount) (name TBD) BR-10 AC2 Approval-gated (VA: ≥2 admins or signer set; FW: 2-of-3 proposal type RESCUE_TOKEN); only for tokens not in unsettled accounting / or only unsupported tokens
VA destination multi-approval BR-10 AC3 Align VA beneficiary + refund wallet updates with Forwarder-style ≥2-of-N before execute
Exchange / KYC refund gates BR-09 Prefer Off-chain enforcement in v1 with audit trail; optional on-chain refundExchangeBlocked / force toSource=false

Transparency note (from BR-10): global pause and rescue go beyond typical BitGo / Coinbase Commerce forwarders; they are client-driven by immutable same-address scale.

3. Flow

All EVM fund movement that changes on-chain custody balances goes through VA / Forwarder functions below. Amounts are integer token minor units. Off-chain ledger credit / debit remains FSD-Ledger territory; this module emits events for reconciliation.

3.0 System context


Fig 2: Contract Artifacts

Item Detail
Deploy createVirtualAccount(salt, InitParams) / createForwarder(salt, InitParams)
Salt finalSalt \= keccak256(abi.encodePacked(msg.sender, salt))
Predict predictVirtualAccountAddress / predictForwarderAddress before first deployment
State (VA) DepositStatus: NONE → REGISTERED → PENDING / FLUSHED / REFUNDED
State (FW) TxStatus: NONE → REGISTERED → READY → SETTLED

3.1 Deposit → flush → settle (happy path context)

Step Who Action
1 Payer ERC20 transfer to predicted VA address
2 Operator registerDeposit(depositId, token, source, amount)
3 Ops KYT / sanctions
4a Pass Operator flush / flushBatch → beneficiary (Forwarder)
4b Fail Operator markPending then refund path (§3.2)
5 Operator registerTransaction on Forwarder
6 Settlement manager settleTransaction / settleBatch

3.2 BR-09: Refund to verified owner

Step Who Action Implementation
1 Ops / Compliance Decide refund; confirm customer KYC-verified / whitelisted wallet is set as refundWallet (or update via approved config change) Off-chain; wallet bound On-chain via setRefundWallet
2 Ops If deposit source is an exchange hot wallet, forbid toSource=true Off-chain
3 Dual control Second approver signs off in ops / ticket workflow before operator key is used Off-chain (BR-09 AC3); on-chain second approval
4 Operator refund(depositId, toSource) while status REGISTERED or PENDING On-chain
5 Contract Transfer full amount to destination; status → REFUNDED; emit DepositRefunded On-chain
toSource Destination When allowed (policy)
true Recorded Deposit.source Only if source is not an exchange / is verified owned by customer
false refundWallet Default for exchange deposits and KYC-verified wallet refunds

Blocked when paused: yes (VA).

3.3 Pause behavior: fund movement blocked

VirtualAccountV1: admin pause / unpause:

Function Blocked when paused?
registerDeposit, markPending, flush, flushBatch, refund Yes
setBeneficiary, setRefundWallet, setTokenSupport No
pause / unpause No

ForwarderV4: SET_PAUSED via 2-of-3:

Function Blocked when paused?
registerTransaction, markReady, settleTransaction, settleBatch Yes
cancelTransaction No
propose / approve No (required to unpause)

3.4 BR-10: Emergency stop (≤5 min @ 100k)

  1. On-chain: Clones honor a shared pause authority (factory-owned or pause registry checked in whenNotPaused / custom modifier) and/or retain per-clone pause for fine control. Chosen baseline: factory/registry-linked pause readable by clones + keep admin per-clone pause.
  2. Off-chain: Ops batch orchestrator fan-outs pause txs (or hits one factory pause) with pre-funded gas, nonce managers, and RPC fan-out so wall-clock ≤5 minutes including public-exploit scenarios without relying solely on FW 2-of-3 latency for the first stop.
  3. Demo AC: Trigger → all fund-moving calls on watched address set revert/paused within ≤5 minutes at 100k-address scale.

Order (DR): pause ingress (VA) first, then settlement (FW); resume reverse: see A4.

3.5 BR-10: Unsupported token recovery

Step Who Action Implementation
1 Ops Detect unsupported / mistaken token balance (monitoring) Off-chain
2 Approvers Dual approval of destination and amounts Off-chain + on-chain proposal
3 Contract rescueToken(token, to, amount) (or FW ProposalType.RESCUE_TOKEN): transfers only tokens outside unsettled deposit/tx accounting On-chain
4 Events Emit rescue event for audit / ledger adjustment On-chain

3.6 BR-10: Destination wallet changes (≥2 approvals every tier)

Requirement Action Implementation
FW beneficiary propose(SET_BENEFICIARY) + approve (≥2 of 3), TTL 7 days On-chain
FW fee wallets SET_FEE_WALLETS 2-of-3 On-chain
VA refund wallet setRefundWallet 2-of-3 On-chain

4. Features

4.1 Virtual Account

FEAT-VA-01 Register deposit

  • registerDeposit(depositId, token, source, amount): OPERATOR; unique depositId; token allowlisted; unsettled + amount ≤ balance.
  • Acceptance: Emits DepositRegistered; duplicate id reverts DuplicateDeposit.

FEAT-VA-02 Mark pending / flush

  • markPending, flush, flushBatch: OPERATOR; REGISTERED (and flush from PENDING per product rules).
  • Acceptance: DepositFlushed to beneficiary; unsettled decreased.

FEAT-VA-03 Refund execution

  • refund(depositId, toSource): OPERATOR; REGISTERED or PENDING → REFUNDED.
  • Related BR: BR-09.

FEAT-VA-04 Config and pause

  • pause: ADMIN (for quick response on emergency case)
  • setBeneficiary, setRefundWallet, setTokenSupport, unpause: governance 2-of-3.

4.2 Forwarder

FEAT-FW-01 Register / ready / cancel

  • Operator lifecycle; cancel allowed when paused.

FEAT-FW-02 Settle / settleBatch

  • Settlement manager; fee + VAT split via FeeMath; net to beneficiary.
  • Acceptance: TransactionSettled(gross, txFee, settlementFee, vat, net).

FEAT-FW-03 Governance 2-of-3

  • propose / approve; types include SET_BENEFICIARY, SET_FEE_WALLETS, SET_FEE_SCHEDULE, SET_OPERATOR, SET_SETTLEMENT_MANAGER, REPLACE_SIGNER, SET_PAUSED.
  • Related BR: BR-10 AC3 (partial), AC1 (pause mechanism exists but not scaled).

4.3 BR-09 refund policy features

FEAT-REF-01 KYC-verified refund destination

  • The refund destination must be a customer KYC-verified / whitelisted wallet (refundWallet).
  • Implementation: Off-chain + on-chain storage of refundWallet.
  • Related BR: BR-09 AC1.
  • Acceptance: UC-REF-01: funds arrive at whitelisted wallet, not unverified EOA.

FEAT-REF-02 Block exchange refund-to-source

  • When a source is classified as an exchange, ops must call for a refund(..., false).
  • Implementation: Off-chain + on-chain.
  • Related BR: BR-09 AC2.
  • Acceptance: UC-REF-02: no transfer to exchange hot wallet.

FEAT-REF-03 Manual refund approval

  • Second human / system approval before OPERATOR broadcasts refund.
  • Implementation: Off-chain; on-chain dual approval optional.
  • Related BR: BR-09 AC3.
  • Acceptance: UC-REF-03: single operator cannot complete refund without recorded approval.

4.4 BR-10 incident-response features

FEAT-IR-01 Emergency stop at scale

  • Stop flush / refund / settle (and register as designed) within ≤5 minutes across \~100k addresses.
  • Implementation: on-chain factory/registry + orchestrator.
  • Related BR: BR-10 AC1.
  • Acceptance: UC-PAUSE-01 demo.

FEAT-IR-02 Unsupported token rescue

  • Approval-based recovery of mistaken unsupported ERC20.
  • Implementation: On-chain.
  • Related BR: BR-10 AC2.
  • Acceptance: UC-RESCUE-01.

FEAT-GOV-01 Dual approval for destination wallets (every tier)

  • ≥2 approvals for beneficiary and refund-wallet changes on VA and FW.
  • Implementation: On-chain + off-chain.
  • Related BR: BR-10 AC3.
  • Acceptance: UC-GOV-01, UC-GOV-02.

4.5 Factory features

Feature ID Capability Implementation
FEAT-FAC-01 CREATE2 create + predict address On-chain
FEAT-FAC-02 Shared / factory pause hook for clones On-chain (BR-10 AC1)

5. Usecases

Detailed use-case catalog for this module is maintained under 08_UC:Catalog use case chi tiết của module này được quản lý tại 08_UC:

6. Endpoints and Payloads This module has no HTTP API. “Endpoints” \= contract functions invoked via JSON-RPC (eth_sendRawTransaction) using ethers/viem/cast.

This module has no HTTP API. Contract ABI/RPC remains the endpoint surface.

Auth model: ECDSA signatures from role keys (OPERATOR, ADMIN, settlementManager, signers): keys held in HSM/MPC per A4; never in load-test plaintext long-term.
Placeholders: \<VA>, \<FW>, \<TOKEN>, \<OPERATOR>, \<ADMIN>: substitute deployed addresses per env.

6.1 Priority endpoints

Call Contract Caller Load-test role
createVirtualAccount Factory VA Deployer Address issuance soak
registerDeposit VA OPERATOR Primary ingress write
flush / flushBatch VA OPERATOR Sweep path
refund VA OPERATOR BR-09 path
pause / unpause VA ADMIN BR-10 stop (per clone)
registerTransaction FW operator Settlement ingress
settleBatch FW settlementManager Batch settle soak
propose / approve FW signers Governance / pause
factory/registry pause Factory / registry Pause authority BR-10 ≤5 min @ 100k
rescueToken VA / FW Approvers BR-10 rescue demo

Suggested profiles (tune per RPC): register 20–100 RPS across many VAs; flushBatch sized to gas ceiling (\~50–200 ids); pause fan-out as many parallel workers as nonce/gas allow for UC-PAUSE-01.

6.2 VA: registerDeposit

Example (ethers-style args):
json
{
"depositId": "0x1111111111111111111111111111111111111111111111111111111111111111",
"token": "\<TOKEN>",
"source": "0x00000000000000000000000000000000000000A1",
"amount": "1000000"
}

Expect: tx success; event DepositRegistered(depositId, token, source, amount).
Errors: DuplicateDeposit, TokenNotSupported, BalanceExceeded, ZeroAmount, paused.

6.3 VA: flushBatch

json
{
"depositIds": [
"0x1111111111111111111111111111111111111111111111111111111111111111",
"0x2222222222222222222222222222222222222222222222222222222222222222"
]
}

Expect: one DepositFlushed per id; ERC20 transfer to beneficiary.
Load note: bound batch length so worst-case gas \< block gas limit.

6.4 VA: refund (BR-09)

json
{
"depositId": "0x1111111111111111111111111111111111111111111111111111111111111111",
"toSource": false
}

Expect: DepositRefunded(depositId, token, destination, amount) with destination \== refundWallet when toSource=false.
Load-test policy: scripts must set toSource=false for exchange-tagged fixtures (UC-REF-02).

6.5 VA: pause / unpause (BR-10 per clone)

Expect: OZ Paused(account) / Unpaused(account); subsequent flush/refund revert.
Scale note: N independent txs. Do not use this alone to claim BR-10 AC1 until factory/orchestrator path exists.

6.6 FW: settleBatch

json
{
"txIds": [
"0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
]
}

Expect: TransactionSettled per id with fee breakdown.
Blocked when paused.

6.7 FW: propose / approve (SET_PAUSED / SET_BENEFICIARY)

Pause payload: ptype \= SET_PAUSED (6), data \= abi.encode(true).
Beneficiary payload: ptype \= SET_BENEFICIARY (0), data \= abi.encode(newBeneficiary).
Expect: ProposalCreated, ProposalApproved, at threshold ProposalExecuted (+ domain event).
Load note: Measuring BR-10 ≤5 min with FW 2-of-3 pause per clone is a known bottleneck: prefer Planned factory pause for the demo clock.

6.8 Factory: create / predict

InitParams: admin, operator, beneficiary, refundWallet, supportedTokens[].

6.9 Other endpoints (specify for post-adjustment load tests)

Function (proposed) Args Gate
pauseAll / registry setPaused(true) Pause authority; BR-10 AC1
rescueToken token, to, amount ≥2 approvals; BR-10 AC2
VA propose/approve for SET_BENEFICIARY / SET_REFUND_WALLET proposal data BR-10 AC3

6.10 Load-test constraints

  • Manage nonces per hot key; use dedicated test keys, never production HSM keys.
  • Cap flushBatch / settleBatch length by gas estimation before soak.
  • For UC-PAUSE-01, instrument wall-clock from trigger to last confirmed pause receipt: not average RPC latency alone.
  • Respect RPC provider RPS; fan-out across endpoints if needed for 100k.
  • Assert events via eth_getLogs / receipt logs for pass criteria.
  • Do not treat FW cancelTransaction as a refund (no ERC20 out).

7. Security

7.1 Application security (Doc03)

Fleet-wide application security is defined in Doc03: Application Security.
Apply as baseline for ops services and S2S callers that submit contract transactions:

Doc03 area Relevance
Part A trust zones / money-movement Operator / settlement callers are high-privilege money path
G1–G9 General controls Auth patterns, secrets (Vault), logging, SDLC
APPSEC-ID-13 Secrets injection (Vault CSI) for operator / signer material reference: not raw keys in app config
APPSEC-ID-16 Input validation on any ops HTTP that enqueues chain txs (depositId, addresses, amounts)
APPSEC-ID-19 Security / audit logging of who approved refunds and pause triggers
Logging / PII Never log private keys, mnemonics, or raw signer material; prefer addresses + role ids
SDLC Change control + audit before mainnet; A1 notes contracts not yet professionally audited

Out of Doc03 depth (cross-refs): on-chain custody cryptography and DR → A4

7.2 Specific security (Smart Contract module)

Aligned with A1 §7 Security Decisions and BR-09 / BR-10.

Control Requirement
Access control VA roles (OPERATOR / DEFAULT_ADMIN); FW operator, settlementManager, 2-of-3 signers
Reentrancy / CEI / SafeERC20 All fund-moving functions
Pause Emergency stop of fund movement
Refund destination KYC-verified wallet; no exchange source refund
Manual refund SoD ≥2 approvals before refund execution
Destination wallet changes ≥2 approvals at every tier (beneficiary / refund)
Unsupported token rescue Approval-based recover
Duplicate IDs Unique depositId / txId
Balance / unsettled checks Cannot over-allocate vs token balance
Token allowlist No fee-on-transfer / rebasing / hooks
Fee caps BPS ≤ 10_000; fees ≤ gross
Immutability Final bytecode before audit; no post-deploy logic upgrade
Cancel vs pause FW cancelTransaction remains available when paused

E. ReferencesE. Tham chiếu