Skip to content

Adding a network ​

Every crypto deposit and withdrawal goes through two services that do the money part the same way on every network. A network only has to say how to find incoming transfers and how to send a withdrawal. This page explains the pieces and how to add a new chain.

15 minutesDeveloperDevelopers, DevOpsVerified against the platform code

The pieces ​

PieceFileJob
DepositServiceapp/Services/Deposits/DepositService.phpRecords each incoming transfer once and credits it once it has enough confirmations
WithdrawalServiceapp/Services/Withdrawals/WithdrawalService.phpHolds the amount when a user asks, sends it when approved, pays it out or refunds it exactly once
Network configconfig/networks.phpOne entry per network id: its scanner, sender, sweeper and address generator, fee columns, token contract column, explorer link
Scannera class implementing DepositScanner (and AddressScanner to watch any address list)Lists the transfers it sees (DetectedDeposit objects) on the addresses it is given (WatchedAddress: user deposit addresses or merchant invoice addresses). Nothing else
Sendera class implementing WithdrawalSender + TransferSenderSends one Transfer (a user withdrawal, merchant payout or merchant refund) and reports the result (SendResult). Nothing else
Sweepera BridgeSweeper (DepositSweeper)Moves funds from a deposit address to the hot wallet (Sweep: a user deposit or a merchant invoice address)
Address generatora class implementing AddressGeneratorCreates a user's deposit address the first time they open the deposit page
deposits:scan {network}scheduler, every minute, one per network with a scannerRuns the scanner and hands each transfer to DepositService
deposits:sweep {network}scheduler, every 3 minutes, one per network with a sweeperClaims each confirmed, unswept deposit once and asks its sweeper to move it (--retry re-queues failed ones)
withdrawals:syncscheduler, every minuteFinishes withdrawals whose bridge wrote the result into the database
Merchant moduleMerchantTransferService, MerchantDepositDetector, MerchantCollectionServiceMerchant payouts / refunds, invoice payments and fund collection on the same scanners, senders and sweepers (merchant:monitor-deposits, merchant:collect-funds, merchant:sync-transfers). A new network works for merchants too

Ready-made drivers:

DriverNetworksHow
EvmExplorerScanner, EvmBridgeSender, EvmBridgeSweeper, EvmAddressGeneratorETH, ERC-20, BNB, BEP-20, Polygon, MATIC-20, and any EVM chain you addDeposits from an Etherscan-compatible API (txlist / tokentx) by chain_id; withdrawals and sweeps through the chain's bridge; addresses generated locally. All set up by one EvmChain::define(...) line
TronScanner, TronBridgeSweeperTRX, TRC-20Tronscan API (credits only transfers Tronscan reports as confirmed); sweeps through bridges/tron
SolanaBridgeSweeperSOL, SPLSweeps through bridges/solana (deposits come from the Solana monitors)
GatewaySender, GatewayAddressGeneratorthe non-EVM networksCall the existing bridge / gateway for that network id

Solana, XRP, TON, Bitcoin, the custom chain and Fireblocks keep their own monitors or callbacks (their APIs differ), but they record and credit through DepositService and finish withdrawals through WithdrawalService.

What the services guarantee ​

How the bridges report results

  • EVM, Tron, Solana (bridges/ethereum, bnb, polygon, tron, solana) answer at once and write the result into the database later: withdrawals.txn (sent) or withdrawals.status = failed, and deposits.wallet_transfer_status (processed, failed, fee_error) for sweeps. Each request names its target (bridges/result-target.js): user withdrawals → withdrawals, merchant payouts / refunds → merchant_payouts / merchant_refunds (chain_txn, chain_status), user sweeps → deposits, merchant collections → merchant_deposit_addresses.sweep_status. Any other target is refused before anything is signed. They answer HTTP 200 with {"message":"Not successful"} when they failed before broadcasting: the platform treats that as refused (withdrawal refunded, sweep retried next run).
  • TON (bridges/ton) answers with the result: {success: true, txHash} (sent; without a hash the withdrawal waits), {success: false} (nothing sent, refunded) or {success: false, unknown: true} (held for review).
  • A bridge writes failed only when the coins certainly didn't leave (refused before broadcasting, reverted on chain, Solana blockhash expired and not in history, Tron node refused the broadcast). When the outcome is unknown (not mined in time, connection lost) it writes nothing, and withdrawals:sync flags the withdrawal Needs review after 2 hours (WithdrawalService::BRIDGE_TIMEOUT_HOURS).

