The original text is from Pavel Naydanov
Translation | Odaily Planet Daily Golem (@web3golem)_
Editor’s note: Polymarket has gained more attention in this U.S. election, not only because the cumulative trading volume of predicted topics has exceeded $3.6 billion, but also because it successfully predicted Trump’s victory ahead of polls and traditional media, making people more aware that Polymarket is not just a betting site, but will become a more real and reliable "news site" (recommended reading: 《Vitalik's new article: From prediction markets to information finance》). Polymarket may be the most striking "scenery" in this round of blockchain innovation.
So, how is Polymarket, which has revolutionary significance in "blockchain," technically implemented? Smart contract developer Pavel Naydanov has detailed the technology used by Polymarket, providing insights for developers (especially newcomers building prediction markets). Odaily Planet Daily has compiled the technical implementation parts as follows; let’s delve into the technical details of the protocol.
CTF: Tokenizing Results
All event outcomes on Polymarket are tokenized:
Such tokens can be called Share tokens;
Shares are purchased with underlying assets, so they are fully collateralized;
Shares can be sold to obtain the underlying assets.
Share tokens are implemented as ERC-1155 based on the Gnosis Conditional Token Framework (CTF), which has proven its effectiveness and has been tested by various protocols. CTF can support up to 256 outcomes per event.
Each prediction is identified in CTF, for which they are assigned a unique condition ID, composed of the hash of three parameters:
Oracle: The address of the oracle that will determine the event outcome, ensuring that only the specified oracle can settle the prediction;
Question ID: The identifier for the prediction, set by the creator of the prediction question. This can be a simple counter that increments with each new prediction or a more complex scheme using text and other data hashes;
outcomeSlotCount: The number of possible outcomes for the prediction.
The following diagram visually demonstrates how CTF (Conditional Token Framework) works:
When users place bets, they provide underlying assets and receive Share tokens, referred to as conditional tokens in CTF. After the oracle determines the prediction, users can claim rewards from CTF based on the prediction outcome.
When users receive conditional tokens, they are considered to have determined a specific position. In CTF, a position represents a set of possible outcome combinations for each prediction. CTF generates these positions for each prediction, with each position corresponding to one of the possible outcome combinations that users can choose.
For example:
What will be the highest-grossing movie of 2024?
Inside Out 2
Deadpool 3
Joker 2
Despicable Me 4
Dune 2
Mad Max 4
Other
Users can vote that "Inside Out 2" will be the highest-grossing movie, or that "Dune 2" will definitely not be the highest-grossing movie of 2024. This combination of predictions will be considered their position.
CTF provides two interesting mechanisms for handling positions: splitting and merging. The splitting mechanism allows a single position to be divided into multiple separate outcomes, while merging combines different outcomes into one position. These mechanisms enable users to flexibly manage their positions.
CTF offers four significant advantages for Polymarket:
Share tokens can be used to confirm users' votes on specific prediction outcomes;
A flexible system is implemented to combine users' votes into various positions;
The responsibility for calculating outcomes based on oracle signals is delegated to CTF;
Rewards are calculated based on the number of Share tokens for the winning outcome.
It is also worth mentioning that CTF allows for the organization of related activities where users' positions can be merged. However, there are currently no such examples on Polymarket. For more information about CTF, you can refer to the official documentation.
Order Mechanism
To make purchases, the Polymarket interface offers three types of orders:
Market — buy immediately at the current market price;
Limit — delayed orders that allow you to specify a price at which to buy once that price is reached;
AMM — buy at a price automatically determined similarly to a decentralized exchange, based on the reserve amount in the pool.
Currently, the AMM order functionality seems to be inactive, as no predictions allowing purchases through AMM have been found. A comment from a user in Polymarket's Discord somewhat explains this situation.
AMM is outdated
According to Polymarket's documentation, AMM was developed as part of the Conditional Token Framework smart contracts. Therefore, AMM is used to determine the purchase price of Share tokens. This fundamental mechanism requires liquidity to ensure stable pricing and reduce volatility. Liquidity providers need economic incentives, receiving rewards from each purchase to keep the system running.
Initially, Polymarket may have been entirely based on CTF, using AMM to determine prices. However, over time, the protocol developed a hybrid solution with an order book, and the other two types of orders (limit and market) began to operate on this customized solution. This solution is referred to as CLOB (Central Limit Order Book) or BLOB (Binary Limit Order Book).
CLOB and BLOB
CLOB (Central Limit Order Book) or BLOB (Binary Limit Order Book) is a system representing a hybrid decentralized order book. In this system, dedicated operators are responsible for handling order matching and initiating the execution of smart contracts.
Without further ado, the system is illustrated in the following diagram:
Users create orders to be executed, which can be limit orders or market orders; operators match user orders and initiate execution on the smart contract. Creating an order means creating a data structure signed with the user's private key according to the EIP-712 standard. Since orders are stored off-chain before execution, the terms of the orders can be quickly and freely adjusted or even completely canceled.
However, everything related to the order book and order matching can only be accessed via API. For convenience, Polymarket provides two clients: one using JavaScript and one using Python.
However, the Exchange.sol smart contract is public and is responsible for creating user positions in CTF. It also allows for the management of user positions and the transfer of assets between them, ensuring security and transparency within the protocol.
This smart contract has been audited, and the audit report is attached to the repository.
Smart Contract
The Exchange smart contract actually has a more specific name, which is CTFExchange.sol. It is not very large, with only about 100 lines of code, but it does have a lot of dependencies.
Most of these are small smart contracts that implement limited functionality:
BaseExchange.sol: An abstract smart contract that implements the ability to receive ERC-1155 tokens and is also responsible for preventing reentrancy attacks;
Auth.sol: A role manager that defines validation functions and modifiers to set roles, including admin and operator for CTFExchange.sol;
Assets.sol: Defines two types of assets, the underlying asset (collateral) and the CTF address;
Fees.sol: Defines protocol fees;
Pausable.sol: Defines the ability to pause smart contract operations, a centralized form that the protocol agrees to adopt in unforeseen circumstances. This only applies to the admin role;
AssetOperation.sol: Defines operations for the underlying asset and CTF, including the transfer, splitting, and merging of positions;
Signature.sol: Defines the code used for user signatures when validating orders;
Hashing.sol: Defines the hash values of order parameters used for signature verification;
Registry.sol: Defines the process of registering predictions in the system and registering tokens for predictions.
All aspects related to the actual execution of orders are implemented in the smart contract Trading.sol. It is also straightforward to traverse the code and study the smart contract. The structure clearly defines entry points through functions:
fillOrder()— Executes an order between the user creating the order and the order selected by the user (another order);
fillOrders() — Similar to fillOrder(), but for a list of orders;
matchOrders()— The operator selects two different orders and executes them.
All of the above functions can only be called by the operator.
Regardless of how the call enters the smart contract, the result is always the same: two users will exchange tokens based on their orders.
Protocol Fees
Fees are charged based on the output assets. For binary predictions, the fees are symmetrical, meaning: if a user sells tokens at a price of $0.99, they will pay the same fee as the buyer who purchases tokens at a price of $0.01.
The calculation formula is simple, taken from the official documentation:
Liquidity Reward Program
The overall goal of the program is to incentivize market liquidity.
For an order book-based exchange to function, someone needs to create limit orders, which provide liquidity that allows market orders to be executed immediately. Users who create limit orders are called market makers. The "tightness" of limit orders relative to the market price determines how quickly market orders are executed and increases trading volume, which is undoubtedly beneficial for end users. Additionally, the greater the liquidity, the harder it is to manipulate the market.
To ensure sufficient liquidity, Polymarket has established a special reward program to incentivize users to create limit orders. The closer limit orders are to the average market price, the higher the rewards. Rewards will be automatically paid out at midnight (UTC time) each day.
This system is modeled after dYdX, and for more information, you can check the original dYdX's liquidity incentive program and Polymarket's detailed liquidity reward calculation formula.
Oracle
Oracles are used to provide prediction results—regardless of whether the event occurs. Oracles are one of the most important components of the protocol, but they are provided by a third-party service rather than the Polymarket team. This oracle is known as UMA.
UMA is a decentralized oracle specifically designed to record any type of data on the blockchain, except for unverifiable data. The oracle operates on an optimistic basis, meaning that data is assumed to be correct unless disputed. UMA has its own arbitration system to resolve disputes, where the arbitrators are real people—participants in the UMA ecosystem, particularly UMA token holders. This system is known as DVM (Data Verification Mechanism).
The following process is used to determine prediction results and record them on the blockchain:
Statement: Predictions are added to the oracle along with rewards. Anyone who successfully disputes the prediction outcome can claim the reward;
Challenge period: During this period, anyone can question the prediction result. If no challenges occur and the time expires, the prediction result is considered ready for final settlement, indicating its accuracy;
Dispute: Any participant in the protocol can dispute the result, whether to claim a reward or for fairness. In practice, this situation is rare, as game theory suggests that most participants behave honestly.
Voting: If a dispute is initiated, UMA token holders will vote to resolve the dispute. UMA is the protocol token used for voting, and participants earn rewards for participating in the vote.
Settlement: The final stage is the settlement process, where data is actually recorded on the blockchain. After this, the prediction result can be considered reliable.
The entire protocol is based on game theory, making it economically disadvantageous for any participant to act maliciously.
Participants submitting prediction results for voting provide collateral to the smart contract. If their results are disputed, they will lose their collateral; otherwise, they will reclaim their collateral and receive rewards. This creates a strong incentive to submit only accurate results.
Participants disputing prediction results also provide collateral. If they are correct, they will reclaim their collateral and receive rewards; otherwise, they will lose their collateral. This incentivizes participants to only challenge results they are confident are incorrect.
Participants resolving disputes must stake UMA tokens and will receive rewards for resolving disputes. If they vote incorrectly or do not vote at all, they will lose part of their staked balance; otherwise, they will receive rewards. There is no way to be negligent.
It is particularly noteworthy that the voting process in disputes is divided into two phases using a commit/reveal scheme:
Commit: Participants secretly vote by submitting the hash of their vote to the smart contract, meaning that no one can discern how participants voted just by looking at the hash.
Reveal: After the voting phase ends, participants reveal their votes, and the smart contract verifies whether they match the previously submitted hash.
This two-phase voting process prevents voters from colluding to undermine the oracle or attack services that rely on prediction results. At the same time, prediction results can be challenged multiple times, in which case UMA allows the decision-making process to restart after previous disputes are resolved.
The process for initiating a dispute is as follows:
Conclusion
The seemingly simple betting and prediction system of Polymarket actually consists of three main modules, each developed by different protocols and teams:
CTF (Conditional Token Framework): Manages combinations, positions, and shares in predictions. This flexible framework created by Gnosis is well-suited for prediction markets.
CLOB (Central Limit Order Book): An internal solution used by Polymarket to implement order books and limit orders. CLOB enables users to effectively participate in the ecosystem and helps aggregate liquidity.
UMA: A decentralized oracle with a unique dispute resolution arbitration system. UMA is the core of the system, transmitting prediction results via the blockchain.
While Polymarket is a betting system, technically, the protocol successfully combines technologies from different projects, making it particularly attractive to developers.
Related Reading
How long will the Polymarket and prediction market craze last after the U.S. elections?
How does Polymarket outperform traditional polls in elections?
免责声明:本文章仅代表作者个人观点,不代表本平台的立场和观点。本文章仅供信息分享,不构成对任何人的任何投资建议。用户与作者之间的任何争议,与本平台无关。如网页中刊载的文章或图片涉及侵权,请提供相关的权利证明和身份证明发送邮件到support@aicoin.com,本平台相关工作人员将会进行核查。