clkhoo5211/VRFPublic 是一个托管在 GitHub 上的开源项目,采用 MIT License 许可证。
仓库全名
clkhoo5211/VRFPublic
README 摘要
On-chain Verifiable Randomness (VRF): Integration Guide English | 简体中文 | 繁體中文 A verifiable randomness service on BNB Smart Chain mainnet. Your contract sends a request; an oracle generates the random number with a BLS12-381 unique signature, the chain verifies it, and your contract receives the result in a callback. The seed includes the hash of the request block, so nobody can predict the result when the request is…
A verifiable randomness service on BNB Smart Chain mainnet. Your contract sends a request; an oracle generates the random number with a BLS12-381 unique signature, the chain verifies it, and your contract receives the result in a callback. The seed includes the hash of the request block, so nobody can predict the result when the request is sent, and anyone can re-verify it afterwards.
Network: BNB Smart Chain mainnet (chainId 56)
Payment: native BNB
Two ways to integrate: Subscription (prepaid, billed at actual cost) or Pay-per-request (attach BNB to each request)
Your contract asks for a random number. An oracle signs a seed that includes the hash of the request block. The chain verifies the signature, derives the random number from it and calls your contract back. A seed has exactly one valid signature, so the oracle cannot choose the result, and anyone can re-check it later.
0.1 Request lifecycle
sequenceDiagram
autonumber
participant C as Your contract
participant K as Coordinator
participant O as Oracle node
participant V as Verifier
participant A as HeaderArchive
C->>K: request(lane, subId, confirmations, callbackGas, numWords)
K->>K: reserve the worst-case cost from the subscription
K-->>O: event Requested (request id, request block)
O->>O: wait for the confirmations, read the request block hash
O->>O: seed = hash(coordinator, chainId, requestId, block hash), then sign it with the BLS key
O->>K: fulfil(signature, request)
K->>V: verify(public key, seed, signature)
V-->>K: valid, random output = keccak256(signature)
K->>C: onRandomness(requestId, words)
K->>K: charge the actual cost (never above the reservation), credit the operator, release the reservation
O->>A: store(request block), so it can still be verified after 256 blocks
0.2 What happens when something goes wrong
flowchart TD
R["Request sent"] --> F["Fulfilled in time"]
F --> CB["onRandomness is called"]
F --> CBF["Callback fails (revert or out of gas)"]
CBF --> DV["Result is stored. Anyone can deliver it again with redeliver / retry"]
R --> TO["Not fulfilled within 100,000 blocks"]
TO --> CN["Request is cancelled. Your contract gets onRequestCancelled: void the round or refund"]
R --> MS["Operator does not fulfil within 8000 blocks"]
MS --> RP["Anyone can report it. After a 2-day dispute period part of the bond is slashed"]
Stores request block hashes (for later re-verification)
OperatorRegistry
0x01DA9bfe6b614f9497c97efE3C90Dfb172fB45Ca
Operator registration
Verifier
0x46F8c7579B6A299750341237bAaeA6fFbf7A2334
BLS signature verification
Official lane:0xfe6f6c68fa6c50e1569c6fe61d9637af93d04632c000c835d41464b41efef2d0
A lane identifies one oracle key (the keccak256 of its public key). You must specify a lane when you send a request. The Coordinator and PayPerRequest are upgradeable proxies, so always use the proxy addresses above.
2. Parameters and limits
Item
Value
Minimum confirmations
3 (you may use more, up to 200)
Random words per request
up to 500
Consumer contracts per subscription
up to 100
Callback gas limit
2,500,000
Request timeout (cancelled if unfulfilled)
100,000 blocks (about 12.5 hours at the current block time)
interface IRandomnessCoordinator {
function createSubscription() external returns (uint256 subId);
function fundSubscription(uint256 subId) external payable;
function addConsumer(uint256 subId, address consumer) external;
function cancelSubscription(uint256 subId, address payable to) external;
function request(bytes32 lane, uint256 subId, uint16 confirmations, uint32 callbackGas, uint32 numWords)
external returns (uint256 requestId);
function quote(bytes32 lane, uint32 callbackGas, uint32 numWords) external view returns (uint256);
}
interface IPayPerRequest {
function quote(uint32 callbackGas, uint32 numWords) external view returns (uint256);
function request(uint32 callbackGas, uint32 numWords) external payable returns (uint256 requestId);
}
Your contract must implement two callbacks (callable only by the Coordinator / PayPerRequest):
function onRandomness(uint256 requestId, uint256[] calldata words) external;
function onRequestCancelled(uint256 requestId) external; // optional; called when a timed-out request is cancelled
contract MyGame {
address constant COORDINATOR = 0x481044B907C40A8eF406691168064BCe8B3fb836;
bytes32 constant LANE = 0xfe6f6c68fa6c50e1569c6fe61d9637af93d04632c000c835d41464b41efef2d0;
uint256 public subId;
mapping(uint256 => address) public playerOf;
// 1. One-time setup: create a subscription, fund it, register this contract as a consumer
// (you can also do this from a wallet)
function setup() external payable {
IRandomnessCoordinator c = IRandomnessCoordinator(COORDINATOR);
subId = c.createSubscription();
c.fundSubscription{value: msg.value}(subId);
c.addConsumer(subId, address(this));
}
// 2. Send a request: 12 confirmations, 200,000 callback gas, 1 random word
function play() external {
uint256 id = IRandomnessCoordinator(COORDINATOR).request(LANE, subId, 12, 200_000, 1);
playerOf[id] = msg.sender;
}
// 3. Callback: only the Coordinator may call it
function onRandomness(uint256 requestId, uint256[] calldata words) external {
require(msg.sender == COORDINATOR, "only coordinator");
// use words[0]; do not revert; do not write a lot of storage here
}
function onRequestCancelled(uint256 requestId) external {
require(msg.sender == COORDINATOR, "only coordinator");
// The request timed out and was cancelled: void this round / refund. Do NOT request again here.
}
}
The example is simplified to show the flow and omits access control; add your own access control to setup, withdrawals and similar functions.
Any address can create and fund a subscription; the creator is the subscription owner. When you no longer need it, the owner calls cancelSubscription to withdraw the balance (not possible while requests are pending).
3.3 Option 2: Pay-per-request (occasional use, no subscription to manage)
address constant PPR = 0x72AA07A2c1852F6EdB1Ee068ca1Af74444A8A5Ac;
function play() external payable {
uint256 price = IPayPerRequest(PPR).quote(200_000, 1); // callback gas, number of random words
uint256 id = IPayPerRequest(PPR).request{value: price}(200_000, 1); // any overpayment is refunded immediately
}
// The random numbers are forwarded to the calling contract's onRandomness(requestId, words)
If the callback fails, the random numbers are stored and can be delivered again with PayPerRequest’s retry(requestId). They are not lost.
Pay-per-request path
flowchart LR
U["Your contract"] -->|"request with BNB attached"| P["PayPerRequest"]
P -->|"funds its own subscription and sends the request"| K["Coordinator"]
K -->|"after fulfilment: onRandomness"| P
P -->|"forwards the result: onRandomness"| U
P -.->|"refunds any overpayment"| U
4. Fees
Subscription: when you send a request, the worst-case cost at the lane’s maximum gas price is reserved (not charged). On fulfilment you are charged the actual cost, never more than the reservation; the rest stays in the subscription.
Charge = actual gas cost × (1 + premium) + flat fee
Pay-per-request: price = Coordinator quote × (1 + markup); any overpayment is refunded immediately.
Rates
Item
Value
Notes
Premium
10%
Added on top of the actual gas cost
Flat fee
0.001 BNB
Charged once per fulfilment
Pay-per-request markup
10%
Pay-per-request only, added on top of the Coordinator quote
Read on chain (the chain is authoritative):
Premium premiumBps and flat fee flatFee: Coordinator.settings()
Markup markupBps: PayPerRequest.markupBps()
Quotes and balance checks:
Coordinator.quote(lane, callbackGas, numWords): how much one request reserves
PayPerRequest.quote(callbackGas, numWords): the pay-per-request price at the current gas price
Reader.affordable(subId, lane, callbackGas, numWords): how many more requests the subscription can afford
Reader.shortfall(subId, lane, callbackGas, numWords, n): how many wei short you are to send n requests
A larger callback gas limit, more random words and a higher gas price all increase the cost.
5. Callback rules and safe usage
Do not revert in the callback and do not exceed the callbackGas you requested. Otherwise the delivery is recorded as failed and must be delivered again.
Do not write a lot of storage in the callback. Store a seed or a result digest and recompute the rest in view functions.
Lock the relevant state between sending the request and receiving the callback. Do not let users decide whether to take part after they have seen the result.
For high-value draws, use 12 or more confirmations (protection against chain reorganisations).
A timed-out request is cancelled and onRequestCancelled is called. Void the round or refund there. Do not request again; that would re-roll with a new seed.
You may send new requests from inside the callback (consecutive draws).
6. Verifying afterwards
Anyone can call Reader.verifyFulfilment(lane, requestId, blockNumber, numWords, sig) to recompute and check a random number. After each fulfilment the node stores the request block hash in HeaderArchive, so requests older than 256 blocks can still be verified.
7. Common errors
Symptom
Cause and fix
Underfunded
The subscription’s available balance is below the reservation. Top up, or use Reader.shortfall to compute the gap
Underpaid
Pay-per-request: msg.value is below the quote. Call quote first
Callback not triggered
Check the DeliveryFailed event. Subscription mode: anyone can call redeliver. Pay-per-request: call retry
Request not fulfilled for a long time
After the timeout (100,000 blocks) it is cancelled and your onRequestCancelled is called
Callback rejected
The callback only accepts calls from the Coordinator / PayPerRequest
8. Operator guide (run an oracle node)
8.1 Overview and admission
Any team can apply to become an operator, run its own oracle node and earn a share of the service fees. Your node holds one BLS key and produces a unique signature for each request; the Coordinator verifies the signature on chain and then calls the consumer contract. The private key never goes on chain and is never shared.
Admission: submit your public key and proof of possession, post the bond, and wait for approval.
Bond: minimum 2 BNB, returned when you exit (minus any slashing).
Earnings: 70% of the service fee (default, up to 90%) plus the gas compensation for fulfilment.
Operator lifecycle
stateDiagram-v2
[*] --> Pending: applyOperator + bond (2 BNB)
Pending --> Active: approved
Active --> Suspended: 3 penalties within 7 days
Suspended --> Active: bond topped up and reinstated
Active --> Exiting: requestExit
Exiting --> [*]: withdraw after the 14-day unbonding period
8.2 Checklist
Item
Recommendation
Server
Linux, 1 CPU core / 1 GB RAM / 10 GB disk is enough; Docker installed; always on
RPC
At least 2 different providers, both must support getLogs (public nodes usually do not); keep GETLOGS_RANGE within the provider’s per-call limit (commonly 5000)
BLS key
Generated locally, stored encrypted, never put on chain, never shared
Hot wallet
A separate, independent key used only to send fulfilment transactions; start with 0.1 BNB, top up when it falls below 0.01 BNB (gas is compensated by the protocol, but you front it)
Admin address
The address used to apply and to withdraw the bond (a hardware wallet or multisig works); different from the hot wallet and the BLS key
Bond
2 BNB
The two keys (BLS key and hot wallet) must be different; the node checks this at startup.
8.3 Download and verify the node software
Download vrf-oracle-<version>.tar.gz and SHA256SUMS from this repository’s Releases.
Verify integrity (in the directory containing both files):
tar xzf vrf-oracle-1.1.0.tar.gz
sha256sum -c SHA256SUMS # macOS: shasum -a 256 -c SHA256SUMS
Build the image:
cd vrf-oracle-1.1.0
docker build -t vrf-oracle:1.1.0 .
The image contains no keys; keys, passwords and RPC URLs are provided at run time. Run the following commands in your working directory (for example ~/vrf).
8.4 Generate keys and apply
Step 1: generate the BLS key (the password is typed in the terminal, at least 12 characters, not echoed; the private key exists only in the encrypted file)
By default it only prints the call data (applyOperator(pk, pop) with 2 BNB attached) and sends nothing. We recommend sending the transaction from your admin address’s wallet (hardware wallet or multisig): to = the registry address, value = 2 BNB, data = the printed call data. Alternatively, set ADMIN_KEY_FILE to a file holding the admin private key and add --send to send from the command line (--admin must match the address of that key).
Step 5: wait for approval. After you apply, the status is Pending. Once approved, the registry registers your lane on the Coordinator. Use the health check (see 8.5) to see the status.
8.5 Configure and run the node
Create node.env:
RPC_URLS=https://your-rpc-1,https://your-rpc-2
COORDINATOR=0x481044B907C40A8eF406691168064BCe8B3fb836
EXPECT_CHAIN_ID=56
EXPECTED_LANE=<the lane from step 3>
GETLOGS_RANGE=5000
POLL_MS=5000
TX_KEY_FILE=/run/secrets/tx_key
ORACLE_KEYSTORE=/keys/oracle.keystore
ORACLE_KEYSTORE_PASSWORD_FILE=/run/secrets/ks_password
Run the health check before starting (do not start if anything FAILs):
docker run --rm -it --env-file node.env \
-v "$PWD/keys:/keys:ro" -v "$PWD/ks_password:/run/secrets/ks_password:ro" -v "$PWD/tx_key:/run/secrets/tx_key:ro" \
--entrypoint node vrf-oracle:1.1.0 opcli.mjs doctor
The health check covers: RPC connectivity, getLogs availability, the Coordinator, hot-wallet balance, lane and public key consistency, the archive contract, and the registry status (Pending / Active). Start only when the registry status is Active and all checks pass.
docker ps --filter name=vrf-oracle # STATUS should be healthy
docker logs --tail 20 vrf-oracle # you should see: node up, lane ...
The node refreshes its cursor file (in the vrf-state volume) for every new block and resumes from the last position after a restart, so no requests are missed. After each fulfilment it stores the request block hash in HeaderArchive for later verification.
8.6 Monitoring and alerts
The same image includes a read-only monitor (no keys). Create monitor.env:
It raises an alert when: the hot-wallet balance drops below NODE_MIN_BALANCE_WEI (0.01 BNB), a request stays unfulfilled for more than PENDING_ALERT_BLOCKS blocks, or the lane is disabled or contract state looks abnormal. Alerts are written to the log (docker logs vrf-monitor; lines with level=alert need action). If you set ALERT_WEBHOOK, alerts are also pushed there as a JSON POST (fields: source, name, level, ev, ts, text, detail; text is a one-line summary, so you can forward it to Telegram, Slack, WeCom and similar).
8.7 Day-to-day operations
Stay online. A request that is still unfulfilled more than 8000 blocks (about 1 hour at the current block time) after it becomes ready can be reported and slashed (see 8.9). Keep the node running with --restart unless-stopped, and keep any upgrade or migration downtime under 10 minutes.
Upgrade the node:
Download the new release, verify SHA256SUMS, and run docker build -t vrf-oracle:<new-version> .
docker stop vrf-oracle && docker rm vrf-oracle
Start the new image with the same options and the same vrf-state volume; the cursor carries over.
Hot-wallet balance. Top up when it falls below 0.01 BNB; do not wait until it cannot send transactions.
RPC. Use at least two providers and watch free-tier quotas (a 3000–5000 ms poll interval is enough; a shorter interval burns quota quickly).
Backups. Keep offline backups of keys/oracle.keystore and the password file. Losing the BLS key means that lane can no longer serve; you would need to generate a new key and apply again.
Replacing the hot wallet. Update the tx_key file and recreate the container. The lane is unaffected.
8.8 Earnings and withdrawal
On each fulfilment: service fee = amount charged − gas compensation, and your share = service fee × share ratio (default 70%). The share is credited to your payout address as credits; the gas compensation is credited to the address that submitted the fulfilment transaction (the hot wallet).
Withdraw by calling Coordinator.claimCredits(to) from the corresponding address, for example from that wallet on BscScan’s Write Contract page.
The share ratio is configured per lane; changes are not retroactive.
8.9 Obligations and slashing
Item
Value
Minimum bond
2 BNB
Counted as missed
Not fulfilled more than 8000 blocks (about 1 hour at the current block time) after the request is ready; anyone may report
Penalty per incident
0.1 BNB
Minimum gap between two penalties for one operator
1 hour (one incident is penalised once)
Slashing cap
Within a rolling 7 days, at most 20% of the bond
Dispute period
2 days (the arbiter may veto; after it ends anyone can execute the slash)
Automatic suspension
3 penalties within 7 days
Unbonding period
14 days (starts when you request exit; then you can withdraw)
Lane maximum gas price
Range 0.1 to 2 gwei; a new lane defaults to 1 gwei
Slashed funds do not go to the protocol; they are sent to the burn address.
Only requests whose block hash is available are penalised (last 256 blocks, or archived). A request that could not be fulfilled because a node was offline too long is not penalised.
After a suspension, top up the bond (topUp(id)) and the approver reinstates you.
The values above follow OperatorRegistry.params() on chain.
8.10 Exiting
Call OperatorRegistry.requestExit(id) from the admin address (look up id with opOfLane(lane)). From then on no new requests are accepted.
Wait for the unbonding period (14 days). The bond can still be reduced by pending slashes.
When the period ends, call OperatorRegistry.withdraw(id, to) to recover the bond.
Before exiting, let the node finish its in-flight requests, then stop it.
9. Limitations
BNB Smart Chain mainnet only; payment in BNB only.
The interface is not compatible with Chainlink; existing Chainlink contracts must be adapted to the interface above.
A single operator can refuse to fulfil. A request that times out is cancelled and your contract is notified, so it never fails silently. If your application cannot tolerate delayed randomness, do not depend on a single lane.
You may use, modify, sell and redistribute them freely, as long as you keep the copyright and license notices.
The software and documentation are provided “as is”, without warranty of any kind, express or implied. You use the service and the software at your own risk.
The node’s third-party dependencies (ethers, @noble/curves) are each under their own MIT licenses.
The contract addresses listed here are public information on BNB Smart Chain mainnet.
评论