Deposits

  • A transfer is stored once per network (unique source_key, normally transaction:address; tokens add the contract and log index; memo networks add the memo). Running a scanner twice, or a scanner and a callback at the same time, can't create a second deposit.
  • It is credited once: the deposit row is locked and must still be pending; the credit and the status change happen in one database transaction.
  • Below the currency's minimum, or while the network's deposits are switched off: stored as ignored, never credited.
  • The deposit fee (deposit_fee_<suffix> columns) is taken when crediting. Confirmations come from the currency (Min deposit confirmations, at least 1).

Withdrawals

  • Request: the amount moves from the Funding balance to In withdraw in one guarded update that refuses to go below zero. Ten parallel requests for more than the balance: one succeeds.
  • Approve: the withdrawal is locked and switched to Sending first, then the sender runs outside any database transaction, then the result is applied. Two admins (or a double click) can't send it twice, and a database retry can never resend it.
  • Result: sent → paid out; queued → Waiting provider approval until the network confirms; certainly failed → refunded; unknown (timeout, bridge crash) → Needs review: the amount stays held, nothing is resent or refunded until an admin decides (see Approvals).
  • The held amount is released exactly once (withdrawals.settled_at), whether it is paid out or refunded, whatever retries or callbacks arrive later.

What each network checks before crediting ​

