diff --git a/docs/dev/protocol/scaling/layer0.md b/docs/dev/protocol/scaling/layer0.md index 72eab7c1..9d4ef8fd 100644 --- a/docs/dev/protocol/scaling/layer0.md +++ b/docs/dev/protocol/scaling/layer0.md @@ -16,9 +16,9 @@ In the context of scaling, the type of client used can significantly impact the In addition to these, Ergo also supports **[Logarithmic space mining](logspace.md)**, which enables the existence of *light miners*. Similar to light clients, light miners can bootstrap using block headers without downloading the entire blockchain. This feature can be integrated into Ergo through a velvet (soft) fork, further enhancing the scalability of the network. -## Weak Blocks +## Sub Blocks -In the quest for Layer 0 (L0) scalability improvements, one of the most promising advancements is the introduction of "weak blocks." These are essentially block candidates with lower proof-of-work difficulty, serving as temporary placeholders that facilitate faster transaction confirmations and optimize network bandwidth. For end-users, this translates into quicker, weakly confirmed transactions—often within 20 seconds—while also making better use of network resources. For a more in-depth look at weak blocks, their advantages, and their role in Ergo's scalability strategy, see this [page](weak-blocks.md). +In the quest for Layer 0 (L0) scalability improvements, one of the most promising advancements is the introduction of "subblocks." These are essentially block candidates with lower proof-of-work difficulty, serving as temporary placeholders that facilitate faster transaction confirmations and optimize network bandwidth. For end-users, this translates into quicker, weakly confirmed transactions—often within 20 seconds—while also making better use of network resources. For a more in-depth look at weak blocks, their advantages, and their role in Ergo's scalability strategy, see this [page](sub-blocks.md). ## State Bloat Management diff --git a/docs/dev/protocol/scaling/layer1.md b/docs/dev/protocol/scaling/layer1.md index c6f4e2bc..4b67b2ba 100644 --- a/docs/dev/protocol/scaling/layer1.md +++ b/docs/dev/protocol/scaling/layer1.md @@ -4,29 +4,118 @@ tags: - Sub Block Confirmation Protocols - Microblocks --- - # Layer 1: On-chain Scalability in Ergo Layer 1, the foundational protocol layer of a blockchain system, is responsible for core functions such as transaction processing, consensus mechanisms, and security protocols. Ergo's Layer 1 is designed with a focus on scalability, incorporating features that boost transaction processing capacity and overall throughput. -## Mainnet 5.0 Activation and its Impact +## Current Scalability Features + +### Extended UTXO Model (EUTXO) +Ergo utilizes an enhanced version of Bitcoin's UTXO model, known as EUTXO, which enables: + +- Turing Complete smart contracts +- Parallel transaction processing +- Higher throughput compared to account-based models +- Efficient state management + +### Protocol Optimizations +Recent developments have improved the protocol's efficiency through: + +- Removal of unused complexity from the Sigma protocol +- Enhanced code readability and maintenance +- Refined transaction ordering and mempool tracking +- Regular node version updates addressing performance + +## Mainnet 5.0 and Beyond + +### Just-in-Time Costing +The introduction of [Just in time costing](jitc.md) in Node V5 has led to: -The introduction of the [*'Just in time costing'*](jitc.md) update in Node V5 has led to a substantial increase in Ergo's block capacity. This enhancement has amplified the network's transaction processing capability by an estimated 5-10 times. +- 5-10x increase in block capacity +- Improved transaction processing capability +- More efficient resource utilization + +### Miner Parameter Adjustments +Developers are actively exploring: + +- Increased block size parameters +- Enhanced transaction size limits +- Optimized mining efficiency +- Improved difficulty calculations through Autolykos updates ## Future Scalability Enhancements -Ergo's Layer 1 also sets the stage for potential scalability improvements through techniques such as Sharding, and the implementation of Sub-Block Confirmation Protocols and Microblocks. +### Microblocks and the Ergo Block Extension Section + +Ergo's [block](block.md) structure includes extension sections containing: + +- Mandatory and arbitrary key-value data +- Anchors for microblock creation +- Support for service chains +- Potential for generic sidechain implementation + +These features enable: + +- Faster block generation times +- Improved transaction throughput +- Support for velvet or soft forks +- Creation of Aspen-style service chains + + +### Sub-Block Confirmation Protocols + +Ergo is actively developing sub-block confirmation protocols that will: + +- Group transactions into sub-blocks +- Reduce confirmation times +- Increase overall throughput +- Improve transaction processing efficiency + +This development is guided by [EIP-15](link-to-eip-15) and builds upon established research from platforms like: + +- [Bitcoin-NG](https://www.usenix.org/system/files/conference/nsdi16/nsdi16-paper-eyal.pdf) +- [Flux](https://www.usenix.org/system/files/atc20-li-chenxing.pdf) + + + ### Sharding +Sharding represents a promising avenue for future scalability improvements by: + +- Partitioning the blockchain database into smaller segments +- Enabling parallel transaction processing +- Maintaining security while improving throughput + +For detailed information, refer to: + +- [On the Security and Performance of Blockchain Sharding](https://eprint.iacr.org/2021/1276) +- [Sharding and Atomic Composability on Ergo](../atomic-composability/#sharding-and-atomic-composability) + +## Community-Driven Development + +### Ergo Improvement Proposals (EIPs) +EIPs serve as the primary mechanism for protocol enhancement through: + +- Community-driven proposals +- Focused scalability improvements +- Systematic implementation processes +- Regular protocol updates -**Sharding** is a scalability technique that partitions the blockchain database into smaller segments, known as 'shards.' Each shard can process transactions and smart contracts independently, enabling parallel transaction processing and significantly boosting blockchain scalability. Although not currently integrated into Ergo, sharding is a promising area for future development. +### Node Version Updates +Regular updates to the Ergo node software provide: -For an in-depth understanding of sharding, refer to the paper [*' On the Security and Performance of Blockchain Sharding'*](https://eprint.iacr.org/2021/1276). For additional context, visit this page on [sharding and atomic composability on Ergo](../atomic-composability/#sharding-and-atomic-composability). +- Bug fixes and performance enhancements +- New scalability features +- Improved difficulty calculations +- Refined Autolykos implementation -### Sub-Block Confirmation Protocols and Microblocks +## Research and Development -Ergo's scalability is further augmented by its *extension sections* within blocks, which can contain **mandatory and arbitrary key-value data**. Specific anchors embedded in these sections facilitate the creation of microblocks, akin to the Bitcoin-NG model. Additionally, it opens up the possibility to generate Aspen-style service chains or generic sidechains through velvet or soft forks. +Ongoing research continues to explore: -Platforms such as [Bitcoin-NG](https://www.usenix.org/system/files/conference/nsdi16/nsdi16-paper-eyal.pdf) and [Flux](https://www.usenix.org/system/files/atc20-li-chenxing.pdf) demonstrate Microblocks and Sub-block confirmation protocols. By utilizing Ergo's *extension sections*, these strategies can markedly enhance the blockchain's throughput. Microblocks enable faster block generation times, thereby improving transaction throughput. +- Advanced sharding techniques +- Novel consensus mechanisms +- Improved transaction ordering +- Enhanced mempool management -These topics continue to be the focus of intense research as of 2023. For a comprehensive understanding, refer to the paper *[Flux: Revisiting Near Blocks for Proof-of-Work Blockchains](https://eprint.iacr.org/2018/415.pdf)*. +For the latest developments in these areas, refer to [Flux: Revisiting Near Blocks for Proof-of-Work Blockchains](https://eprint.iacr.org/2018/415.pdf). \ No newline at end of file diff --git a/docs/dev/protocol/scaling/layer2.md b/docs/dev/protocol/scaling/layer2.md index 18d9fcb7..b30ed3cf 100644 --- a/docs/dev/protocol/scaling/layer2.md +++ b/docs/dev/protocol/scaling/layer2.md @@ -1,20 +1,16 @@ --- tags: - - Plasma - - NIPoPoWs - - Lightning - - Rollups - - Hydra +- Layer 2 +- Scaling +- Sidechains +- Off-chain Solutions +- Sigma Chains --- - - # Layer 2: Off-Chain Layer 2 solutions are secondary frameworks or protocols constructed on top of a [Layer 1](layer1.md) blockchain protocol. Their purpose is to enhance the efficiency, scalability, and capabilities of the underlying blockchain by facilitating *off-chain* transactions or computations. -Ergo is compatible with a broad range of Layer 2 solutions derived from other UTXO blockchains, such as Bitcoin's Lightning Network. Ergo can also implement various off-chain solutions like [Hydra](https://iohk.io/en/research/library/papers/hydrafast-isomorphic-state-channels/) and sidechains, which help alleviate blockchain congestion and offer benefits akin to ZK-rollups. - -The integration of specific Layer 2 solutions into Ergo is determined by the requirements of the applications being developed. +Ergo is compatible with a broad range of Layer 2 solutions derived from other UTXO blockchains. The platform can implement various off-chain solutions like [Hydra](https://iohk.io/en/research/library/papers/hydrafast-isomorphic-state-channels/) and sidechains, which help alleviate blockchain congestion and offer benefits akin to ZK-rollups. > Join the Layer 2 discussion on [Telegram](https://t.me/ErgoLayer2) or [Discord](). @@ -24,74 +20,114 @@ The integration of specific Layer 2 solutions into Ergo is determined by the req ErgoScript features several advancements like time-weighted data, Turing completeness, read-only data inputs, multi-stage contracts, sigma protocols, NIPoPoWs, and more. These enhancements enable a variety of Layer 2 protocols, each addressing scalability issues in their unique way. -> **Ergo can thus be considered a shared *settlement layer* for multiple Level-2 protocols and applications.** +> **Ergo serves as a settlement layer for multiple Layer 2 protocols and applications.** -## Plasma: Enhancing Data Structures +## Current Layer 2 Projects and Developments -Ergo inherently supports [AVL trees](avl.md), an efficient authenticated data structure that allows for proving different properties of the data without accessing the entire dataset. +### Layer 2 Solutions Leveraging Sub-Blocks +While sub-blocks are a Layer 1 protocol enhancement, they enable several Layer 2 scaling solutions: -The ledger is maintained as an AVL tree using **[Plasma](plasma.md)**. Users conduct off-chain transactions with the bank, resulting in changes in the ledger. The bank periodically publishes a compact snapshot of the ledger on the blockchain. +- Faster confirmation times for Layer 2 protocols +- Enhanced support for payment channels +- More efficient state channel operations +- Improved settlement layer for off-chain transactions -The [Plasma Library](plasma.md) can be used to build *Plasma chains*, leading to a comprehensive L2 solution. Currently, it's mainly used for data compression and contract simplification, but the development of Plasma chains is a promising future prospect. +Layer 2 protocols can utilize sub-blocks to: -## NIPoPoWs: Facilitating Scalability - -[NiPoPoWs](nipopows.md) offer significant scalability potential by enabling the interoperability of various blockchain networks. This capability can alleviate the load on individual chains by distributing it across multiple networks, thus enhancing overall network efficiency and scalability. - -### Enhanced Security through Interoperability +- Group off-chain transactions more efficiently +- Reduce settlement times +- Increase throughput for Layer 2 applications +- Enable more responsive user experiences -One practical application of NIPoPoWs involves smaller, less secure blockchains leveraging the security of larger, more established chains. For example, a minor blockchain could periodically submit proofs of work to a larger chain, effectively anchoring their blockchain to the larger network. This anchoring process utilizes the security and computational power of the larger chain to enhance the integrity and trustworthiness of the smaller chain. +### SigmaChains and Sidechains +SigmaChains leverage Ergo's Sigma contracts to create versatile sidechains that can operate as either merge-mined sidechains or standalone blockchains. Key features include: -This approach not only boosts the security of the smaller chain but also enables seamless asset transfers between chains without requiring a centralized intermediary. By utilizing NIPoPoWs, these transfers maintain cryptographic proof of their legitimacy, ensuring that both chains recognize the validity of the transaction. +- Enhanced scalability and privacy features +- Experimental platform for new features +- Various chain commitment options for main chain security +- Comprehensive technical documentation in "Sigma Deck 2" -### Scalability of Layer 2 Solutions +### ChainCash +ChainCash is developing a decentralized, peer-to-peer monetary system using Layer 2 derivative signature chains. The project features: -NIPoPoWs could further improve the scalability of Layer 2 solutions like sidechains or state channels. By providing a robust method for these technologies to communicate more securely and efficiently, NIPoPoWs help to offload transactions from the main blockchain. This reduces congestion and increases transaction throughput, addressing one of the primary challenges facing blockchain scalability today. +- Elastic money creation capabilities +- Digital notes representing various values +- Support for digital tokens and real-world assets +- Implementation of top-up transactions and blockchain scanning -#### Applications in Layer 2 Technologies: - -- **Sidechains**: NIPoPoWs enable sidechains to operate more autonomously from the main chain while still maintaining a connection secured by proof-of-work. This is particularly useful for applications requiring faster processing times or handling specialized transactions. -- **State Channels**: By securing state channels with NIPoPoWs, transactions can be processed off the main chain with assurances of their eventual consistency and integrity when reconciled on the main chain. - -### The Role of NIPoPoWs in Cross-Chain Communications +## Plasma: Enhancing Data Structures -NIPoPoWs facilitate not just asset transfers but also a variety of cross-chain interactions, from smart contract executions to consolidated data verification across networks. This interoperability is key to realizing a fully integrated blockchain ecosystem where different platforms can share capabilities and enhance each other's functionality without compromising on security. +Ergo inherently supports [AVL trees](avl.md), an efficient authenticated data structure that allows for proving different properties of the data without accessing the entire dataset. -By leveraging NIPoPoWs, blockchain networks can achieve higher scalability, enhanced security, and increased efficiency, making blockchain technology more practical and accessible for a broader range of applications. +The ledger is maintained as an AVL tree using **Plasma**. Users conduct off-chain transactions with the bank, resulting in changes in the ledger. The bank periodically publishes a compact snapshot of the ledger on the blockchain. -## Emerging Layer 2 Solutions +The [Plasma Library](plasma.md) enables the building of Plasma chains, currently used primarily for: -There are several Layer 2 solutions currently under development that show great promise: +- Data compression +- Contract simplification +- Plasma staking contracts +- Off-chain operation management -### **Lightning Network** +## NIPoPoWs: Facilitating Scalability -The Lightning Network is a Layer 2 protocol that operates by allowing two participants to pool their funds into a specific type of joint multi-signature wallet. This wallet facilitates the creation and enforcement of off-chain agreements. The network is composed of these interconnected channels, enabling off-chain payments to be routed across multiple channels, akin to an abacus. +[NiPoPoWs](nipopows.md) enhance blockchain interoperability and scalability through: -### **Rainbow Network** +### Enhanced Security through Interoperability +- Smaller chains can leverage security of larger networks +- Periodic proof-of-work submissions between chains +- Cryptographically secure asset transfers +- Enables seamless asset transfers without centralized intermediaries + +### Cross-Chain Communications +- Facilitates smart contract executions across networks +- Enables consolidated data verification +- Supports integrated blockchain ecosystems +- Improves scalability of Layer 2 solutions like sidechains + +### Applications in Layer 2 Technologies +- **Sidechains**: NIPoPoWs enable sidechains to operate more autonomously while maintaining security +- **State Channels**: Transactions can be processed off-chain with assurances of eventual consistency +- **Cross-Chain Verification**: Enables efficient verification of transactions across different chains +- **Security Enhancement**: Smaller chains can leverage the security of larger networks -The Rainbow Network is an off-chain, non-custodial exchange and payment network that supports any assets for which two parties can agree on a price oracle. It enables users to trade, borrow, lend, and make payments in synthetic assets entirely off-chain, even though they only have one on-chain payment channel collateralized by a single asset. For more details, refer to [this paper](http://research.paradigm.xyz/RainbowNetwork.pdf). +## Emerging Layer 2 Solutions -### **Rollups** +### Lightning Network -Rollups are a Layer 2 solution that could be implemented on Ergo using [AVL trees](avl.md). They involve bundling groups of transactions together, with the primary focus being on data posting on-chain, rather than verification. +The Lightning Network creates payment channels through multi-signature wallets, enabling off-chain transactions between participants. -There are two primary types of *Rollups* used for scaling: +### Rainbow Network +A non-custodial exchange and payment network supporting multiple assets through price oracles, enabling off-chain trading, borrowing, and lending. -- **Optimistic Rollups** operate by handling transactions on a parallel chain that is compatible with the main chain. This model is termed 'optimistic' because it relies on the *Fraud-Proof principle*, where aggregators do not actively verify Layer 2, but intervene in case of fraud disputes. For more information, refer to this [ergoforum](https://www.ergoforum.org/t/optimistic-rollups-and-fraud-proofs-in-ergo/3819) post. -- **ZK-Rollups** utilize [zkSNARKs](https://blog.ethereum.org/2016/12/05/zksnarks-in-a-nutshell/) (zero-knowledge succinct non-interactive arguments of knowledge) to reduce network load by bundling hundreds of transfers off-chain into a single transaction. While their implementation is more complex than hybrid approaches, many projects are exploring this direction. +### Rollups +Two primary types of rollups are being explored: -### **Hydra** +- **Optimistic Rollups**: Handle transactions on parallel chains using fraud-proof principles +- **ZK-Rollups**: Utilize zkSNARKs to bundle hundreds of transfers off-chain -Hydra, a form of **State Channels**, employs a *peer-to-peer signing model* that is particularly effective for simple applications such as payment channels. One of its limitations is that it requires the participants to be predefined at the time of channel creation, necessitating a new contract for each new participant. While this model provides high levels of privacy and security, it lacks flexibility for open systems. To address this, IOHK introduced [Hydra: Isomorphic State Channels](https://iohk.io/en/research/library/papers/hydrafast-isomorphic-state-channels/), a solution that leverages both on-chain and off-chain computations, powered by the eUTXO design, to facilitate multi-party state channels. This approach opens up possibilities for other innovative state channel constructions, which could be utilized in tools like ErgoMixer. +### Additional Solutions +- **Hydra**: Implements isomorphic state channels for multi-party transactions +- **Zero-Knowledge Contingent Payments**: Enable trustless knowledge-based payments +- **FairSwap/FastSwap protocols**: Provide secure and efficient transaction methods +- **Coinpools**: Group transactions for improved efficiency -### **Zero-Knowledge Contingent Payments** +## Development Considerations -Zero-Knowledge Contingent Payments are designed to be released only when the payee discloses specific knowledge in a trustless manner, ensuring that neither the payer nor the payee can cheat. This is achieved through a combination of a `hash-locked transaction` and an external protocol that verifies the correct data is revealed when the hash lock is released. +### Security and Consensus +- Careful evaluation of security implications for new Layer 2 solutions +- Selection of appropriate consensus mechanisms for different applications +- Implementation of robust fraud prevention measures -### **FairSwap/FastSwap protocols** +### User Experience +- Development of mempool chaining for immediate transaction feedback +- Focus on seamless integration between Layer 1 and Layer 2 solutions +- Optimization of transaction processing and confirmation times -The FairSwap and FastSwap protocols are Layer 2 solutions that provide secure and efficient transaction methods. Detailed information about these protocols can be found in [this paper](https://eprint.iacr.org/2019/1296). +### Research and Development +Ongoing research continues to explore: -### **Coinpools** +- Advanced sharding techniques +- Novel consensus mechanisms +- Improved transaction ordering +- Enhanced mempool management -Coinpools represent another potential Layer 2 solution for the UTXO model. They offer a method for grouping transactions to improve efficiency and scalability. More information about Coinpools can be found in [this paper](https://discrete-blog.github.io/coinpool/). diff --git a/docs/dev/protocol/tx/babel-fees.md b/docs/dev/protocol/tx/babel-fees.md index 55b0495d..2010f40e 100644 --- a/docs/dev/protocol/tx/babel-fees.md +++ b/docs/dev/protocol/tx/babel-fees.md @@ -1,155 +1,77 @@ # Babel Fees -> From [EIP-31](https://github.com/ergoplatform/eips/blob/6fb344914b98f81117910ae7f486533f0db6fea9/eip-0031.md) -The term “babel fees“ refers to the concept of paying transaction fees in tokens (fe. stablecoins) instead of the platform’s primary token (ERG). For more information about the origin of the term and concepts behind “babel fees“, please see the following articles: +Babel fees (introduced via [EIP-0031](https://github.com/ergoplatform/eips/blob/master/eip-0031.md)) allow users to pay transaction fees in tokens other than the platform's primary token (ERG). This system is particularly helpful for users primarily interested in transferring tokens without needing to obtain ERG. - * [Babel fees - denominating transaction costs in native tokens](https://iohk.io/en/blog/posts/2021/02/25/babel-fees/) - * [Paying fee in ErgoMix in primary tokens](https://www.ergoforum.org/t/paying-fee-in-ergomix-in-primary-tokens/73) +/// details | How Babel Fees Work on Ergo + {type: info, open: false} +On Ergo, Babel fee payments are facilitated through pre-defined Babel Fee pools, offering a predictable and transparent fee payment process. This system differs from Cardano's approach, where users broadcast incomplete transactions and wait for a third party to pay fees in ADA in exchange for the offered tokens. -EIP-0031 aims to provide the standard for paying fees in tokens and thus has the same goal as Cardano’s “babel fees“; however, it chooses a different approach, with the main difference being that EIP-0031 does not require any forking. +Here's how Babel fees work: -With Cardano’s approach, the user publishes an “invalid"(incomplete) transaction and has to wait, hoping that somebody will take his tokens and pay the transaction fees in a primary token (ADA), therefore completing the transaction. EIP-0031, on the other hand, chooses the opposite approach. +1. **EIP-31 Supporters Provide Liquidity:** -> **On Cardano**, you will send an “incomplete” transaction, offering to pay the fee using x amount of tokens and wait until a third party accepts your tokens in exchange for ADA to pay the fees. -> -> **On Ergo**, we have pre-defined Babel Fee pools, so there is no waiting, and we can know in advance what tokens we can use to pay fees and the best price available. - - -Supporters wishing to make money from EIP-0031 will publish UTXOs, containing primary tokens locked by a smart contract. These will contain price attributes (i.e. how much of the primary tokens is that one specific supporter is willing to pay for one piece of user’s tokens (i,e. stablecoins)). Let us call this user’s token a “babel token”. - -The user willing to pay the transaction fee in babel tokens can now find whether any UTXOs belonging to the P2S address specified by the corresponding smart contract for that specific babel token exist. If any UTXO contains enough primary tokens for required fees, the user can calculate the price of buying the required amount of primary tokens from this UTXO and then decide whether or not he wishes to use it. If he accepts this exchange ratio (defined by the UTXO’s price attribute), he can consequently spend this UTXO in his transaction to cover the transaction fees. This spending user now has to recreate the UTXO with the same parameters and insert the required amount of babel tokens into it (primary tokens difference should be less or equal to inserted babel tokens amount times price), which is going to be ensured by the smart contract. - -A strong advantage of this approach (compared to Cardano’s one) is that the user always knows in advance whether there is an opportunity to pay via “babel fees” or not and, if there is, what is the exchange ratio. He can be (almost) certain that if he decides to use it, his transaction will be included in the blockchain ledger. Be aware, however, that there exist some exceptions to this rule, which is later discussed in the “Wallets implementation” section. - -Motivation --------------------------------------------- - -Many users use blockchain solely for transferring (native)tokens, such as stablecoins or even “meme” coins. These users, understandably, do not want to be bothered with keeping an eye on the amount of blockchain’s primary token they own or even obtaining this primary token in the first place. - -Once they run out of primary tokens, they have to, difficultly (and often costly) swap their tokens of interest for the primary tokens they can later use to cover transaction fees. Since primary tokens are also needed for these swaps, users may be forced to introduce new capital to their portfolio solely to purchase primary tokens used for fee-paying. - -Since basic transactional fees on the Ergo blockchain are generally quite low, the "babel fees" users would probably be willing to pay a fee that could be higher than that of a primary token transaction in exchange for being able to pay in their token of interest and not having to bother with the blockchain’s primary token purchase. - -This brings up a financial incentive for “EIP-0031 supporters”, who could benefit from this arbitrage by providing liquidity for such “babel fees” users, with the primary token’s selling price (expressed in tokens of interest) being higher compared to the same token pair on the exchanges. - -Smart contract specification --------------------------------------------- -Here is the smart contract's source code in ErgoScript which will be used to protect the babel fee box: -```scala -{ - - // ===== Contract Information ===== // - // Name: EIP-0031 Babel Fees Contract - // Description: Contract guarding the babel fee box, checking if the valid output babel box was recreated and the token exchange was valid. - // Version: 1.0.0 - - // ===== Relevant Variables ===== // - val babelFeeBoxCreator: SigmaProp = SELF.R4[SigmaProp].get - val ergPricePerToken: Long = SELF.R5[Long].get - val tokenId: Coll[Byte] = _tokenId - val recreatedBabelBoxIndex: Option[Int] = getVar[Int](0) + - Users (referred to as "EIP-31 supporters") create Unspent Transaction Outputs (UTXOs) containing ERG locked in a smart contract + - These UTXOs have a price attribute specifying the amount of ERG the supporter is willing to pay for one unit of a specific "babel token" + - Smart contracts secure these UTXOs - // ===== Perform Babel Fee Swap ===== // - if (recreatedBabelBoxIndex.isDefined) { +2. **Users Select a Babel Fee Box:** - // Check conditions for a valid babel fee swap - val validBabelFeeSwap: Boolean = { - - // Output babel fee box - val recreatedBabelBox: Box = OUTPUTS(recreatedBabelBoxIndex.get) - - // Check that the babel fee box is recreated correctly - val validBabelFeeBoxRecreation: Boolean = { + - Users locate UTXOs for their desired token + - Verify sufficient ERG for transaction fees + - Evaluate exchange rates + - Choose the most favorable rate - allOf(Coll( - (recreatedBabelBox.propositionBytes == SELF.propositionBytes), - (recreatedBabelBox.tokens(0)._1 == tokenId), - (recreatedBabelBox.R4[SigmaProp].get == babelFeeBoxCreator), - (recreatedBabelBox.R5[Long].get == ergPricePerToken), - (recreatedBabelBox.R6[Coll[Byte]].get == SELF.id) - )) +3. **Babel Fee Box is Spent and Recreated:** - } + - User spends the selected UTXO + - Recreates UTXO with identical parameters (creator's public key and price) + - Deposits required token amount + - Smart contract ensures the difference in ERG is less than or equal to the amount of inserted babel tokens multiplied by the price - // Check that the user's token was exchanged correctly - val validBabelFeeExchange: Boolean = { - - val nanoErgsDifference: Long = SELF.value - recreatedBabelBox.value - val babelTokensBefore: Long = if (SELF.tokens.size > 0) SELF.tokens(0)._2 else 0L - val babelTokensDifference: Long = recreatedBabelBox.tokens(0)._2 - babelTokensBefore - - allOf(Coll( - (babelTokensDifference * ergPricePerToken >= nanoErgsDifference), - (nanoErgsDifference >= 0) - )) - - } - - allOf(Coll( - validBabelFeeBoxRecreation, - validBabelFeeExchange - )) - - } - - sigmaProp(validBabelFeeSwap) - - } else { - - // ===== Perform Babel Fee Box Withdrawl ===== // - babelFeeBoxCreator - - } - -} -``` - -### Contract Template -Compilation of babel fee box smart contracts for different tokens of interest will result in different P2S addresses, leading to each token having a unique corresponding ErgoTree and, consequently, a unique P2S babel fee box smart contract address. To avoid rebuilding the contract for each token, the implementer can use the following contract template, where the `{tokenId}` fragment must be replaced by the hexadecimal identifier of the token of interest. +> **On Cardano**, you will send an "incomplete" transaction, offering to pay the fee using x amount of tokens and wait until a third party accepts your tokens in exchange for ADA to pay the fees. +> +> **On Ergo**, we have pre-defined Babel Fee pools, so there is no waiting, and we can know in advance what tokens we can use to pay fees and the best price available. -``` -100604000e20{tokenId}0400040005000500d803d601e30004d602e4c6a70408d603e4c6a7050595e67201d804d604b2a5e4720100d605b2db63087204730000d606db6308a7d60799c1a7c17204d1968302019683050193c27204c2a7938c720501730193e4c672040408720293e4c672040505720393e4c67204060ec5a796830201929c998c7205029591b1720673028cb272067303000273047203720792720773057202 -``` +For more information about the origin of the term and concepts behind "babel fees", please see the following articles: -### Output position +* [Babel fees - denominating transaction costs in native tokens](https://iohk.io/en/blog/posts/2021/02/25/babel-fees/) +* [Paying fee in ErgoMix in primary tokens](https://www.ergoforum.org/t/paying-fee-in-ergomix-in-primary-tokens/73) -The position of the recreated Babel Box in the transaction's outputs must be set as a context extension variable in the spending Babel Box. +/// -1. Context variable `0` - * Type: `SInt` - * Value: position of the recreated Babel Box in the transaction's outputs -### Parameters -Parameters (creator’s public key and price) are specified via registers, meaning the resulting babel fee boxes from different creators will always belong to the same P2S address, improving their searchability. +## Providing Babel Fee Liquidity -1. Register R4 - * Type: `SigmaProp` - * Value: creator's public key -2. Register R5 - * Type: `SLong` - * Value: how much nanoErgs is the creator willing to pay for one babel token +Providing liquidity for Babel fees is a way to earn passive income while helping new users onboard to Ergo. As a liquidity provider, you lock up ERG in a smart contract and specify a rate at which you're willing to buy tokens. When users pay transaction fees with those tokens, you automatically receive them in exchange for your ERG. This creates a win-win situation - users can transact without needing ERG, and you accumulate tokens at your desired rate. -Babel fee box creator can spend the babel box in any circumstances. -Other users, on the other hand, can spend this box as input to their transaction only when they also recreate it as the output of their transaction with the very same [registers](registers.md) (R4, R5) values together with the insertion of a required amount of babel tokens (the amount of inserted babel tokens multiplied by the price specified in the R5 register has to be equal to or bigger than the amount of nanoErgs spent from the babel fee box). +/// details | To provide Babel fee liquidity: -Wallets implementation --------------------------------------------- + {type: question, open: true} -Wallet developers will need to decide whether they want to support EIP-0031. If they do decide to support this standard, they should also decide on which tokens they want to support (this could be done based on user requirements – e.g. implementing big stablecoins or “meme” coins, etc.), as this could be more convenient than supporting all tokens. -As P2S addresses belonging to a specific token of interest stay the same, these addresses could be easily “hardcoded” when supporting only a few tokens. Suppose the developers decide to support any token. In that case, the previously mentioned smart contract for each token that which user holds should be compiled or "mounted" as described in ["Contract Template"](#contract-template) subsection, and the availability of Babel Fee boxes (UTXOs) for the specific tokens of interest in the blockchain should be subsequently checked. -The proposed babel fee smart contract is general and does not impose many restrictions on the transaction. It is possible to transact some tokens while paying babel fees with another token, etc. -Once the wallet finds a babel fee box which could be used to pay required transaction fees, it should calculate the required price for the transaction fee and present it to the user, so he can decide whether to use this particular option. +1. Go to the [Tokenjay](https://tokenjay.app/) site +2. Click "Open App" +3. Click "Purchase Tokens" +4. Click "Babel Fee Liquidity" +5. Connect a compatible ErgoPay wallet +6. Click "create new babel fee box" +7. Select token from drop-down box or own ID entered below +8. Optional: Enter token ID of a fungible token (not an NFT) not on drop-down list +9. Enter rate, or number of $ERG per token, often as a decimal, such as 0.0001 +10. Enter the amount of $ERG you are willing to buy at that rate +11. Click "create Babel fee box" +12. Scan QR code +13. Check the rates before signing +14. Optional: Go back to Step 6 if the rates were not as expected +15. Sign transaction in your ErgoPay compatible wallet +/// -The wallet should also check the current mempool and determine whether someone is trying to spend this specific babel fee box. In that case, the wallet should construct a “chained” transaction (using the mempool’s transaction output (recreated babel fee output) as the new babel fee box input). This way, many transactions spending “the same” box could be chained and mined inside a single block. A situation can also occur when the babel fee box owner is trying to spend his own box. In that case, the wallet should select another babel fee box, if available. +## Developers -Once the wallet successfully crafts and relays the transaction to the mempool, it MUST keep an eye on the transaction until it is mined. This is important because the wallet cannot prevent somebody else from spending the same babel fee box as our user’s transaction is trying to spend. When two transactions are trying to spend the same box, only one from them can be mined and therefore included in the blockchain, while the other has to be recrafted with the new babel fee box and relayed again to the network. Such a thing should occur rarely, but when it does, the wallet has to handle the situation correctly while notifying the user that the transaction did not go through. +By implementing babel fees in your application, you can enable new users to start transacting immediately using tokens instead of ERG. The Fleet SDK makes this easy with its babel-fees plugin, which handles all the complexities of token-to-ERG conversions and contract interactions. -Reference implementations --------------------------------------------- -* [Nautilus Wallet implementation](https://github.com/capt-nemo429/nautilus-wallet/pull/82) -* [AppKit implementation](https://github.com/ergoplatform/ergo-appkit/pull/204) \ No newline at end of file +You can see the full documentation [here](babel-fleet.md). \ No newline at end of file diff --git a/docs/dev/protocol/tx/babel-fleet.md b/docs/dev/protocol/tx/babel-fleet.md new file mode 100644 index 00000000..bd9be6d5 --- /dev/null +++ b/docs/dev/protocol/tx/babel-fleet.md @@ -0,0 +1,213 @@ +# Babel Fees Plugin Documentation + + +The **Babel Fees Plugin** is a Fleet SDK extension that allows transaction fees to be paid using tokens instead of ERG. This is particularly valuable for onboarding users with empty wallets by enabling token-to-ERG swaps for transaction fees. The plugin includes utility functions for contract creation, validation, and management, along with seamless integration into Fleet SDK's transaction framework. + +--- + +### Key Features + +1. **Token-Based Fee Payment**: + + - Enables users to pay fees with tokens. + - Automates token-to-ERG swaps. + +2. **Validation Utilities**: + + - Validate Babel Boxes and contracts to ensure proper functionality. + +3. **Customizable Contracts**: + + - Developers can define token prices and liquidity for Babel Boxes. + +4. **Optimized for Modern Development**: + + - Supports both ESM and CommonJS modules. + - Tree-shaking enabled for optimal bundle size. + +--- + +### Installation + +Install the Babel Fees Plugin via npm: + +```bash +npm install @fleet-sdk/babel-fees-plugin +``` + +Ensure compatibility with Fleet SDK Core: + +```bash +npm install @fleet-sdk/core +``` + +The plugin requires **Node.js ≥ 18**. + +--- + +### Usage Example + +#### Add Babel Fees to a Transaction + +```typescript +import { TransactionBuilder } from '@fleet-sdk/core'; +import { BabelSwapPlugin } from '@fleet-sdk/babel-fees-plugin'; + +const tx = new TransactionBuilder(1000000) // Replace with current block height + .from(inputs) // Transaction inputs + .extend( + BabelSwapPlugin(babelBox, { + tokenId: "03faf2cb329f2e90d6d23b58d91bbb6c046aa143261cc21f52fbe2824bfcbf04", + amount: "50" // Amount of tokens to swap + }) + ) + .payMinFee() + .sendChangeTo("9hY16vzHmmfyVBwKeFGHvb2bMFsG94A1u7To1QWtUokACyFVENQ") // Change address + .build(); + +console.log(tx); +``` + +--- + +### API Reference + +#### Plugins + +1. **`BabelSwapPlugin`** + + - **Description**: Adds Babel Fee logic to transactions for token-to-ERG conversions. + - **Parameters**: + - `babelBox`: A valid Babel Fee box providing token liquidity. + - `token`: Specifies the token and amount to swap for ERG. + - **Usage**: + ```typescript + BabelSwapPlugin(babelBox, { + tokenId: "03faf2cb329f2e90d6d23b58d91bbb6c046aa143261cc21f52fbe2824bfcbf04", + amount: "50" + }); + ``` + +#### Utility Functions + +1. **`getTokenPrice(babelBox: Box): bigint`** + + - Retrieves the price of a token unit in Nanoergs from a Babel Box. + - **Example**: + ```typescript + const price = getTokenPrice(babelBox); + console.log(`Price per token: ${price}`); + ``` + +2. **`buildBabelContract(tokenId: string): string`** + + - Constructs a Babel Fee ErgoTree for a specified token ID. + +3. **`isValidBabelBox(box: Box): boolean`** + + - Checks if a given box is a valid Babel Fee box. + +4. **`extractTokenIdFromBabelContract(ergoTree: string): string`** + + - Extracts the token ID from a Babel Fee ErgoTree. + +5. **`isBabelContractForTokenId(ergoTree: string, tokenId: string): boolean`** + + - Validates that a Babel Fee contract matches a given token ID. + +--- + +### Box Discovery and Identification + + + +The hexadecimal representation of the Babel Fees contract is: +``` +100604000e20{tokenId}0400040005000500d803d601e30004d602e4c6a70408d603e4c6a7050595e67201d804d604b2a5e4720100d605b2db63087204730000d606db6308a7d60799c1a7c17204d1968302019683050193c27204c2a7938c720501730193e4c672040408720293e4c672040505720393e4c67204060ec5a796830201929c998c7205029591b1720673028cb272067303000273047203720792720773057202 +``` +Replace `{tokenId}` with the specific token ID and use this as a parameter in the API endpoint: `https://api.ergoplatform.com/api/v1/boxes/unspent/byErgoTree/{ErgoTree}` + + +```typescript +const fetchBabelBox = async (ergoTree: string) => { + try { + const response = await fetch(`https://api.ergoplatform.com/api/v1/boxes/unspent/byErgoTree/${ergoTree}`); + const json = await response.json(); + return json.items[0]; // Returns the first Babel Box + } catch (error) { + console.error("Error fetching Babel Box:", error); + return null; + } +}; +``` + + +### Tutorials + +[this guide](http://147.182.244.219/ergobabelfees.html) provides a tutorial on how mint a token, create your babel box, and self-sign on a web application with Babel Fees. + +--- + +### Development Insights + +#### Key Updates from `CHANGELOG.md` + +- **Validation Enhancements**: + + - Type validation for Babel Box fields (`R4`, `R5`) introduced in version `0.1.16`. + +- **Module Export Fixes**: + + - Improved ESM and CommonJS export compatibility in version `0.1.10`. + +#### Package Metadata + +- **Version**: `0.1.18` +- **Dependencies**: + - `@fleet-sdk/core` + - `@fleet-sdk/common` + - `@fleet-sdk/serializer` +- **Environment**: + - Requires Node.js 18 or above. + +--- + +### Testing and Validation + +#### Unit Testing Example + +```typescript +describe("BabelSwapPlugin Tests", () => { + it("should integrate Babel Fee inputs and outputs", () => { + const babelBox = { /* Mock Babel Box */ }; + const tx = new TransactionBuilder(1000000) + .from(inputs) + .extend(BabelSwapPlugin(babelBox, { + tokenId: "03faf2cb329f2e90d6d23b58d91bbb6c046aa143261cc21f52fbe2824bfcbf04", + amount: "50" + })) + .build(); + + expect(tx.inputs).toContain(babelBox); + }); +}); +``` + +--- + +### Reference Implementations + +* [Implementing Ergo Babel Fees with Fleet-SDK - May 17, 2024](http://147.182.244.219/ergobabelfees.html) +* [Nautilus Wallet implementation](https://github.com/capt-nemo429/nautilus-wallet/pull/82) +* [AppKit implementation](https://github.com/ergoplatform/ergo-appkit/pull/204) +* [Fleet SDK Babel fees plugin](https://fleet-sdk.github.io/docs/plugins/babel-fees) + + +### Additional Resources + +- **Fleet SDK Documentation**: [Fleet SDK Babel Fees Plugin](https://fleet-sdk.github.io/docs/plugins/babel-fees) +- **Ergo Platform API**: [Ergo API Documentation](https://api.ergoplatform.com/api/v1/docs/) +- **EIP-0031 Specification**: [Ergo Babel Fees EIP](https://github.com/ergoplatform/eips/blob/master/eip-0031.md) + +For real-world implementation examples, refer to [community tutorial](babel-impl.md) linked within the Fleet SDK documentation. + diff --git a/docs/dev/protocol/tx/babel-impl.md b/docs/dev/protocol/tx/babel-impl.md new file mode 100644 index 00000000..4242f1c3 --- /dev/null +++ b/docs/dev/protocol/tx/babel-impl.md @@ -0,0 +1,308 @@ +# Babel Fees Implementation Guide + +## Overview + +This guide provides detailed instructions for implementing Babel fees in your Ergo applications. The implementation example demonstrates how to enable users to pay transaction fees using tokens instead of ERG, which is particularly useful for new users who may not have ERG in their wallets. + +## Prerequisites + +1. Node.js and npm (tested with Node v20.10.0) +2. Fleet SDK core and babel-fees plugin +3. Webpack for building +4. A minted token to use for Babel fees +5. A Nautilus wallet +6. Ubuntu 22.04 LTS (for server setup) + +## Implementation Steps + +### 1. Token Preparation + +First, mint the token you wish to use for Babel Fees: +1. Create your token (e.g., "lightning tokens" with 1,000,000 supply) +2. Note the Asset ID (e.g., `272a4aeba6d1596ee0405b13fa223074077fd31f2d519fcd2f7b1656596db029`) +3. Note the bank wallet address (e.g., `9hqbqkUfC4nmi1fVNcj8B3iEYh9HUnsLazcsRHwjoZJpZbmrCiq`) + +### 2. Create Babel Fee Box + +Use TokenJay.app to create a Babel Box providing liquidity: +1. Visit [Tokenjay](https://tokenjay.app/) +2. Click "Open App" +3. Navigate to "Purchase Tokens" → "Babel Fee Liquidity" +4. Connect your ErgoPay wallet +5. Create new babel fee box +6. Set your exchange rate (e.g., 0.0001 ERG per 1 token) +7. Set liquidity amount (e.g., 10,000 tokens & 100 ERG) + +### 3. Server Setup + +```bash +# Update system +sudo apt-get update +sudo apt-get upgrade + +# Install NVM +curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.5/install.sh | bash + +# Restart terminal or reboot +nvm install v20.10.0 +nvm install-latest-npm + +# Install nginx +sudo apt-get install nginx + +# Create project directory +cd /var/www/html +mkdir fleetsdk +cd fleetsdk/ + +# Install dependencies +npm install @fleet-sdk/core +npm install --save-dev webpack webpack-cli ts-loader html-webpack-plugin typescript +npm install @fleet-sdk/babel-fees-plugin +``` + +### 4. Configuration Files + +Create webpack configuration (`webpack.config.js`): +```javascript +const path = require('path'); +const HtmlWebpackPlugin = require('html-webpack-plugin'); + +module.exports = { + mode: 'development', + entry: './src/index.ts', + devtool: 'inline-source-map', + module: { + rules: [ + { + test: /\.tsx?$/, + use: 'ts-loader', + exclude: /node_modules/, + }, + ], + }, + resolve: { + extensions: ['.tsx', '.ts', '.js'], + }, + output: { + filename: 'bundle.js', + path: path.resolve(__dirname, 'dist'), + }, + plugins: [ + new HtmlWebpackPlugin({ + template: 'index.html' + }) + ] +}; +``` + +Create TypeScript configuration (`tsconfig.json`): +```json +{ + "compilerOptions": { + "outDir": "./dist/", + "sourceMap": true, + "noImplicitAny": true, + "module": "es6", + "target": "es5", + "jsx": "react", + "allowJs": true + }, + "include": [ + "./src/**/*" + ] +} +``` + +### 5. Implementation Code + +Create the main implementation file (`src/index.ts`): + +```typescript +import { OutputBuilder, TransactionBuilder } from '@fleet-sdk/core'; +import { BabelSwapPlugin } from '@fleet-sdk/babel-fees-plugin'; + +// Configuration - Replace with your values +const AssetID = "272a4aeba6d1596ee0405b13fa223074077fd31f2d519fcd2f7b1656596db029"; +const BabelBoxBankAddr = "9hqbqkUfC4nmi1fVNcj8B3iEYh9HUnsLazcsRHwjoZJpZbmrCiq"; +const ergoTree = `100604000e20${AssetID}0400040005000500d803d601e30004d602e4c6a70408d603e4c6a7050595e67201d804d604b2a5e4720100d605b2db63087204730000d606db6308a7d60799c1a7c17204d1968302019683050193c27204c2a7938c720501730193e4c672040408720293e4c672040505720393e4c67204060ec5a796830201929c998c7205029591b1720673028cb272067303000273047203720792720773057202`; + +// Fetch Babel Box from API +const fetchBabelBox = async () => { + try { + const response = await fetch(`https://api.ergoplatform.com/api/v1/boxes/unspent/byErgoTree/${ergoTree}`); + const json = await response.json(); + const babelBox = json.items[0]; + + const additionalRegisters = { + R4: babelBox.additionalRegisters.R4?.serializedValue, + R5: babelBox.additionalRegisters.R5?.serializedValue, + R6: babelBox.additionalRegisters.R6?.serializedValue, + R7: babelBox.additionalRegisters.R7?.serializedValue, + R8: babelBox.additionalRegisters.R8?.serializedValue, + R9: babelBox.additionalRegisters.R9?.serializedValue + }; + + return { ...babelBox, additionalRegisters }; + } catch (error) { + console.error('Failed to fetch Babel Box:', error); + return null; + } +} + +// Main Babel Fees transaction function +const BabelFees = async () => { + try { + const connected = await ergoConnector.nautilus.connect(); + if (connected) { + const defaultAddress = await ergo.get_change_address(); + const height = await ergo.get_current_height(); + const babelBox = await fetchBabelBox(); + + if (!babelBox) { + console.log("No suitable Babel Box found."); + return; + } + + const unsignedTx = new TransactionBuilder(height) + .from(await ergo.get_utxos()) + .extend(BabelSwapPlugin(babelBox, { + tokenId: AssetID, + amount: "50" + })) + .to( + new OutputBuilder( + '1000000', + defaultAddress + ).addTokens({ + tokenId: AssetID, + amount: "50" + }) + ) + .sendChangeTo(BabelBoxBankAddr) + .payMinFee() + .build() + .toEIP12Object(); + + const signedTx = await ergo.sign_tx(unsignedTx); + const txId = await ergo.submit_tx(signedTx); + + if (txId) { + console.log("Transaction ID:", txId); + } + } + } catch (error) { + console.error("Transaction Error:", error); + } +}; + +// Event listeners +document.addEventListener('DOMContentLoaded', () => { + const PayWithBabelFees = document.getElementById('BabelFees'); + if (PayWithBabelFees) { + PayWithBabelFees.addEventListener('click', BabelFees); + } +}); +``` + +### 6. Create HTML Interface + +Create `babelfees.html`: +```html + + + + + Ergo BabelFees + + + +
+
+ +
+
+ + +``` + +### 7. Build and Deploy + +Compile the TypeScript code: +```bash +cd /var/www/html/fleetsdk +npx webpack +``` + +## Testing + +To test your implementation: + +1. Create a new Nautilus wallet (0 assets initially) +2. Transfer appropriate amount of tokens to the new wallet +3. Wait for transaction settlement +4. Connect to your test page using the wallet +5. Attempt self-signing with Babel fees + +## Important Security Notes + +1. Change Address Handling: + - Current implementation sends change to `BabelBoxBankAddr` + - Using `defaultAddress` is cleaner but requires security evaluation + - Consider potential liquidity draining attacks + +2. Transaction Monitoring: + - Implement proper error handling + - Monitor transaction status + - Handle concurrent spending attempts + +## Reference Implementations +* [Nautilus Wallet implementation](https://github.com/capt-nemo429/nautilus-wallet/pull/82) +* [AppKit implementation](https://github.com/ergoplatform/ergo-appkit/pull/204) +* [Fleet SDK Babel fees plugin](https://fleet-sdk.github.io/docs/plugins/babel-fees) + +## Additional Resources +- [EIP-0031 Specification](https://github.com/ergoplatform/eips/blob/master/eip-0031.md) +- [Fleet SDK Documentation](https://fleet-sdk.github.io/docs/plugins/babel-fees) +- [Ergo Platform API Documentation](https://api.ergoplatform.com/api/v1/docs/) + + + + +## Wallet Implementation Considerations + +### Box Discovery and Identification +The hexadecimal representation of the Babel Fees contract is: +``` +100604000e20{tokenId}0400040005000500d803d601e30004d602e4c6a70408d603e4c6a7050595e67201d804d604b2a5e4720100d605b2db63087204730000d606db6308a7d60799c1a7c17204d1968302019683050193c27204c2a7938c720501730193e4c672040408720293e4c672040505720393e4c67204060ec5a796830201929c998c7205029591b1720673028cb272067303000273047203720792720773057202 +``` +Replace `{tokenId}` with the specific token ID and use this as a parameter in the API endpoint: `https://api.ergoplatform.com/api/v1/boxes/unspent/byErgoTree/{ErgoTree}` + +### Implementation Requirements + +1. **Fee Calculation and Display** + + - Calculate required Babel fee amount + - Show clear exchange rates + - Provide fee comparisons + - Display transaction status updates + +2. **Transaction Management** + + - Monitor mempool for concurrent spending + - Implement chained transaction support + - Handle transaction failures gracefully + - Support multiple users spending same box + +3. **Security Considerations** + + - Validate all Babel fee box parameters + - Implement proper change address handling + - Consider potential liquidity draining attacks + + +### Development Tools +- Fleet SDK plugin: `@fleet-sdk/babel-fees-plugin` +- API integration endpoints +- Smart contract templates + diff --git a/docs/dev/scs/debugging.md b/docs/dev/scs/debugging.md index 21b259db..279956db 100644 --- a/docs/dev/scs/debugging.md +++ b/docs/dev/scs/debugging.md @@ -2,33 +2,75 @@ Since ErgoScript is usually encapsulated within string literals, it is not feasible to directly set breakpoints within the script text itself for debugging purposes. -However, ErgoScript is a deliberate subset of Scala, and a robust test suite, SigmaDslSpecification, exists to verify the equivalence between ErgoScript and Scala. As such, you can utilize Scala's debugging capabilities to debug ErgoScript. +## Scala-Based Debugging Approach -An example of such a debugging scenario is provided in the sigmastate-interpreter repository, specifically within [AssetsAtomicExchange.scala#L29](https://github.com/ScorexFoundation/sigmastate-interpreter/blob/83dc78b5c80b11dcab41ba8aa75a0a8a650e6473/sigmastate/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchange.scala#L29). +ErgoScript is a deliberate subset of Scala, and a robust test suite, SigmaDslSpecification, exists to verify the equivalence between ErgoScript and Scala. As such, you can utilize Scala's debugging capabilities to debug ErgoScript. + +### Practical Debugging Example + +An example of a debugging scenario is provided in the sigmastate-interpreter repository, specifically within [AssetsAtomicExchange.scala#L29](https://github.com/ScorexFoundation/sigmastate-interpreter/blob/83dc78b5c80b11dcab41ba8aa75a0a8a650e6473/sigmastate/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchange.scala#L29). ```scala -// See link for full context: - lazy val buyerProp = proposition("buyer", { ctx: Context => - import ctx._ - (HEIGHT > deadline && pkA) || { - val tokenData = OUTPUTS(0).R2[Coll[(Coll[Byte], Long)]].get(0) - val knownId = OUTPUTS(0).R4[Coll[Byte]].get == SELF.id - allOf(Coll( - tokenData._1 == tokenId, - tokenData._2 >= 60L, - OUTPUTS(0).propositionBytes == pkA.propBytes, - knownId - )) - } - }, +// Debugging example from AssetsAtomicExchange +lazy val buyerProp = proposition("buyer", { ctx: Context => + import ctx._ + (HEIGHT > deadline && pkA) || { + val tokenData = OUTPUTS(0).R2[Coll[(Coll[Byte], Long)]].get(0) + val knownId = OUTPUTS(0).R4[Coll[Byte]].get == SELF.id + allOf(Coll( + tokenData._1 == tokenId, + tokenData._2 >= 60L, + OUTPUTS(0).propositionBytes == pkA.propBytes, + knownId + )) + } +}, ``` -In this instance, a breakpoint can be set at the specified line above. Following this, debug run can be executed for the [corresponding test](https://github.com/ScorexFoundation/sigmastate-interpreter/blob/401d40a22430661ed5a397098633465b1e39e3bc/sigmastate/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchangeTests.scala#L46): +## Debugging Process + +In this instance, a breakpoint can be set at the specified line above. Following this, a debug run can be executed for the [corresponding test](https://github.com/ScorexFoundation/sigmastate-interpreter/blob/401d40a22430661ed5a397098633465b1e39e3bc/sigmastate/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchangeTests.scala#L46): ```scala -// Test link: +// Test method for atomic exchange property("atomic exchange spec") { - + // Test implementation details +} ``` -During this execution, the debugger should halt at the pre-set breakpoint, enabling you to inspect and understand the code behavior in a step-by-step manner. \ No newline at end of file +## Debugging Technique + +During this execution, the debugger should halt at the pre-set breakpoint, enabling you to: +- Inspect variable states +- Understand code behavior step-by-step +- Validate contract logic in a controlled environment + +## Key Debugging Strategies + +1. **Use Scala Debugging Tools** + - Leverage IntelliJ IDEA or other Scala IDEs + - Set breakpoints in test cases + - Step through contract logic + +2. **Comprehensive Testing** + - Create detailed test scenarios + - Cover multiple execution paths + - Simulate different blockchain states + +3. **Context Validation** + - Carefully examine context variables + - Verify box selection and properties + - Check sigma proposition construction + +## Recommended Resources + +- [SigmaState Interpreter Repository](https://github.com/ScorexFoundation/sigmastate-interpreter) +- [ErgoScript Documentation](/dev/scs/ergoscript.md) +- [Ergo Developer Forum](https://www.ergoforum.org/) + +## Best Practices + +- Break complex contracts into smaller, testable components +- Use property-based testing +- Understand the nuances of the UTXO model +- Leverage Scala's type system for compile-time checks diff --git a/docs/dev/scs/ergoscript-primer.md b/docs/dev/scs/ergoscript-primer.md index f4d5fd11..97fd5efa 100644 --- a/docs/dev/scs/ergoscript-primer.md +++ b/docs/dev/scs/ergoscript-primer.md @@ -1,49 +1,113 @@ --- tags: - ErgoScript + - Beginner Guide --- -# A Quick Primer on ErgoScript +# ErgoScript: A Beginner's Guide -//// admonition | Background Reading -/// admonition | 1. Paradigm - type: note +## What is ErgoScript? -Ergo's transaction model offers several advantages over the account-based model, explore this new [paradigm](/dev/scs/#paradigm). -/// +ErgoScript is a powerful, developer-friendly programming language designed specifically for writing smart contracts on the Ergo blockchain. Think of it as a specialized language that allows you to create complex financial contracts and applications with unprecedented flexibility and security. -/// admonition | 2. Key Concepts - type: tip +## Key Characteristics -Explore the [Core Concepts of ErgoScript](ergoscript-key-concepts.md). -/// -/// admonition | 3. Context Claims - type: note +### 1. UTXO-Based Model +Unlike account-based blockchains, ErgoScript uses the UTXO (Unspent Transaction Output) model. This means: -Ergo offers a unique approach to smart contract-enabled blockchains, providing efficient global context claims through the concept of data inputs. +- Contracts define conditions for spending coins +- Transactions are immutable and more secure +- Improved scalability and parallel processing -/// -/// admonition | 4. ErgoScript vs ErgoTree - type: note +### 2. Declarative Programming +ErgoScript is declarative, which means you specify **what** should happen, not **how** it happens. For example: -ErgoScript is a high-level developer-friendly language for writing smart contracts that are then compiled to ErgoTree before being written to the blockchain. Explore the distinction [here](ergoscriptvergotree.md) -/// -//// +```scala +// A simple contract that allows spending only after a specific block height +if (HEIGHT > 100000) signerPubKey else fail() +``` +This contract says: "Allow spending only if the current blockchain height is greater than 100,000, otherwise fail." +### 3. Sigma Protocols +ErgoScript leverages advanced cryptographic techniques called Sigma Protocols, enabling: +- Complex signature schemes +- Ring signatures +- Threshold signatures +- Advanced privacy features +## Getting Started -## ErgoScript Examples +### Basic Syntax +ErgoScript is a subset of Scala, so if you're familiar with functional programming, you'll feel right at home. Here's a simple example: -> **Tip:** For beginners, we highly recommend the [ErgoScript P2S playground](https://wallet.plutomonkey.com/p2s/), which can be used to get the Ergo address corresponding to some arbitrary ErgoScript program. Please use the P2S playground only for experiments. +```scala +// A contract that requires two of three signatures to spend +val pubKey1 = ... +val pubKey2 = ... +val pubKey3 = ... +sigmaProp(pubKey1 && pubKey2 || pubKey1 && pubKey3 || pubKey2 && pubKey3) +``` -- [Anyone Can Spend Scripts](anyone-can-spend.md) -- [No-one-Can Spend Scripts](no-one-can-spend.md) -- [Context Variables](context-variables.md) -- [Code-blocks](code-blocks.md) -- [Public-keys](public-keys.md) -- [Functional Programming](functional-programming.md) -- [Box Structure](box-structure.md) -- [Storing Data](storing-data.md) +### Development Tools +- [ErgoScript P2S Playground](https://wallet.plutomonkey.com/p2s/): Experiment and generate Ergo addresses +- [Ergo AppKit](https://github.com/ergoplatform/ergo-appkit): Development framework for building Ergo applications + +## Common Use Cases + +1. **Multi-Signature Wallets** + Create wallets requiring multiple parties to approve transactions + +2. **Time-Locked Contracts** + Define contracts that can only be executed after a specific time or block height + +3. **Conditional Spending** + Set complex conditions for spending funds based on various parameters + +## Learning Paths + +### Beginner +- [ErgoScript Overview](/dev/scs/ergoscript.md) +- [UTXO Model Explained](/dev/protocol/eutxo) + +### Intermediate +- [Sigma Protocols](/dev/scs/sigma.md) +- [Advanced Contract Patterns](/dev/scs/contracts.md) + +### Advanced +- [ErgoTree Compilation](/dev/scs/ergoscriptvergotree.md) +- [Cryptographic Protocols](/dev/crypto/) + +## Best Practices + +1. Keep contracts simple and readable +2. Use built-in cryptographic primitives +3. Always consider transaction validation overhead +4. Test contracts thoroughly in the playground + +## Common Pitfalls to Avoid + +- Overcomplicating contract logic +- Ignoring performance implications +- Neglecting error handling +- Not understanding UTXO model nuances + +## Community and Support + +- [Ergo Developer Forum](https://www.ergoforum.org/) +- [Ergo GitHub Discussions](https://github.com/ergoplatform/ergo/discussions) +- [Ergo Developer Telegram](https://t.me/ergo_dev) + +## Next Steps + +1. Experiment with the P2S Playground +2. Study example contracts +3. Join community discussions +4. Start building your first dApp! + +## Recommended Reading + +- [Ergo Whitepaper](https://ergoplatform.org/en/whitepaper/) +- [ErgoScript Technical Documentation](/dev/scs/) diff --git a/docs/dev/scs/ergoscript.md b/docs/dev/scs/ergoscript.md index aac0654d..8d9e7646 100644 --- a/docs/dev/scs/ergoscript.md +++ b/docs/dev/scs/ergoscript.md @@ -91,6 +91,7 @@ Please see this [Quick Primer on ErgoScript](/dev/scs/ergoscript-primer) for an ## Comparative Analysis ErgoScript stands out by: + - Providing Turing-completeness without compromising blockchain efficiency - Supporting advanced cryptographic protocols - Enabling complex financial contracts with minimal overhead diff --git a/docs/index.md b/docs/index.md index 0a9ada1b..5008a85c 100644 --- a/docs/index.md +++ b/docs/index.md @@ -135,6 +135,12 @@ Ergo’s community is vibrant and continuously evolving. Keep updated with the l "content": "An alternative blockchain you can use for experimentation", "image": "../../assets/img/dev-grid/testnet.png", "url": "../../node/testnet.md" + }, + { + "title": "Bookmarks", + "content": "An overview of Ergo resources", + "image": "../../assets/img/dev-grid/faq.png", + "url": "https://direct.me/ergo" } ] diff --git a/docs/roadmap.md b/docs/roadmap.md index 3a702eb8..ba4ae2a5 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -257,73 +257,262 @@ Ergo is developed a by a combination of the [Ergo Foundation](ergo-foundation.md - [Crux Finance MVP](https://cruxfinance.io/) - [x] SigmaO options trading platform -/// - +/// /// details | 2024: Future Horizons (In Progress and Planned) {open: true} + - Ongoing work to define rules for new releases and research-driven development frameworks - Encouragement of new stakeholder organizations within the Ergo ecosystem -- **Milestones:** - - [x] [ErgoHack VIII - Ergo as a Smart Layer](http://docs.ergoplatform.org/events/ergohack/#ergohackviii) [(Playlist)](https://youtube.com/playlist?list=PL8-KVrs6vXLRp_oUjngJiiWMTFo4qZbAk) - - [x] [DAO for Ergo core](devdao.md) - - [x] Ergo achieved [#1 in TVL% of market cap for a PoW chain](https://x.com/cannon_qq/status/1772254513920876671?t=8KODg1I33kaPSNQw_wn2Bg) - - [x] Ergo listed on MEXC exchange - - [ ] Continous discussions for improved accessibility, including potential listings on US markets ([progress tracked here](https://ergo.getgrist.com/jf9KPR1HUDJH/Project-Management/p/28)) - - **Sigmanauts** - - **00/24**: Sigmanauts Mining Pool launches. - - **01/24**: The [first proposal on Paideia](https://app.paideia.im/Sigmanauts/proposal/promote-richi-mana-to-sigmanaut-05b10641-0097-4b8a-9a47-c0aac5c67aeb) passes. - - **03/24**: The Sigmanauts [officially take over management of the Market-Making services](https://app.paideia.im/Sigmanauts/proposal/05825226-0ea4-4fb0-ae4a-cb0ecc984684). - - **03/24**: In recognition of the Sigmanauts' dedication and hard work on securing the MEXC listing, the Ergo Foundation [provides a substantial grant](https://twitter.com/Sigmanauts/status/1768369713472553068) matching the amount raised by the Sigmanauts. - -- **Development Focus:** - - **Reference Client**: - - [ ] [Sub-blocks](subblocks.md) implementation - - [ ] P2P layer optimization and review - - [ ] Bootstrapping improvements - - [ ] Sidechain implementation modularization - - [ ] Potential RocksDb integration - - [ ] Enhanced testing for indices, scans, and wallet - - **Sigma**: - - [ ] [Sigma 6.0 implementation](https://github.com/ergoplatform/eips/blob/a24fc414abbc10e6ee59f878b280d9ecc725e10c/eip-0050.md) and validation context extension research - - [ ] Signature re-checking optimization - - [ ] ErgoScript 2.0 - - [ ] [EIP-0046: Atomic Chains](https://github.com/ergoplatform/eips/blob/2de4ea0deff12a276f74df57ef3a14dab2c5dfb8/eip-0046.md) - - [ ] [EIP-0047: Pooled Transaction Inputs](https://github.com/ergoplatform/eips/blob/0836dd1eca323c6b5fd6b5172c27a465bd4449cd/eip-0047.md) - - [ ] [MerkleTrees](https://github.com/ScorexFoundation/sigmastate-interpreter/issues/296) - - [ ] Revisiting formal verification implementation - - [ ] Bulletproofs - - [ ] Exploration of Rust and JavaScript support in addition to ErgoScript - - [ ] Consideration of high-level language support (e.g., Lisp) - - [ ] Improvements to error-checking and debugging tools - - [ ] Revisiting formal verification implementation - - **SDKs**: - - [x] [AppKit](appkit.md) - - [x] [FleetSDK](fleet.md) - - [x] [sigma-rust](sigma-rust.md) - - [ ] JIT costing implementation in Sigma-Rust - - [ ] 6.0 features implementation in Sigma-Rust - - [ ] Sigma-Rust-Mini development - - [x] Sigma.js - - **Libraries & Tooling** - - [x] [ergo-lib-go](https://github.com/sigmaspace-io/ergo-lib-go) - - [x] [escript.online](https://escript.online) - - [x] [Blockly Playground Integration](https://escript.online/blockly) - - **Mining Ecosystem:** - - [ ] Lithos decentralized mining pool infrastructure expected launch by end of 2024 - - [ ] Plans for reintroduction of Fair Initial Mining Offerings (FIMOs) - - **Wallets:** - - [x] Nautilus - - [x] Manifest v3 rework - - [ ] Ledger - - [x] Available in developer mode - - [ ] Keystone Integration - - [ ] EIP-12 / EIP-20 - - [ ] Metamask integration - - [ ] Trustwallet Integration - - [ ] Light SPV Clients using NiPoPoWs +#### Milestones + +- [x] [ErgoHack VIII - Ergo as a Smart Layer](http://docs.ergoplatform.org/events/ergohack/#ergohackviii) +- [x] [DAO for Ergo core](devdao.md) +- [x] Ergo achieved [#1 in TVL% of market cap for a PoW chain](https://x.com/cannon_qq/status/1772254513920876671?t=8KODg1I33kaPSNQw_wn2Bg) +- [x] Ergo listed on MEXC exchange +- [x] Ergo Node improvements: + - Successful migration from LevelDB to RocksDB + - 6.0.0-alpha1 release with Global.some/none methods and AVL+ Tree optimizations +- [x] Sigma protocol updates: + - Sigma 5.0.14 release + - Sigma 6.0.0 update with scrypto 3.0.0 +- [x] Infrastructure improvements: + - Sigmaspace blockchain indexer completion (full index <24 hours) + - Resolved indexer issues (rollbacks, duplicates, threading) + - Sigmaspace explorer API compatibility with ergoplatform.org + - Sigmaspace storage rent dashboard launch + +#### Sigmanauts Achievements + +- [x] Sigmanauts Mining Pool launch +- [x] Storage rent integration completed for Sigmanauts Mining Pool +- [x] First proposal on Paideia passes (January 2024) +- [x] Official takeover of Market-Making services management (March 2024) +- [x] Substantial EF grant received matching Sigmanauts-raised funds (March 2024) + +#### Application Achievements + +**Wallet Developments** + +- [x] Nautilus Wallet improvements: + + - Version 0.15.0 release + - Abyss v0.13.0-beta.1 with performance improvements + - New frontend implementation + - Improved Firefox compatibility + - Enhanced asset ranking and sorting in Assets and Send tabs + - Comprehensive dApp documentation + +- [x] Minotaur Wallet: + + - Version 2.0.1 production release + +- [x] Satergo Wallet: + + - 3x faster transaction history loading + - New Ergonnection library version + - Simplified Windows installations + +**Infrastructure & Tools** + +- [x] Sigmaspace development: + + - Complete blockchain indexer (<24 hours full index) + - Storage rent dashboard launch with tracking features + - Explorer API compatibility with ergoplatform.org + +- [x] Lithos progress: + + - Initial client development completion + - Fraud proofs contracts for NISPs (PoW verification, header validation) + +- [x] Rosen Bridge improvements: + + - Enhanced decimal handling logic for cross-chain transactions + - API and UI revisions + +**DeFi Applications** + +- [x] SigmaUSD improvements: + + - Enhanced stability mechanisms + - Oracle upgrade exploration + +- [x] Fleet SDK advancements: + + - AgeUSD integration completion + - Enhanced development toolkit + +- [x] Celaut platform development +- [x] Bene fundraising platform updates + +#### Development Focus + +**Reference Client** + +- [ ] [Sub-blocks](subblocks.md) implementation: + + - Data types and update procedures + - Candidate generation + - Block template regeneration integration + +- [ ] P2P layer optimization and review +- [ ] Bootstrapping improvements +- [ ] Sidechain implementation modularization +- [x] RocksDB integration and optimization +- [ ] Enhanced testing for indices, scans, and wallet + +**Sigma** + +- [ ] [Sigma 6.0 implementation](https://github.com/ergoplatform/eips/blob/a24fc414abbc10e6ee59f878b280d9ecc725e10c/eip-0050.md) and validation context extension research + + - [x] Progress on Sigma 6.0 features: + + - SOption[] serialization + - Header serialization/deserialization + - Header.checkPoW implementation + - Global.powHit implementation + - Enhanced collections and numeric methods + - Improved error messages + + +- [ ] Signature re-checking optimization +- [ ] ErgoScript 2.0 +- [ ] [EIP-0046: Atomic Chains](https://github.com/ergoplatform/eips/blob/2de4ea0deff12a276f74df57ef3a14dab2c5dfb8/eip-0046.md) +- [ ] [EIP-0047: Pooled Transaction Inputs](https://github.com/ergoplatform/eips/blob/0836dd1eca323c6b5fd6b5172c27a465bd4449cd/eip-0047.md) +- [ ] [MerkleTrees](https://github.com/ScorexFoundation/sigmastate-interpreter/issues/296) +- [ ] [EIP-44](eip44.md): Implementation of "truthy boxes" for verifying minted tokens and encrypted NFT content +- [ ] Revisiting formal verification implementation +- [ ] Bulletproofs +- [ ] Exploration of Rust and JavaScript support in addition to ErgoScript +- [ ] Consideration of high-level language support (e.g., Lisp) +- [ ] Improvements to error-checking and debugging tools +- [x] Enhanced stateless validation in Sigma-Rust + +**SDKs** + +- [x] [AppKit](appkit.md) +- [x] [FleetSDK](fleet.md) + + - [x] Integration with AgeUSD stablecoin +- [x] [sigma-rust](sigma-rust.md) + - [ ] JIT costing implementation in Sigma-Rust + - [ ] 6.0 features implementation in Sigma-Rust + - [ ] Sigma-Rust-Mini development +- [x] Sigma.js + +**Libraries & Tooling** + +- [x] [ergo-lib-go](https://github.com/sigmaspace-io/ergo-lib-go) +- [x] [escript.online](https://escript.online) + - [x] [Blockly Playground Integration](https://escript.online/blockly) +- [x] Token metadata standards discussion +- [x] Lithos light-client integration progress + +**Mining Ecosystem** + +- [ ] Lithos decentralized mining pool infrastructure expected launch by end of 2024 +- [ ] Plans for reintroduction of Fair Initial Mining Offerings (FIMOs) + +**Wallets** + +- [x] Nautilus + + - [x] Manifest v3 rework + +- [ ] Ledger + + - [x] Available in developer mode + +- [x] Keystone Integration progress +- [ ] EIP-12 / EIP-20 +- [ ] Metamask integration +- [ ] Trustwallet Integration +- [ ] Light SPV Clients using NiPoPoWs + +**Ecosystem Growth** + +- [x] DeFi ecosystem expansion: + + - New protocols exploration + - NFT platform improvements + +- [ ] Continuous integration of new protocols and platforms +- [x] UX/UI improvement initiatives across applications + +**Documentation & Education** + +- [x] New educational materials on: + + - Merkle trees + - Extension blocks + - Soft-fork rules + - Signature schemes + - ErgoScript compilation + +- [x] Ergo Forum enhancement as knowledge hub + +**Development Process Improvements** + +- [x] Enhanced focus on code quality and review processes +- [x] Improved version management procedures +- [x] Better transparency in development communication + +**Ongoing Challenges** + +- [ ] **Scalability Improvements (Layer 1 and Layer 2)** + + - Sub-blocks implementation for enhanced transaction throughput + - Layer 2 solutions exploration: + + - Weak consensus mechanisms for local payment networks + - Digital bearer certificates + + - P2P layer optimization for network efficiency + - Bootstrapping improvements for faster node synchronization + - Research into enhanced transaction processing and network scalability + +- [ ] **Usability Enhancements** + - Wallet and dApp user experience improvements + - Development tools advancement: + + - Comprehensive ErgoScript debugger + - Enhanced escript.online functionality + - Structured output for debugging + + - Documentation and education: + + - Improved developer documentation + - Enhanced tutorials and guides + - Better onboarding resources + + - Streamlined development workflows + +- [ ] **Security Strengthening** + + - Ongoing vulnerability assessment and mitigation + - Protocol security mechanism enhancements + - Smart contract security improvements + - Regular security audits and reviews + - Implementation of best practices for secure development + +- [ ] **Ecosystem Development** + + - Continuous discussions for improved accessibility + - Potential listings on US markets + - Balancing rapid development with thorough testing + - Enhanced coordination between development teams + - Streamlined contribution processes + +- [ ] **Technical Debt and Optimization** + + - Code quality maintenance + - Performance optimization + - System architecture improvements + - Technical documentation updates + - Development process refinements /// @@ -341,6 +530,7 @@ Every new addition to our growing DeFi ecosystem contributes to the expansion of - [x] [ErgoAuctionHouse](ergo-auctions.md) (peer-to-peer auctions) - [x] [Trade House](https://ergoauctions.org/trade?pair=ERG-SigUSD) (orderbook-based P2P DEX) - [x] [SkyHarbor](skyharbor.md) (NFT Market) + - [x] [SkyHarbor Raffle for new UI](https://skyharbor.medium.com/enhancing-the-nft-experience-skyharbors-new-initiative-9679e94e3cd8) - [x] [single-tx-swap](https://www.single-tx-swap.com/) (trustless p2p swaps) - [x] [TokenJay](https://tokenjay.app/app/#purchases) (p2p escrow) @@ -348,7 +538,7 @@ Every new addition to our growing DeFi ecosystem contributes to the expansion of - [ ] [PalmyraComDex](palmyra.md) (commodities DEX) ([Alpha live](https://palmyra.app/)!) - [ ] [Crystal Pool](crystal-pool.md) (instant L1 order-based trading) - [ ] [Machina Finance](machina-finance.md) (grid DEX) -- [ ] [Mew Finance](https://mewfinance.com/) +- [x] [Mew Finance](https://mewfinance.com/) ### Stablecoins @@ -366,6 +556,7 @@ Every new addition to our growing DeFi ecosystem contributes to the expansion of ### Gaming and Metaverse - [x] [BlitzTCG](blitz.md) (trading card game) - [x] [CyberVerse](cyberverse.md) (metaverse gaming platform) + - [x] Cyberverse Multiplayer ### Derivatives and Synthetics @@ -388,7 +579,7 @@ Every new addition to our growing DeFi ecosystem contributes to the expansion of - [x] ADA Bridge - [x] BTC Bridge - [ ] Runes Integration - - [ ] EVM Bridge + - [x] EVM Bridge - [ ] R&D for Monero - [ ] RosenFast Service - [ ] Bridge Expansion Kit @@ -397,15 +588,13 @@ Every new addition to our growing DeFi ecosystem contributes to the expansion of - [ ] BCH Bridge - [ ] Hummingbot Integration / Customisation - [ ] [Sigma Chains](sigma-chains.md) - Revitalizing Proof of Work + - [ ] Trustless Relays (Superseding BTC custody solutions with Ergo smart-contracts) - [ ] Implementing sidechains with trustless transfers and various consensus mechanisms (merged mined with ERG, other blockchains, or double merged mined) - [ ] Expanding Ergo's contractual layer to sidechains, incorporating features like Bulletproofs-based sigma protocols and elevating certain contracts to first-class citizens - [ ] Experimenting with scalability solutions like sharding on sidechains - [ ] Utilizing ERG and other tokens on Ergo and sidechains from launch, fostering a rich and diverse DeFi ecosystem - [ ] Launching existing applications on sidechains, contingent on modifications to the contractual layer -- [ ] [Analog Ergo](analog-ergo.md) (atomic swaps) - - [x] Alpha Live - - [x] Lightning Swaps @@ -419,7 +608,6 @@ Every new addition to our growing DeFi ecosystem contributes to the expansion of - [x] [Paideia](paideia.md) (DAO toolkit) - [ ] [Lithos](lithos.md) (decentralized mining infrastructure) -- [ ] [Thz.FM](thz-fm.md) (decentralised media monetisation & management) - [ ] [The Field](the-field.md) (peer-to-pool pledging protocol) diff --git a/docs/social_contract.md b/docs/social_contract.md index 440e68c6..aab717b7 100644 --- a/docs/social_contract.md +++ b/docs/social_contract.md @@ -4,8 +4,6 @@ The Ergo protocol is very flexible and may be changed in the future by the commu In case of intentional violation of any of these principles, the resulting protocol should not be called Ergo. - - ### Decentralization First. - Ergo should be as decentralized as possible: any parties (social leaders, software developers, hardware manufacturers, miners, funds and so on) whose absence or malicious behavior may affect the security of the network should be avoided. diff --git a/docs/tutorials/token_integration.md b/docs/tutorials/token_integration.md index e27768a8..e7054693 100644 --- a/docs/tutorials/token_integration.md +++ b/docs/tutorials/token_integration.md @@ -1,64 +1,1093 @@ -# Integration Guide for Bridging ERG Tokens +# Cross-Chain Token Integration Guide for Rosen Bridge Tokens -This guide provides a comprehensive approach to integrating and listing ERG tokens bridged to different networks, focusing on Ethereum, Cardano, and platform-specific analytics. Follow these steps to ensure your token is accurately recognized and accessible across various platforms and decentralized applications (dApps). +This guide outlines the process for integrating and listing tokens that have been bridged between networks using Rosen Bridge. Whether you're bridging from Ergo to Cardano, Cardano to Ethereum, or any other supported network combination, these steps will help ensure your token is properly integrated across ecosystems. -## General Integration Steps +## Overview of Cross-Chain Possibilities -### 1. CoinGecko +Tokens can be bridged between any networks connected via Rosen Bridge. This means: -CoinGecko connects token data to multiple DeFi platforms. Listing here enhances visibility and accessibility across the ecosystem: +- Ergo tokens can be bridged to Cardano/Ethereum +- Cardano tokens can be bridged to Ergo/Ethereum +- Future networks will be supported as they're added to Rosen Bridge (BSC, DOGE) -- **Submit a New Token Request**: Use the [CoinGecko Token Request Form](https://www.coingecko.com/request-form/tokens/new?locale=en) to input essential details, like the token contract address, symbol, and name. -- **Verification Guide**: Follow the [CoinGecko Verification Guide](https://support.coingecko.com/hc/en-us/articles/23725417857817-Verification-Guide-for-Listing-Update-Requests-on-CoinGecko) to ensure your submission is accurate and meets listing criteria. +### Key Considerations for Multi-Chain Presence +- Each bridged version represents the same token on different networks +- Liquidity needs to be managed across all chains +- Analytics and trading platforms should be integrated per network +- Community education needed for cross-chain functionality -### 2. DEX Integration Checklist +## Phase 1: Initial Listing and Market Data Setup -Listing your bridged token on decentralized exchanges (DEXs) enables liquidity and trading. Each DEX has unique requirements for listing; however, general steps include: +### Market Data Platforms Overview -- **Liquidity Pools**: Check each DEX’s documentation for specific pool requirements, such as initial liquidity contributions and associated fees. -- **Submit a Token Request**: Many DEXs use public GitHub repositories or online forms to process token requests. Verify that the token’s details align with the contract information. +#### CoinGecko +The world's largest independent crypto data aggregator. Generally easier to get listed compared to CoinMarketCap but still requires significant volume and legitimate activity. ---- +- Submit via [CoinGecko Token Request Form](https://www.coingecko.com/request-form/tokens/new?locale=en) +- Follow the [CoinGecko Verification Guide](https://support.coingecko.com/hc/en-us/articles/23725417857817-Verification-Guide-for-Listing-Update-Requests-on-CoinGecko) -## Network-Specific Integrations +Options: -### Ethereum +- For tokens with existing listings + decent volume: Potential automatic acceptance +- Alternative: $400 for fast-track listing -Ethereum-based platforms are essential for ERG tokens bridged to the Ethereum network: +#### CoinMarketCap +The most recognized crypto data platform globally. Getting listed here provides significant legitimacy but has stringent requirements. Typically requires higher volume and more established presence than CoinGecko. Essential for serious projects but should be attempted after CoinGecko listing. + +#### LiveCoinWatch +A growing alternative to CMC and CoinGecko. Generally has lower barriers to entry and faster listing times. Good for building initial market presence and tracking metrics while working toward larger platform listings. + +#### GeckoTerminal +Modern DEX analytics platform focusing on real-time trading data and charts. Particularly strong for tracking DEX pairs and providing detailed trading analytics. + +## Phase 2: Analytics Integration + +### Trading Analytics Platforms + +#### Dexscreener + +Popular DEX pair analytics platform with strong community adoption. Often the first stop for traders researching new tokens. While token information can be automatically pulled from CoinGecko once listed there, enhanced features are available as a paid option. + +- Purchase (Optional) [Enhanced Token Info](https://marketplace.dexscreener.com/product/token-info) for $299 +- Benefits: + - Verified token status + - Custom branding + - Social links integration + +#### Dextools.io + +Industry standard for Ethereum token trading and analysis. Basic listing is available for free, with token information pulled from CoinGecko. + +- Submit via [Dextools Fast Track Form](https://docs.google.com/forms/d/e/1FAIpQLSd1BAqjAl9nntlS2mOk76tE0Q-dEf-AT1bUblDXikjZ-PNP1Q/formResponse) + +### Security and Audit Platforms + +- Quick Intel: Focuses on rapid security analysis and risk assessment. Popular among traders for quick verification of token safety. + +- GoPlus: Comprehensive security API providing real-time contract analysis. Industry standard for contract verification. + +- Honeypot.is: Specialized in detecting scam tokens and contract malfunction. Essential for proving token tradability. + +- De.Fi Scanner: Modern security platform focusing on DeFi-specific risks and vulnerabilities. Helps establish token credibility. + +#### Verifying The Source Code + +Source code verification is essential for removing "Unverified Contract" warnings that appear on security scanners and DEX aggregators. By publishing your token's source code on Etherscan, you enable public inspection of the contract code and confirm there are no hidden functions. + +/// details | Verifying The Source Code + {type: warning, open: false} +You can verify all of wrapped tokens using this code. Use Compiler version 0.8.20, MIT license, and EVM version paris. Leave all other fields at their default values. + +```sol +// Sources flattened with hardhat v2.22.12 https://hardhat.org + +// SPDX-License-Identifier: MIT + +// File @openzeppelin/contracts/interfaces/draft-IERC6093.sol@v5.0.2 + +// Original license: SPDX_License_Identifier: MIT +// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol) +pragma solidity ^0.8.20; + +/** + * @dev Standard ERC20 Errors + * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens. + */ +interface IERC20Errors { + /** + * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers. + * @param sender Address whose tokens are being transferred. + * @param balance Current balance for the interacting account. + * @param needed Minimum amount required to perform a transfer. + */ + error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed); + + /** + * @dev Indicates a failure with the token `sender`. Used in transfers. + * @param sender Address whose tokens are being transferred. + */ + error ERC20InvalidSender(address sender); + + /** + * @dev Indicates a failure with the token `receiver`. Used in transfers. + * @param receiver Address to which tokens are being transferred. + */ + error ERC20InvalidReceiver(address receiver); + + /** + * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers. + * @param spender Address that may be allowed to operate on tokens without being their owner. + * @param allowance Amount of tokens a `spender` is allowed to operate with. + * @param needed Minimum amount required to perform a transfer. + */ + error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed); + + /** + * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. + * @param approver Address initiating an approval operation. + */ + error ERC20InvalidApprover(address approver); + + /** + * @dev Indicates a failure with the `spender` to be approved. Used in approvals. + * @param spender Address that may be allowed to operate on tokens without being their owner. + */ + error ERC20InvalidSpender(address spender); +} + +/** + * @dev Standard ERC721 Errors + * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens. + */ +interface IERC721Errors { + /** + * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20. + * Used in balance queries. + * @param owner Address of the current owner of a token. + */ + error ERC721InvalidOwner(address owner); + + /** + * @dev Indicates a `tokenId` whose `owner` is the zero address. + * @param tokenId Identifier number of a token. + */ + error ERC721NonexistentToken(uint256 tokenId); + + /** + * @dev Indicates an error related to the ownership over a particular token. Used in transfers. + * @param sender Address whose tokens are being transferred. + * @param tokenId Identifier number of a token. + * @param owner Address of the current owner of a token. + */ + error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner); + + /** + * @dev Indicates a failure with the token `sender`. Used in transfers. + * @param sender Address whose tokens are being transferred. + */ + error ERC721InvalidSender(address sender); + + /** + * @dev Indicates a failure with the token `receiver`. Used in transfers. + * @param receiver Address to which tokens are being transferred. + */ + error ERC721InvalidReceiver(address receiver); + + /** + * @dev Indicates a failure with the `operator`’s approval. Used in transfers. + * @param operator Address that may be allowed to operate on tokens without being their owner. + * @param tokenId Identifier number of a token. + */ + error ERC721InsufficientApproval(address operator, uint256 tokenId); + + /** + * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. + * @param approver Address initiating an approval operation. + */ + error ERC721InvalidApprover(address approver); + + /** + * @dev Indicates a failure with the `operator` to be approved. Used in approvals. + * @param operator Address that may be allowed to operate on tokens without being their owner. + */ + error ERC721InvalidOperator(address operator); +} + +/** + * @dev Standard ERC1155 Errors + * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens. + */ +interface IERC1155Errors { + /** + * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers. + * @param sender Address whose tokens are being transferred. + * @param balance Current balance for the interacting account. + * @param needed Minimum amount required to perform a transfer. + * @param tokenId Identifier number of a token. + */ + error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId); + + /** + * @dev Indicates a failure with the token `sender`. Used in transfers. + * @param sender Address whose tokens are being transferred. + */ + error ERC1155InvalidSender(address sender); + + /** + * @dev Indicates a failure with the token `receiver`. Used in transfers. + * @param receiver Address to which tokens are being transferred. + */ + error ERC1155InvalidReceiver(address receiver); + + /** + * @dev Indicates a failure with the `operator`’s approval. Used in transfers. + * @param operator Address that may be allowed to operate on tokens without being their owner. + * @param owner Address of the current owner of a token. + */ + error ERC1155MissingApprovalForAll(address operator, address owner); + + /** + * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. + * @param approver Address initiating an approval operation. + */ + error ERC1155InvalidApprover(address approver); + + /** + * @dev Indicates a failure with the `operator` to be approved. Used in approvals. + * @param operator Address that may be allowed to operate on tokens without being their owner. + */ + error ERC1155InvalidOperator(address operator); + + /** + * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation. + * Used in batch transfers. + * @param idsLength Length of the array of token identifiers + * @param valuesLength Length of the array of token amounts + */ + error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength); +} + + +// File @openzeppelin/contracts/token/ERC20/IERC20.sol@v5.0.2 + +// Original license: SPDX_License_Identifier: MIT +// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol) + +pragma solidity ^0.8.20; + +/** + * @dev Interface of the ERC20 standard as defined in the EIP. + */ +interface IERC20 { + /** + * @dev Emitted when `value` tokens are moved from one account (`from`) to + * another (`to`). + * + * Note that `value` may be zero. + */ + event Transfer(address indexed from, address indexed to, uint256 value); + + /** + * @dev Emitted when the allowance of a `spender` for an `owner` is set by + * a call to {approve}. `value` is the new allowance. + */ + event Approval(address indexed owner, address indexed spender, uint256 value); + + /** + * @dev Returns the value of tokens in existence. + */ + function totalSupply() external view returns (uint256); + + /** + * @dev Returns the value of tokens owned by `account`. + */ + function balanceOf(address account) external view returns (uint256); + + /** + * @dev Moves a `value` amount of tokens from the caller's account to `to`. + * + * Returns a boolean value indicating whether the operation succeeded. + * + * Emits a {Transfer} event. + */ + function transfer(address to, uint256 value) external returns (bool); + + /** + * @dev Returns the remaining number of tokens that `spender` will be + * allowed to spend on behalf of `owner` through {transferFrom}. This is + * zero by default. + * + * This value changes when {approve} or {transferFrom} are called. + */ + function allowance(address owner, address spender) external view returns (uint256); + + /** + * @dev Sets a `value` amount of tokens as the allowance of `spender` over the + * caller's tokens. + * + * Returns a boolean value indicating whether the operation succeeded. + * + * IMPORTANT: Beware that changing an allowance with this method brings the risk + * that someone may use both the old and the new allowance by unfortunate + * transaction ordering. One possible solution to mitigate this race + * condition is to first reduce the spender's allowance to 0 and set the + * desired value afterwards: + * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 + * + * Emits an {Approval} event. + */ + function approve(address spender, uint256 value) external returns (bool); + + /** + * @dev Moves a `value` amount of tokens from `from` to `to` using the + * allowance mechanism. `value` is then deducted from the caller's + * allowance. + * + * Returns a boolean value indicating whether the operation succeeded. + * + * Emits a {Transfer} event. + */ + function transferFrom(address from, address to, uint256 value) external returns (bool); +} + + +// File @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol@v5.0.2 + +// Original license: SPDX_License_Identifier: MIT +// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol) + +pragma solidity ^0.8.20; + +/** + * @dev Interface for the optional metadata functions from the ERC20 standard. + */ +interface IERC20Metadata is IERC20 { + /** + * @dev Returns the name of the token. + */ + function name() external view returns (string memory); + + /** + * @dev Returns the symbol of the token. + */ + function symbol() external view returns (string memory); + + /** + * @dev Returns the decimals places of the token. + */ + function decimals() external view returns (uint8); +} + + +// File @openzeppelin/contracts/utils/Context.sol@v5.0.2 + +// Original license: SPDX_License_Identifier: MIT +// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol) + +pragma solidity ^0.8.20; + +/** + * @dev Provides information about the current execution context, including the + * sender of the transaction and its data. While these are generally available + * via msg.sender and msg.data, they should not be accessed in such a direct + * manner, since when dealing with meta-transactions the account sending and + * paying for execution may not be the actual sender (as far as an application + * is concerned). + * + * This contract is only required for intermediate, library-like contracts. + */ +abstract contract Context { + function _msgSender() internal view virtual returns (address) { + return msg.sender; + } + + function _msgData() internal view virtual returns (bytes calldata) { + return msg.data; + } + + function _contextSuffixLength() internal view virtual returns (uint256) { + return 0; + } +} + + +// File @openzeppelin/contracts/token/ERC20/ERC20.sol@v5.0.2 + +// Original license: SPDX_License_Identifier: MIT +// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol) + +pragma solidity ^0.8.20; + + + + +/** + * @dev Implementation of the {IERC20} interface. + * + * This implementation is agnostic to the way tokens are created. This means + * that a supply mechanism has to be added in a derived contract using {_mint}. + * + * TIP: For a detailed writeup see our guide + * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How + * to implement supply mechanisms]. + * + * The default value of {decimals} is 18. To change this, you should override + * this function so it returns a different value. + * + * We have followed general OpenZeppelin Contracts guidelines: functions revert + * instead returning `false` on failure. This behavior is nonetheless + * conventional and does not conflict with the expectations of ERC20 + * applications. + * + * Additionally, an {Approval} event is emitted on calls to {transferFrom}. + * This allows applications to reconstruct the allowance for all accounts just + * by listening to said events. Other implementations of the EIP may not emit + * these events, as it isn't required by the specification. + */ +abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors { + mapping(address account => uint256) private _balances; + + mapping(address account => mapping(address spender => uint256)) private _allowances; + + uint256 private _totalSupply; + + string private _name; + string private _symbol; + + /** + * @dev Sets the values for {name} and {symbol}. + * + * All two of these values are immutable: they can only be set once during + * construction. + */ + constructor(string memory name_, string memory symbol_) { + _name = name_; + _symbol = symbol_; + } + + /** + * @dev Returns the name of the token. + */ + function name() public view virtual returns (string memory) { + return _name; + } + + /** + * @dev Returns the symbol of the token, usually a shorter version of the + * name. + */ + function symbol() public view virtual returns (string memory) { + return _symbol; + } + + /** + * @dev Returns the number of decimals used to get its user representation. + * For example, if `decimals` equals `2`, a balance of `505` tokens should + * be displayed to a user as `5.05` (`505 / 10 ** 2`). + * + * Tokens usually opt for a value of 18, imitating the relationship between + * Ether and Wei. This is the default value returned by this function, unless + * it's overridden. + * + * NOTE: This information is only used for _display_ purposes: it in + * no way affects any of the arithmetic of the contract, including + * {IERC20-balanceOf} and {IERC20-transfer}. + */ + function decimals() public view virtual returns (uint8) { + return 18; + } + + /** + * @dev See {IERC20-totalSupply}. + */ + function totalSupply() public view virtual returns (uint256) { + return _totalSupply; + } + + /** + * @dev See {IERC20-balanceOf}. + */ + function balanceOf(address account) public view virtual returns (uint256) { + return _balances[account]; + } + + /** + * @dev See {IERC20-transfer}. + * + * Requirements: + * + * - `to` cannot be the zero address. + * - the caller must have a balance of at least `value`. + */ + function transfer(address to, uint256 value) public virtual returns (bool) { + address owner = _msgSender(); + _transfer(owner, to, value); + return true; + } + + /** + * @dev See {IERC20-allowance}. + */ + function allowance(address owner, address spender) public view virtual returns (uint256) { + return _allowances[owner][spender]; + } + + /** + * @dev See {IERC20-approve}. + * + * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on + * `transferFrom`. This is semantically equivalent to an infinite approval. + * + * Requirements: + * + * - `spender` cannot be the zero address. + */ + function approve(address spender, uint256 value) public virtual returns (bool) { + address owner = _msgSender(); + _approve(owner, spender, value); + return true; + } + + /** + * @dev See {IERC20-transferFrom}. + * + * Emits an {Approval} event indicating the updated allowance. This is not + * required by the EIP. See the note at the beginning of {ERC20}. + * + * NOTE: Does not update the allowance if the current allowance + * is the maximum `uint256`. + * + * Requirements: + * + * - `from` and `to` cannot be the zero address. + * - `from` must have a balance of at least `value`. + * - the caller must have allowance for ``from``'s tokens of at least + * `value`. + */ + function transferFrom(address from, address to, uint256 value) public virtual returns (bool) { + address spender = _msgSender(); + _spendAllowance(from, spender, value); + _transfer(from, to, value); + return true; + } + + /** + * @dev Moves a `value` amount of tokens from `from` to `to`. + * + * This internal function is equivalent to {transfer}, and can be used to + * e.g. implement automatic token fees, slashing mechanisms, etc. + * + * Emits a {Transfer} event. + * + * NOTE: This function is not virtual, {_update} should be overridden instead. + */ + function _transfer(address from, address to, uint256 value) internal { + if (from == address(0)) { + revert ERC20InvalidSender(address(0)); + } + if (to == address(0)) { + revert ERC20InvalidReceiver(address(0)); + } + _update(from, to, value); + } + + /** + * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from` + * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding + * this function. + * + * Emits a {Transfer} event. + */ + function _update(address from, address to, uint256 value) internal virtual { + if (from == address(0)) { + // Overflow check required: The rest of the code assumes that totalSupply never overflows + _totalSupply += value; + } else { + uint256 fromBalance = _balances[from]; + if (fromBalance < value) { + revert ERC20InsufficientBalance(from, fromBalance, value); + } + unchecked { + // Overflow not possible: value <= fromBalance <= totalSupply. + _balances[from] = fromBalance - value; + } + } + + if (to == address(0)) { + unchecked { + // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply. + _totalSupply -= value; + } + } else { + unchecked { + // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256. + _balances[to] += value; + } + } + + emit Transfer(from, to, value); + } + + /** + * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0). + * Relies on the `_update` mechanism + * + * Emits a {Transfer} event with `from` set to the zero address. + * + * NOTE: This function is not virtual, {_update} should be overridden instead. + */ + function _mint(address account, uint256 value) internal { + if (account == address(0)) { + revert ERC20InvalidReceiver(address(0)); + } + _update(address(0), account, value); + } + + /** + * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply. + * Relies on the `_update` mechanism. + * + * Emits a {Transfer} event with `to` set to the zero address. + * + * NOTE: This function is not virtual, {_update} should be overridden instead + */ + function _burn(address account, uint256 value) internal { + if (account == address(0)) { + revert ERC20InvalidSender(address(0)); + } + _update(account, address(0), value); + } + + /** + * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens. + * + * This internal function is equivalent to `approve`, and can be used to + * e.g. set automatic allowances for certain subsystems, etc. + * + * Emits an {Approval} event. + * + * Requirements: + * + * - `owner` cannot be the zero address. + * - `spender` cannot be the zero address. + * + * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument. + */ + function _approve(address owner, address spender, uint256 value) internal { + _approve(owner, spender, value, true); + } + + /** + * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event. + * + * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by + * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any + * `Approval` event during `transferFrom` operations. + * + * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to + * true using the following override: + * ``` + * function _approve(address owner, address spender, uint256 value, bool) internal virtual override { + * super._approve(owner, spender, value, true); + * } + * ``` + * + * Requirements are the same as {_approve}. + */ + function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual { + if (owner == address(0)) { + revert ERC20InvalidApprover(address(0)); + } + if (spender == address(0)) { + revert ERC20InvalidSpender(address(0)); + } + _allowances[owner][spender] = value; + if (emitEvent) { + emit Approval(owner, spender, value); + } + } + + /** + * @dev Updates `owner` s allowance for `spender` based on spent `value`. + * + * Does not update the allowance value in case of infinite allowance. + * Revert if not enough allowance is available. + * + * Does not emit an {Approval} event. + */ + function _spendAllowance(address owner, address spender, uint256 value) internal virtual { + uint256 currentAllowance = allowance(owner, spender); + if (currentAllowance != type(uint256).max) { + if (currentAllowance < value) { + revert ERC20InsufficientAllowance(spender, currentAllowance, value); + } + unchecked { + _approve(owner, spender, currentAllowance - value, false); + } + } + } +} + + +// File contracts/rsADA.sol + +// Original license: SPDX_License_Identifier: MIT +pragma solidity ^0.8.20; + +contract rsADA is ERC20 { + constructor() ERC20("rsADA", "rsADA") { + _mint(msg.sender, 45000000000000000); + } + + function decimals() public view virtual override returns (uint8) { + return 6; + } +} + + +// File contracts/rsBTC.sol + +// Original license: SPDX_License_Identifier: MIT +pragma solidity ^0.8.20; + +contract rsBTC is ERC20 { + constructor() ERC20("rsBTC", "rsBTC") { + _mint(msg.sender, 2100000000000000); + } + + function decimals() public view virtual override returns (uint8) { + return 8; + } +} + + +// File contracts/rsBTN.sol + +// Original license: SPDX_License_Identifier: MIT +pragma solidity ^0.8.20; + +contract rsBTN is ERC20 { + constructor() ERC20("rsBTN", "rsBTN") { + _mint(msg.sender, 12585000000000); + } + + function decimals() public view virtual override returns (uint8) { + return 6; + } +} + + +// File contracts/rsCOMET.sol + +// Original license: SPDX_License_Identifier: MIT +pragma solidity ^0.8.20; + +contract rsCOMET is ERC20 { + constructor() ERC20("rsCOMET", "rsCOMET") { + _mint(msg.sender, 21000000000); + } + + function decimals() public view virtual override returns (uint8) { + return 0; + } +} + + +// File contracts/rsERG.sol + +// Original license: SPDX_License_Identifier: MIT +pragma solidity ^0.8.20; + +contract rsERG is ERC20 { + constructor() ERC20("rsERG", "rsERG") { + _mint(msg.sender, 97739924500000000); + } + + function decimals() public view virtual override returns (uint8) { + return 9; + } +} + + +// File contracts/rsHOSKY.sol + +// Original license: SPDX_License_Identifier: MIT +pragma solidity ^0.8.20; + +contract rsHOSKY is ERC20 { + constructor() ERC20("rsHOSKY", "rsHOSKY") { + _mint(msg.sender, 1000000000000001); + } + + function decimals() public view virtual override returns (uint8) { + return 0; + } +} + + +// File contracts/rsHUNT.sol + +// Original license: SPDX_License_Identifier: MIT +pragma solidity ^0.8.20; + +contract rsHUNT is ERC20 { + constructor() ERC20("rsHUNT", "rsHUNT") { + _mint(msg.sender, 100000000000000); + } + + function decimals() public view virtual override returns (uint8) { + return 6; + } +} + + +// File contracts/rsIAG.sol + +// Original license: SPDX_License_Identifier: MIT +pragma solidity ^0.8.20; + +contract rsIAG is ERC20 { + constructor() ERC20("rsIAG", "rsIAG") { + _mint(msg.sender, 1000000000000000); + } + + function decimals() public view virtual override returns (uint8) { + return 6; + } +} + + +// File contracts/rsINDY.sol + +// Original license: SPDX_License_Identifier: MIT +pragma solidity ^0.8.20; + +contract rsINDY is ERC20 { + constructor() ERC20("rsINDY", "rsINDY") { + _mint(msg.sender, 35000000000000); + } + + function decimals() public view virtual override returns (uint8) { + return 6; + } +} + + +// File contracts/rsLQ.sol + +// Original license: SPDX_License_Identifier: MIT +pragma solidity ^0.8.20; + +contract rsLQ is ERC20 { + constructor() ERC20("rsLQ", "rsLQ") { + _mint(msg.sender, 21000000000000); + } + + function decimals() public view virtual override returns (uint8) { + return 6; + } +} + + +// File contracts/rsMIN.sol + +// Original license: SPDX_License_Identifier: MIT +pragma solidity ^0.8.20; + +contract rsMIN is ERC20 { + constructor() ERC20("rsMIN", "rsMIN") { + _mint(msg.sender, 3000000000000000); + } + + function decimals() public view virtual override returns (uint8) { + return 6; + } +} + + +// File contracts/rsOPTIM.sol + +// Original license: SPDX_License_Identifier: MIT +pragma solidity ^0.8.20; + +contract rsOPTIM is ERC20 { + constructor() ERC20("rsOPTIM", "rsOPTIM") { + _mint(msg.sender, 100000000000000); + } + + function decimals() public view virtual override returns (uint8) { + return 6; + } +} + + +// File contracts/rsRSN.sol + +// Original license: SPDX_License_Identifier: MIT +pragma solidity ^0.8.20; + +contract rsRSN is ERC20 { + constructor() ERC20("rsRSN", "rsRSN") { + _mint(msg.sender, 1000000000000); + } + + function decimals() public view virtual override returns (uint8) { + return 3; + } +} + + +// File contracts/rsSigRSV.sol + +// Original license: SPDX_License_Identifier: MIT +pragma solidity ^0.8.20; + +contract rsSigRSV is ERC20 { + constructor() ERC20("rsSigRSV", "rsSigRSV") { + _mint(msg.sender, 10000000000001); + } + + function decimals() public view virtual override returns (uint8) { + return 0; + } +} + + +// File contracts/rsSigUSD.sol + +// Original license: SPDX_License_Identifier: MIT +pragma solidity ^0.8.20; + +contract rsSigUSD is ERC20 { + constructor() ERC20("rsSigUSD", "rsSigUSD") { + _mint(msg.sender, 10000000000001); + } + + function decimals() public view virtual override returns (uint8) { + return 2; + } +} + + +// File contracts/rsSNEK.sol + +// Original license: SPDX_License_Identifier: MIT +pragma solidity ^0.8.20; + +contract rsSNEK is ERC20 { + constructor() ERC20("rsSNEK", "rsSNEK") { + _mint(msg.sender, 76715880000); + } + + function decimals() public view virtual override returns (uint8) { + return 0; + } +} + + +// File contracts/rsSPF.sol + +// Original license: SPDX_License_Identifier: MIT +pragma solidity ^0.8.20; + +contract rsSPF is ERC20 { + constructor() ERC20("rsSPF", "rsSPF") { + _mint(msg.sender, 1000000000000000); + } + + function decimals() public view virtual override returns (uint8) { + return 6; + } +} + + +// File contracts/rsSPLASH.sol + +// Original license: SPDX_License_Identifier: MIT +pragma solidity ^0.8.20; + +contract rsSPLASH is ERC20 { + constructor() ERC20("rsSPLASH", "rsSPLASH") { + _mint(msg.sender, 99999999996576); + } + + function decimals() public view virtual override returns (uint8) { + return 6; + } +} + + +// File contracts/rsSUNDAE.sol + +// Original license: SPDX_License_Identifier: MIT +pragma solidity ^0.8.20; + +contract rsSUNDAE is ERC20 { + constructor() ERC20("rsSUNDAE", "rsSUNDAE") { + _mint(msg.sender, 2000000000000000); + } + + function decimals() public view virtual override returns (uint8) { + return 6; + } +} + + +// File contracts/rsVYFI.sol + +// Original license: SPDX_License_Identifier: MIT +pragma solidity ^0.8.20; + +contract rsVYFI is ERC20 { + constructor() ERC20("rsVYFI", "rsVYFI") { + _mint(msg.sender, 450000000000000); + } + + function decimals() public view virtual override returns (uint8) { + return 6; + } +} +``` +/// +## Phase 3: Network-Specific Integrations + +### Ethereum Network + +This section covers the main priorities for Ethereum integration which are those [Trading Analytics Platforms](#trading-analytics-platforms) mentioned above and Uniswap. Due to Ethereum's massive DeFi ecosystem, there are hundreds of additional DEXes, lending protocols, yield farms, and other DeFi platforms that tokens could potentially integrate with. Track key platforms via [DeFiLlama's Ethereum section](https://defillama.com/chain/Ethereum). #### Uniswap +The largest DEX on Ethereum. Essential for any ETH-based token. + +- Submit to [Uniswap Default Token List](https://github.com/Uniswap/default-token-list/issues/new?assignees=&labels=token+request&template=token-request.md&title=Add+%7BTOKEN_SYMBOL%7D%3A+%7BTOKEN_NAME%7D) +- Monitor gas fees via [ETH Gas Station](https://ethgasstation.info/) + +#### Coinbase Wallet +Most popular non-custodial wallet in the US. Listing here provides significant mainstream exposure. -1. **Liquidity Pool Setup**: Refer to the [Liquidity Guide](rsERGLP.md) for detailed steps on adding liquidity. Since gas fees vary significantly, check real-time gas prices on [ETH Gas Station](https://ethgasstation.info/) to avoid excessive costs. -2. **Token Request on Uniswap**: Submit an issue to the [Uniswap Default Token List](https://github.com/Uniswap/default-token-list/issues/new?assignees=&labels=token+request&template=token-request.md&title=Add+%7BTOKEN_SYMBOL%7D%3A+%7BTOKEN_NAME%7D) GitHub repository. Ensure token details match the contract specifications. +### Cardano Network -#### Ethereum Analytics Platforms +Track platforms via [DeFiLlama's Cardano section](https://defillama.com/chain/Cardano) -Analytics platforms like Dexscreener and Dextools.io provide real-time data tracking for Ethereum-based tokens, enhancing visibility and attracting a larger user base: +#### Taptools.io +Premier analytics platform for Cardano assets. Essential for Cardano token visibility. -- **Dexscreener**: Purchase [Enhanced Token Info](https://marketplace.dexscreener.com/product/token-info) for $299 to improve your token’s profile with additional metrics, links, and a more robust display. -- **Dextools.io Fast Track**: For quicker listing, use the Fast Track option by paying with $DEXT, $ETH, or $BNB via the [Dextools Fast Track Form](https://docs.google.com/forms/d/e/1FAIpQLSd1BAqjAl9nntlS2mOk76tE0Q-dEf-AT1bUblDXikjZ-PNP1Q/formResponse). +#### Cardanoscan +Main block explorer for Cardano. View transactions at [Cardanoscan](https://cardanoscan.io/). Crucial for transaction verification and tracking. ---- +#### AdaPulse +News and analytics platform focusing on Cardano ecosystem projects. -### Cardano +#### DEX Platforms +- Splash: Our recommended DEX for initial liquidity and trading +- View all Cardano DEXes ranked by TVL at [DeFiLlama's Cardano DEX Rankings](https://defillama.com/chain/Cardano) -Integrating with Cardano platforms extends your token's reach within the Cardano ecosystem: +### DeFi Ecosystem -#### Taptools +- Liqwid: Decentralised lending protocol -Taptools tracks Cardano assets and supports token analytics. To list your bridged ERG token, reach out directly to Taptools through their website for specific listing steps. +### Ergo Ecosystem -#### Cardano DEXs +#### Core Integrations -DEXs like Splash, Minswap, and WingRiders support bridged tokens. Visit [DeFiLlama’s Cardano section](https://defillama.com/chain/Cardano) to explore these DEXs and contact each platform individually for listing details. +- Decentralised exchange: [ErgoDEX](https://dex.ergo.io/) and [MewMart](https://mart.mewfinance.com/) +- ErgoTipperBot: Social tipping service, helps with community engagement. Tip your rsToken in Telegram, Discord, bsky, Reddit, and more. + - To add a token to the list, [simply create a PR that adds your token to the list](https://github.com/Luivatra/ergotipper-tokens#supported-tokens-in-the-ergotipper-bot). +- SigmaFi PR: Decentralised bonds + - [Add as a verified token](https://github.com/capt-nemo429/sigmafi-ui/pull/14) +- DuckPools: DAO-governed liquidity platform + - Requires DAO vote +- ErgoMixer: Can mix any rsToken by default, but requires a custom PR to have the name of your rsToken in the UI. (TBC) +- TradeHouse: Decentralised orderbook for Ergo assets, -#### Cardano Analytics Platforms +## Best Practices -Cardano-focused analytics platforms can improve visibility by providing Cardano-based metrics and trading data for your token. -1. **Taptools.io** -2. **Cardanoscan**: Display real-time transaction data for bridged tokens on [Cardanoscan](https://cardanoscan.io/). -3. **AdaPulse**: AdaPulse covers Cardano asset updates and offers project-specific data for listed tokens. +### Monitoring +- Use ETH Gas Station for optimizing Ethereum transactions +- Monitor platform performance via DeFiLlama (most comprehensive DeFi TVL tracker) ---- +### Gas Fee Management +Track real-time gas prices on [ETH Gas Station](https://ethgasstation.info/) to: -Following these steps will help establish your bridged ERG token on various networks, ensuring broad visibility across DeFi ecosystems. \ No newline at end of file +- Optimize transaction timing +- Reduce costs for users +- Plan liquidity operations diff --git a/mkdocs.yml b/mkdocs.yml index 5c88ef8e..5ce8371e 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -440,6 +440,9 @@ nav: - Data Inputs: dev/protocol/tx/read-only-inputs.md - Fees: dev/protocol/tx/min-fee.md - Unified Transactions: dev/protocol/tx/unified.md + - Babel Fees: + - dev/protocol/tx/babel-fees.md + - Babel Fees Plugin: dev/protocol/tx/babel-fleet.md - Resources: - Standards: - Babel Fees: dev/protocol/tx/babel-fees.md