NetworkA deposit counts only when
EVM chainsThe explorer reports it successful (not isError, receipt OK), it's a plain transfer to the user's address (not a contract call), it doesn't come from the hot wallet; tokens: the contract is this chain's contract column of a listed currency
TronTronscan reports it confirmed and SUCCESS, not risky; TRX only (TRC-10 tokens ignored); TRC-20: the contract of the transaction is a listed trc_contract
SolanaThe transaction succeeded, and a transfer in it goes to the user's address (a transaction that only mentions the address credits nothing); SPL: into the user's own token account (owner checked) with the listed mint
XRPtesSUCCESS, the destination tag belongs to a user, and only the delivered XRP is credited (partial payments and issued tokens named "XRP" can't inflate it)
TONInternal, incoming, not aborted, not bounced, and the memo belongs to a user
BitcoinA receive output to a user address, each output credited on its own
Custom chainThe explorer reports it successful; tokens: a listed custom_contract. Credited after the sweep
FireblocksThe webhook signature is valid and Fireblocks reports COMPLETED

Add an EVM chain (one line) ​

EVM chains work the same way, so a new one is one line in config/networks.php. Ethereum, BNB Smart Chain and Polygon are set up exactly like this:

php
// config/networks.php (end of the file)
    + EvmChain::define(30, 31, 8453, 'ETH', env('APP_BASE_URL', 'http://localhost:8008'), 'base', 'https://basescan.org',
        'APP_BASESCAN_API', 'APP_BASESCAN_KEY', contract: 'base_contract', fee: 'base');
ArgumentExampleMeaning
coin id, token id30, 31Ids of the two rows in the networks table (token id null for a coin-only chain)
chain id8453Chain id for the explorer API (Etherscan v2 serves many chains by id)
symbol'ETH'The coin's symbol in Currencies
bridgeenv('APP_BASE_URL', ...)URL of the chain's bridge: a copy of bridges/ethereum started with the chain's RPC (see Bridges)
settings'base'Hot wallet settings: base.wallet and base.private_key
explorer'https://basescan.org'Transaction links (/tx/<hash>)
API / key'APP_BASESCAN_API', 'APP_BASESCAN_KEY'.env names of the explorer API URL (default Etherscan v2) and key(s). Without a key of its own the chain uses APP_ETHERSCAN_KEY
contract:'base_contract'Currency column with the token contract on this chain
fee:'base'Suffix of the token fee columns (withdraw_fee_base, ..._fixed, deposit_fee_base, ..._fixed). When those columns don't exist, the generic withdraw_fee / deposit_fee columns are used
routes: / decimals:['eth', 'erc'], [12, 8]Bridge route names and amount decimals; the defaults match bridges/ethereum

That line gives the chain deposit scanning (scheduled automatically), sweeps to the hot wallet, withdrawals with withdrawals:sync, deposit addresses and explorer links. Besides it you need:

  1. Two rows in networks (migration or seeder) with those ids, type coin. They appear in Admin → Networks, where deposits and withdrawals are switched on or off.
  2. The bridge running for the chain, and the hot wallet saved in the two settings. Copy bridges/ethereum to a new folder and change two lines in its eth-config.js: global.geth (the chain's RPC URL, for example process.env.APP_BASE_NODE) and global.port (a free port, 8008 above). Its routes stay eth / erc, which is the routes: default. Block the port from outside like the other bridges.
  3. For tokens: the contract column on currencies (a migration), filled for each token. The admin Currencies form doesn't have a field for a new chain's contract yet; set it in the database or add the field.

The test suite adds a chain like this and runs it end to end (address, deposit through the chain-id API, credit, withdrawal through its own bridge, fee fallback, explorer link).

Add any other chain ​

Write two classes and register them:

php
// app/Services/Networks/Drivers/MyChainScanner.php
class MyChainScanner implements DepositScanner
{
    public function scan(Network $network, array $config): iterable
    {
        foreach (WalletAddress::where('network_id', $network->id)->has('user')->get() as $address) {
            foreach ($this->api()->incoming($address->address) as $tx) {
                yield new DetectedDeposit(
                    networkId: $network->id,
                    userId: $address->user_id,
                    currencyId: Currency::where('symbol', 'MYC')->value('id'),
                    txn: $tx['hash'],
                    address: $address->address,
                    amount: $tx['amount'],            // decimal string, in coins
                    confirmations: $tx['confirmations'],
                );
            }
        }
    }
}

// app/Services/Networks/Drivers/MyChainSender.php
class MyChainSender implements WithdrawalSender
{
    public function send(Withdrawal $w, string $amount, array $config): SendResult
    {
        $r = $this->bridge()->send($w->address, $amount, $w->id);   // $amount = amount − fee

        return match (true) {
            $r->hash !== null => SendResult::sent($r->hash),
            $r->accepted => SendResult::queued($r->id),          // the bridge writes the hash later
            default => SendResult::failed($r->error),            // only when nothing was sent
        };
        // Throwing (timeout...) = unknown: the withdrawal is held for an admin
    }
}
php
// config/networks.php
40 => ['sender' => MyChainSender::class, 'fee' => '', 'sync' => true, 'explorer' => 'https://explorer.mychain.org/tx/%s',
    'scanner' => ['class' => MyChainScanner::class],
    'address' => MyChainAddressGenerator::class,     // creates user deposit addresses
    'sweeper' => MyChainSweeper::class],             // optional: networks where funds land on user addresses

Rules for drivers:

  • A scanner only reports. Never write deposits or balances yourself; return every transfer you see, old ones included. DepositService skips what it already has.
  • Give a key when one transaction can pay the same address several times (txn:address:logIndex), and a paymentId key part on memo networks.
  • Set finalized: true when the network reports finality instead of a confirmation count, and transferStatus: 'processed' when funds land in the hot wallet directly (memo networks, no sweep).
  • A sender returns failed only when it is certain nothing left the hot wallet. When unsure, throw or return unknown.
  • If your bridge writes the transaction hash (or status = 'failed') into withdrawals later, set 'sync' => true and withdrawals:sync finishes them.

Test without a blockchain ​

Drivers can be swapped for fakes:

php
NetworkRegistry::fakeSender(NETWORK_ERC, new MyFakeSender(SendResult::sent('0xabc')));
NetworkRegistry::fakeScanner(NETWORK_ERC, new MyFakeScanner([$detectedDeposit]));
Artisan::call('deposits:scan', ['networks' => ['erc20']]);

Explorer-based scanners can be tested with Http::fake(). The project's own suite (funds_test.php, 124 checks, and networks_test.php, 91 checks covering every network above with mocked APIs, both rolled back) covers recording and crediting once, confirmations, minimums, fees, legacy rows, sweep-first networks, the EVM and Tron scanners against fake APIs, the EVM bridge sender, sweeper and address generator, the Tron and Solana sweepers, TON's answers, the bridges' "Not successful" answer and silent failures, a newly added EVM chain, every withdrawal outcome, internal transfers, cold-storage transfers, the user API, and the webhook guards. Real concurrency was checked too: 10 parallel withdrawal requests over HTTP (one accepted) and 5 processes approving the same withdrawal (one send).

Commands ​

bash
php artisan deposits:scan            # every network with a scanner
php artisan deposits:scan erc20 trx  # by slug or id
php artisan deposits:sweep           # move confirmed deposits to the hot wallet (--pause=5 between sweeps, --retry for failed ones)
php artisan withdrawals:sync         # finish bridge-confirmed / bridge-failed withdrawals

Owner documentation for the CryptoTech exchange platform.