<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vega Engineering on Medium]]></title>
        <description><![CDATA[Stories by Vega Engineering on Medium]]></description>
        <link>https://medium.com/@vegaengineering?source=rss-5fe9ae9c779f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*nDoeTqER-eMTesA2Dmwg6Q.jpeg</url>
            <title>Stories by Vega Engineering on Medium</title>
            <link>https://medium.com/@vegaengineering?source=rss-5fe9ae9c779f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:46:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vegaengineering/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Vega ERC20 Bridge]]></title>
            <link>https://blog.vega.xyz/vega-erc20-bridge-331a5235efa2?source=rss-5fe9ae9c779f------2</link>
            <guid isPermaLink="false">https://medium.com/p/331a5235efa2</guid>
            <category><![CDATA[vega-101]]></category>
            <dc:creator><![CDATA[Vega Engineering]]></dc:creator>
            <pubDate>Tue, 26 Jan 2021 12:07:41 GMT</pubDate>
            <atom:updated>2021-08-19T14:53:58.481Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_NIimcOA9-e0A26kyHNXQ.jpeg" /></figure><p>“A blockchain bridge provides a connection that allows for the transfer of tokens or data between two different blockchain ecosystems.” -Jagdeep Sidhu</p><p>“Cry a river. Build a bridge. Get over it.” -Unknown</p><p>The Ethereum/Vega bridge enables the noncustodial, fully-decentralized management of Ethereum-based assets into and out of the Vega network. That’s a lot to unpack, but it means that this bridge allows users of Vega to deposit and withdraw Ethereum-based tokens to and from their Vega account. There are no assets native to the Vega network, so all assets used to settle markets are, by necessity, bridged in from other blockchains. The first bridge to be released is specifically for Ethereum-based ERC20 tokens, the most established token standard in all of cryptocurrency. The ERC20 bridge immediately gives markets on Vega access to all of the assets that make up the core of decentralized finance (DeFi). As of the time of writing, Tether, Dai, and USDC stable tokens alone make up 21 billion dollars, add in Ether itself (via wETH) and Wrapped Bitcoin and that number balloons to 182 billion dollars. The non-crypto world is waking up to what is possible and mass adoption will bring an absolute explosion of value stored on-chain, all of which can flow unimpeded through Vega’s network.</p><pre>╔═══════════╦═════════════════════╗<br>║   Token   ║ Total Value (USD)   ║<br>╠═══════════╬═════════════════════╣<br>║ Ethereum  ║ $156,847,068,812.00 ║<br>║ WBTC      ║ $4,059,245,408.00   ║<br>║ Tether    ║ $14,739,827,859.00  ║<br>║ Dai       ║ $1,384,792,599.00   ║<br>║ USDC      ║ $5,145,876,891.00   ║<br>║ Total     ║ $182,176,811,569.00 ║<br>╚═══════════╩═════════════════════╝</pre><pre>-Etherscan 19Jan2021</pre><p><a href="https://cointelegraph.com/explained/blockchain-bridges-explained">Jagdeep’s article on Blockchain Bridges is worth a read.</a></p><h3>Money Lego: The Blocks</h3><p>The ERC20 bridge consists of 3 Main smart contracts and an event queuing service. The smart contracts: Multisig Control, ERC20 Bridge Logic, and ERC20 Asset Pool, manage all of Vega’s Ethereum-side assets and security.</p><p>First is Multisig Control, which is the root of all Vega to Ethereum security. Any smart contracts that properly use the “verify signatures” check correctly are completely controlled by the Vega network itself and fully out of the control of any admin or custodian. This is accomplished by submitting validator-signed orders from a greater-than-threshold number of validators.</p><p>Next is the ERC20 Bridge Logic contract. This smart contract uses Multisig Control for security and contains deposit and withdrawal functions that work with any listed asset that is a functional ERC20. This contract also contains the functions necessary to list and remove assets and set min/max deposits on a per-asset basis. Since all of the security is governed by Multisig Control, valid governance decisions are the only way to change settings, and all validators must agree before issuing a withdrawal order. This contract is by far the most complex and thus has the highest potential for errors or exploits. To mitigate this problem, all assets deposited with the “deposit asset” function are atomically (in same tx) forwarded to the Asset Pool. This allows the Vega network to redeploy the bridge logic and assign it to the asset pool. This brings the major advantage that assets don’t need to be migrated when the bridge needs to change which is expensive, time consuming, and potentially dangerous.</p><p>Last up is of course the Asset Pool itself. This smart contract is the receiver for all deposits and was designed to be as simple as possible. All it does it send assets to where it’s assigned Bridge Logic tells it to. If an error is found in the bridge logic, Vega governance can invalidate the bridge logic, preserving the assets until such time that a new bridge logic can be voted in.</p><p>As is standard practice when programming smart contracts, any time something of note happens on the bridge, say a deposit or change of voting threshold, an event is raised and forever shows up immutably in the Ethereum blockchain. An Event Queue then finds and propagates these events to the Vega Network where each validator individually confirms that each event does indeed show up on-chain. The event then gets recorded to the Vega chain and the loop is complete.</p><h3>How It Works</h3><p>When designing the ERC20 bridge, great care was taken to maximize security while still maintaining a simple, familiar workflow that is in-line with the cryptocurrency and DeFi products and systems that everyone is used to, with some notable twists. As with more complex DeFi products such as Uniswap or Balancer, there will often be a UI between the end user and the contract functions. On the other hand, the functions are still simple enough that someone can use a command line wallet or go to <a href="https://www.myetherwallet.com/">https://www.myetherwallet.com/</a> (.com anything else is phishing) and easily make a deposit or withdrawal. We have manual instructions out now for testnet <a href="https://github.com/vegaprotocol/Public_Test_Bridge_Tools">here</a>.</p><h4>Deposits</h4><p>Depositing a listed ERC20 token is a simple process that follows with what DeFi and token users are used to. First, the user “approves” the bridge smart contract to move the tokens, then they run “deposit asset” with their vega public key and how much they want to deposit as parameters. If they have a sufficient balance, and have approved, then the tokens will move to the Asset Pool and an “Asset Deposited” event will be emitted to the Ethereum blockchain. This will be picked up by the Event Queue and propagated to the Vega network. Once the event has been seen and the block has been sealed, the user is credited with the deposit. The biggest bottleneck here is Ethereum’s block speed/cost. Once mined on Ethereum the deposit is nearly instant… especially in ETH terms.</p><h4>Withdrawals</h4><p>Withdrawals are a bit more complicated since they use the multisig control system mentioned above. A user starts a withdrawal by making a “prepare withdrawal” request to the Vega network. This can be done with the API and soon Vega Console, and it triggers the Vega validator nodes to validate that that user has the balance available. The network locks those funds and then signs a withdrawal order consisting of the target ethereum address, the ERC20 token contract address, the amount to withdraw, an expiration time, and a unique number that protects against replay attacks. The withdrawal expiration provides certainty that funds can be unlocked if the withdrawal isn’t executed. All of this is hashed and signed then the signatures are gathered and bundled and given to the user. Once the user has the signed withdrawal order, they use those as parameters for the “withdrawal asset” function. While this seems much more complicated, it’s fewer (and less esoteric) parameters than many of the current vesting/yield farming DeFi contracts that have had minimal problems with adoption.</p><h3>Decentralized Noncustody</h3><p>When planning the bridge strategy a problem quickly arose: how does Vega, a fully decentralized network, effect change on Ethereum contracts without owning any Ether for gas fees? The first attempt was a standard multisig contract, but this made the gas problem even worse as each validator would have to have gas and run many transactions. Even batched this made the bridge prohibitively expensive. The next thing researched was various Threshold Signature Schemes (TSS) but each of those came with either speed bottlenecks or simple DOS attack vectors, as well as adding a processing burden that could be a performance bottleneck.</p><p>The solution that was settled on is a bearer bond-type system where Vega network issues immutable orders that are then used as parameters to run smart contract functions. Each Vega validator node has a registered and approved Ethereum address that they use to sign the multisig commands. This allows for the interested party to pay the Ethereum network fees, rather than the network itself. There is no individual authority or custodian that can control a user’s funds, only the users themselves can cause the protocol to issue a withdrawal request.</p><p>Each Vega validator has access to it’s own Ethereum node to independently verify on-chain events raised by network-controlled smart contracts. The security of Vega is the security of the bridge. Vega’s decentralized security relies on consensus between multiple validator nodes, these same nodes are in control of all funds in the system. This system ensures that all funds deposited on Ethereum are directly linked to funds in Vega; it’s a zero-sum, closed system.</p><h3>It’s Always S̶u̶n̶n̶y̶ Better With Pictures</h3><p>They say a picture is worth a thousand words, well this post is well over a thousand words at this point, so have some pictures:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5QCVyfm03lwLefGN" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2t2BcbWAz72_GwAi" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t64cgy9hkLnUmHPC" /></figure><h3>What Makes Vega Different?</h3><p>Blockchain interoperability has been a common need in cryptocurrency and DeFi and many startups have been created just to tackle that single problem. Rather than rely on one of these bridges from a third party, the decision was made to create a bridge to meet the very specific needs of Vega’s bespoke trading-tuned noncustodial network. To this end, a balance was struck between versatility and simplicity. Many attacks on crypto and DeFi have been accomplished through callbacks and blindly passing along data/commands from trusted third parties. The ability to pass calldata between Vega and Ethereum was ignored in favor of the Command Query Responsibility Segregation pattern (CQRS) along with a restricted command set (deposit, withdrawal, list asset, etc) to allow equal-parts expandability and testability.</p><h3>To Infinity!</h3><p>As mentioned above, the multisig control contract along with the upgradable bridge logic allows Vega’s dev team, as well as the community, to expand and alter functionality as consensus sees fit. To add new Vega-controlled smart contracts, one simply has to (walk into Mordor) implement functions using the Multisig Control pattern, and assign Vega’s currently valid Multisig Control for the “verify signatures” check, and then convince Vega’s community governance to add the features. This expandability will allow Vega to adapt and grow as the DeFi and Ethereum communities mature and develop, as well as allows the community to contribute in a real and meaningful way.</p><p>Ethereum is but one of the multitudes of blockchains that currently exist, and there are many more on the horizon. Now that the ERC20 bridge and supporting systems are in place, the next stop is native Ether. Ether plays very very differently from ERC20 tokens within smart contracts, and thus requires an entirely different codebase. After the native Ether bridge, the goal is Bitcoin native (as opposed to wrapped bitcoin, which is an ERC20), Ripple (XRP), and Dogecoin (DOGE) bridges. Each of these will require much research and will each get individual writeups.</p><h3>Want to learn more? Come play!</h3><p>If you would like some guidance, or to chat about the protocol, ask questions, give feedback, or just hang out, you can join our<a href="https://calendar.google.com/event?action=TEMPLATE&amp;tmeid=MWJrajk0dWN1Z2RpOGVkbW1sNGhpNms2anFfMjAyMDExMjZUMTgwMDAwWiBjX2VsMGE5cW0zdWJlc2Y2NnFzbmxndG1wNzg4QGc&amp;tmsrc=c_el0a9qm3ubesf66qsnlgtmp788%40group.calendar.google.com&amp;scp=ALL"> weekly Testnet jam call</a> or jump onto our <a href="https://vega.xyz/discord">Discord</a> to chat to one of the Vega team.</p><h3>Useful Links:</h3><p><a href="https://github.com/vegaprotocol/go-wallet">Wallet repo</a><br><a href="https://docs.testnet.vega.xyz/">User documentation</a><br><a href="https://community.vega.xyz/c/testnet/">Vega community</a> — testnet thread<br><a href="https://vega.xyz/discord">Vega Discord</a><br><a href="https://calendar.google.com/event?action=TEMPLATE&amp;tmeid=MWJrajk0dWN1Z2RpOGVkbW1sNGhpNms2anFfMjAyMDEyMTdUMTgwMDAwWiBjX2VsMGE5cW0zdWJlc2Y2NnFzbmxndG1wNzg4QGc&amp;tmsrc=c_el0a9qm3ubesf66qsnlgtmp788%40group.calendar.google.com&amp;scp=ALL">Calendar invite to weekly Vega Testnet Jam</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=331a5235efa2" width="1" height="1" alt=""><hr><p><a href="https://blog.vega.xyz/vega-erc20-bridge-331a5235efa2">Vega ERC20 Bridge</a> was originally published in <a href="https://blog.vega.xyz/">Vega Protocol</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The challenge of cross-compiling with go, cgo and xgo]]></title>
            <link>https://blog.vega.xyz/the-challenge-of-cross-compiling-with-go-cgo-and-xgo-a8a3b1aeffc7?source=rss-5fe9ae9c779f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8a3b1aeffc7</guid>
            <category><![CDATA[derivatives]]></category>
            <category><![CDATA[vega-101]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[vega-developer]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <dc:creator><![CDATA[Vega Engineering]]></dc:creator>
            <pubDate>Wed, 10 Jun 2020 14:36:50 GMT</pubDate>
            <atom:updated>2020-06-10T14:42:30.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F5HnNuBRpUlfKDjGhZnv3A.jpeg" /></figure><h3>Cross-Compiling Vega with GO, CGO and XGO</h3><p>Hi, my name is Ashley and I’m part of the core engineering team.</p><p>As we continue developing Vega, we’re obviously thinking ahead to when people around the world will want to run Vega nodes. Not all of them will be running the same hardware and operating systems as we do, and we need to cater for that.</p><p>Rather than having multiple machines, each on different hardware and running a different operating system, and each compiling Vega for their particular hardware and operating system combination, it’s far preferable to choose one combination and compile multiple times in such a way that each resulting program can be run on a particular operating system and hardware combination. This process is called cross-compiling.</p><h4>Enter Golang cross-compiling</h4><p>The Vega core node software is written in <a href="https://golang.org/">Golang</a>, and the helpful Golang developers have done their best to <a href="https://golangcookbook.com/chapters/running/cross-compiling/">make cross-compiling easy</a>.</p><p>To see the impressive variety of supported operating system and hardware combinations, run go tool dist list. The list should include many operating systems (Android, Darwin (MacOSX), Linux, several BSD flavours, and Windows) and several hardware architectures (386, AMD64, ARM, ARM64, and some MIPS flavours).</p><p>It looks like we’re done. Just run GOOS=myOS GOARCH=myCPU go build ./app and go home. And that would be the case, if we didn’t need cgo.</p><h4>Oh, cgo</h4><p><a href="https://golang.org/cmd/cgo/">cgo</a> is used to inject C or C++ code into Golang code. Here’s a simple C example:</p><pre>package main</pre><pre>// #include &lt;stdio.h&gt;<br>//<br>// void sayHi() {<br>// printf(“Hello, embedded C!\n”);<br>// }<br>import “C”</pre><pre>func main() {<br>    C.sayHi()<br>}</pre><p>With Golang code that includes C/C++ code, a C/C++ compiler is needed in addition to the Golang one. Unfortunately, C/C++ compilers are not nearly as friendly with cross-compiling as the Golang one is. A hardware-architecture-specific, operating-system-specific C/C++ compiler is needed for each hardware architecture and operating system combination. Our go build command starts to grow:</p><pre>env \<br>    CGO_ENABLED=1 \<br>    CC=my-OS-specific-C-compiler \<br>    CXX=my-OS-specific-Cplusplus-compiler \<br>    GOOS=myOS \<br>    GOARCH=myCPU \<br>    \<br>    go build ./myapp</pre><p>At this point, you might be wondering why we didn’t consider removing all the C/C++ code from Vega. If only it were so simple! Although Vega itself contains no embedded C or C++ code, it depends on <a href="https://github.com/ethereum/go-ethereum/">go-ethereum</a>, which currently depends on <a href="https://github.com/olebedev/go-duktape/tree/v3">duktape</a>, which needs cgo. There is a <a href="https://github.com/ethereum/go-ethereum/issues/20590">go-ethereum ticket</a> to make duktape an optional dependency, but in the meantime we’re going to need to Deal With It (TM).</p><h4>xgo to the rescue</h4><p>Rather than reinvent the wheel of tracking down and installing a set of C/C++ compilers, a quick online search revealed <a href="https://github.com/karalabe/xgo">xgo</a>, which provides pre-created Docker container images packed full of C and C++ compilers for various hardware architectures and operating systems.</p><p>While our use of private Github dependencies did prevent xgo from working out-of-the-box, a quick look at its <a href="https://github.com/karalabe/xgo/blob/master/docker/base/build.sh">main build script</a> revealed the magic incantations necessary to be able to run a Docker container and compile for Linux and MacOSX. Our build command has grown into a docker run command plus go build command inside.</p><pre>docker run — rm -ti \<br>    -v &quot;$HOME/.ssh:/root/.ssh&quot; \<br>    -v &quot;$HOME/containergo/cache:/go/cache&quot; \<br>    -v &quot;$HOME/containergo/pkg:/go/pkg&quot; \<br>    -v &quot;$PWD:/go/src/project&quot; \<br>    -w /go/src/project \<br>    -e CGO_ENABLED=1 \<br>    -e CC=my-OS-specific-C-compiler \<br>    -e CXX=my-OS-specific-Cplusplus-compiler \<br>    -e GOOS=myOS \<br>    -e GOARCH=myCPU \<br>    -e GOCACHE=/go/cache \<br>    --entrypoint go \<br>    karalabe/xgo-latest:latest \<br>        build ./myapp</pre><p>Notably absent from the list of working operating systems was Windows. No amount of tweaking code, or dependency versions, or Go build options, was able to get the compilation to work. All I got was errors like “oledlg.h:428:3: error: unknown type name &#39;interface&#39;”. Online searches also failed to help.</p><p>Somehow, though, I noticed that the xgo <a href="https://github.com/karalabe/xgo/blob/master/docker/base/Dockerfile">Docker container image</a> is based on Ubuntu 16.04. Since that’s pretty ancient, I thought I’d have a crack at updating it to Ubuntu 20.04. That process was simple but slow, even on an 8-CPU cloud-based VM I was using for the task, but eventually a shiny new Docker image was built and the moment of truth arrived.</p><p>After what seemed like half a lifetime of cross-compiling, the Windows build of Vega finished with no errors. The list of operating systems and hardware architectures Vega is now ready to have running nodes includes:</p><ul><li>Linux on 386, AMD64, ARM64</li><li>MacOSX on AMD64</li><li>Windows on 386, AMD64</li></ul><h4>A gift to the community</h4><p>With so much time taken and effort made, I’d hate for other people to have to pointlessly go through the same process, so here are some resources to help avoid that:</p><ul><li><a href="https://github.com/vegaprotocol/xgo">https://github.com/vegaprotocol/xgo</a> - Here you can find the updates and improvements made from the original xgo project.</li><li><a href="https://hub.docker.com/u/vegaprotocol/">https://hub.docker.com/u/vegaprotocol/</a> - Here you can find Docker images build from the above Github repository. Images are available for Golang 1.11, 1.12, 1.13 and 1.14. For a summary of the updates and improvements, look at <a href="https://hub.docker.com/r/vegaprotocol/xgo-base">xgo-base</a>.</li></ul><p>That’s all from me, I wish you luck in your Golang/cgo cross-compiling journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8a3b1aeffc7" width="1" height="1" alt=""><hr><p><a href="https://blog.vega.xyz/the-challenge-of-cross-compiling-with-go-cgo-and-xgo-a8a3b1aeffc7">The challenge of cross-compiling with go, cgo and xgo</a> was originally published in <a href="https://blog.vega.xyz/">Vega Protocol</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How we leverage CQRS at Vega to build safer trading systems]]></title>
            <link>https://blog.vega.xyz/how-we-leverage-cqrs-at-vega-to-build-safer-trading-systems-2b9f4914daf8?source=rss-5fe9ae9c779f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b9f4914daf8</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[cqrs]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[vega-guides]]></category>
            <category><![CDATA[vega-developer]]></category>
            <dc:creator><![CDATA[Vega Engineering]]></dc:creator>
            <pubDate>Tue, 02 Jun 2020 10:26:16 GMT</pubDate>
            <atom:updated>2020-06-02T10:49:46.232Z</atom:updated>
            <content:encoded><![CDATA[<p>When talking about the technical architecture of Vega, we <a href="https://vega.xyz/assets/vega-technical-overview.pdf">quickly highlight</a> that we’ve adopted a design pattern called Command Query Responsibility Segregation <strong><em>aka </em>CQRS</strong>. I hear you saying “what does that mean?” and “why should it be of interest to me?”. I’ll try and answer those questions in this post, but first, let’s dig a little deeper into the background and history.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KWZfxrwBAqMNC6hcts3uDQ.jpeg" /><figcaption>Barney, Dave and the team discussing Vega in London</figcaption></figure><p>In early 2018, when designing Vega, Dave Hrycyszyn advocated for the use of CQRS. I’d come across this pattern, but not really had chance to use it, he’d previously identified that it has great merits when used with blockchain. Thanks Dave!</p><p>Most famously attributed to the pattern is the software engineering pioneer <a href="https://martinfowler.com/bliki/CQRS.html">Martin Fowler</a>, he states the following:</p><blockquote>“At its heart is the notion that you can use a different model to update information than the model you use to read information. For some situations, this separation can be valuable, but beware that for most systems CQRS adds risky complexity.”</blockquote><p>This is a little different to other data patterns, for example CRUD, where users can create, read, update and delete records atomically using a single operation.</p><p>With the design for Vega, we have a consensus layer, currently provided by a Tendermint core blockchain. Typically a set of geographically distributed validator nodes provide a consistent ordered view over a set of data transactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*2cwQQuZRHTprO9XuALGFUg.jpeg" /><figcaption>The data flow in Vega leveraging CQRS referenced from the <a href="https://vega.xyz/papers/vega-protocol-whitepaper.pdf">Vega Protocol Whitepaper</a></figcaption></figure><p>The <a href="https://arxiv.org/abs/1807.04938">BFT algorithm</a> used in <a href="https://www.tendermint.com/">Tendermint core</a> provides a guarantee of consistent ordering within each batch of transactions. Often in blockchain we refer to these batches as a <strong>block</strong>. All data inputs that may cause state change must go through consensus so that the network has a consistent view.</p><p>To help visualise this, take a look at the diagram above, it shows our consensus layer receiving ‘write’ transactions and outputting a set of ordered transactions ready to be processed by the Vega protocol core.</p><p>Referring back to the definition of <strong>CQRS</strong>, you can think about these messages as <strong>Commands</strong>. We have distilled all the ‘write’ operations needed for Vega into a discrete collection of protocol transaction messages. A subset of these messages can be seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*qampyn41uzIYi5DvoNJaLg.jpeg" /><figcaption>Collateral and Trading commands diagram referenced from the <a href="https://vega.xyz/papers/vega-protocol-whitepaper.pdf">Vega Protocol Whitepaper</a></figcaption></figure><p>When a command is passed into the protocol core, it is processed and as a side effect, data state may be affected and changed. In our design, we update the state in a store and clients who wish to read the effects of the state change must do so using an API request. You can think about these ‘read’ operations as <strong>Queries</strong>. Importantly they are separated, or <strong>Segregated</strong> from all ‘write’ operations.</p><p>So <em>“what does that mean?”</em>, well it means that we can nicely secure our system using a Vega defined instruction set and use the power of distributed state machines to process them safely. No writes can happen without taking the form of a defined command, and reads must be strictly from stores and read API. We enforce strict separation between the consensus, application, and API layers. From our research and the working application, it’s clear that a distributed, decentralised trading platform like Vega is an ideal candidate for <strong>CQRS</strong>.</p><p>For example, we can be sure that only order instructions received and agreed on by the consensus layer are processed by the core engines and affect the collateral or trades in the system. The same can be said for voting on markets or other governance.</p><p>Oh yeah and <em>“why should it be of interest to me?”</em>, if you’re designing a transactional, blockchain based application and need to safely separate your ‘write’ operations from your ‘read’ operations then it can lead to a much clearer and safer way to control the representation of the information in your system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*ziUehGLI-84po7qjaI8ZPw.jpeg" /><figcaption>Our Lego Saturn 5 rocket assembled by the team in 2019</figcaption></figure><p>Feel free to <a href="https://community.vega.xyz/u/cdm/">reach out to me on our Discourse Community</a> if you’d like to know more or fancy chatting/debugging your designs. Thanks for reading, and I hope this will help you<em> launch even more</em> amazing blockchain projects.</p><p>Chris @ Vega Protocol</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b9f4914daf8" width="1" height="1" alt=""><hr><p><a href="https://blog.vega.xyz/how-we-leverage-cqrs-at-vega-to-build-safer-trading-systems-2b9f4914daf8">How we leverage CQRS at Vega to build safer trading systems</a> was originally published in <a href="https://blog.vega.xyz/">Vega Protocol</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Amends]]></title>
            <link>https://blog.vega.xyz/making-amends-2b1c6eb68e88?source=rss-5fe9ae9c779f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b1c6eb68e88</guid>
            <category><![CDATA[orders]]></category>
            <category><![CDATA[vega-updates]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[amends]]></category>
            <dc:creator><![CDATA[Vega Engineering]]></dc:creator>
            <pubDate>Mon, 11 May 2020 17:02:29 GMT</pubDate>
            <atom:updated>2020-05-11T17:02:29.923Z</atom:updated>
            <content:encoded><![CDATA[<h3>Making Amends (Happen)</h3><p>Hi my name is Pete and I am part of the core engineering team. Recently I took on the ticket to implement amends functionality into the core of the Vega system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j0GddgM_RFrOmpH6L3HI3g.jpeg" /></figure><p>I thought, “how hard can it be to alter an existing order? The hard part of getting the order into the system has been performed already”. Well here is a quick review of some of the things I learnt while making this ‘quick’ change.</p><h3>How does an amend affect the order book?</h3><p>If a client needs to reduce the size of an order, the matching engine can keep the order in the same place in the order book and just reduce its size. Nothing else needs to be done to keep the order book correct and fair. If a client wants to increase the size of the order, the matching engine cannot just increase it in place as that has an unfair effect on the people behind that order in the price level. This means the matching engine has to remove the order and reinsert it into the back of the price level. The same thing happens if a client tries to amend the price of an order. This produces a very different computation time depending on what is being amended.</p><h3>Does the client really know the current state of the order?</h3><p>The first attempt of handling a size change was done using absolute values. This means a client tells the order book to change the order size from A to B. This makes sense if the order has not been filled but if the order has been partially filled the client might end up with a total order size more than they wanted.</p><p>Here is an example:</p><p>The order book has a client buy order for 100 items at price 500. The client decides they only need 60 items so they send off an amend with a new size of 60. While that order is being sent, the original order is partially filled with 50 items, leaving 50 remaining. When the amend gets to the order book, the size of the remaining order will be increased from 50 to 60. After this is fully filled, the total amount filled for this order will be 110.</p><p>To get around this, we have a size delta, which is used to adjust the original size. In the case above, the client would send an amend with a sizeDelta of -40. When the amend reaches the order book, the remaining size of the order would be reduced by 40 down to 10 remaining. Then after being fully filled the total size would be 60, as expected.</p><h3>When is an amend not an amend?</h3><p>When clients use the Vega Console to amend orders, basic validation can be performed to make sure the amend makes sense. Sending a price amend for an order where the new price is the same as the current price is such an example. However API users have to validate the values themselves and it is possible for them to send such an amend. How should we handle that amend? Plenty of options exist, we could reject the amend as soon as we realise the price is the same. We could accept the amend but not touch the existing order. How would we let the user know what had happened? After collecting some great feedback from the traders and other coders in the team, we decided to not reject those trades and to update the ModifiedAt field in the order before sending out a fresh OrderResponse message. This way the user can see that the amend was processed but no changes are made to the position of the order in the orderbook.</p><h3>How do we keep track of all the versions?</h3><p>Amends take an existing order and change something about it. An order can be amended many times before it is finally filled or cancelled. For reconciliation systems, knowing the history of how the order changed is a requirement and something that the Vega core needs to support. The way we handle this internally is with a version number. Whenever something is changed due to an amend, we update the order and then increment the version number. The order response we give back to the user contains the version number for the live order. If the user wants to get the order information for a previous order, they can query using the orderID and version number to retrieve it. Unlike normal financial exchanges, crypto exchanges run 24/7/365. Orders can stay in the book for the lifetime of the exchange, so to make sure we do not overflow the version storage we are using an unsigned 64 bit value to represent the version number. If the user amends the same order 1,000,000 times a second, the version number will not overflow for around half a million years!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b1c6eb68e88" width="1" height="1" alt=""><hr><p><a href="https://blog.vega.xyz/making-amends-2b1c6eb68e88">Making Amends</a> was originally published in <a href="https://blog.vega.xyz/">Vega Protocol</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Engineering the systems that powered Vega in the early days]]></title>
            <link>https://blog.vega.xyz/how-did-we-get-here-the-systems-that-power-vega-part-1-653e8f9f2eba?source=rss-5fe9ae9c779f------2</link>
            <guid isPermaLink="false">https://medium.com/p/653e8f9f2eba</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[vega-developer]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[startup]]></category>
            <dc:creator><![CDATA[Vega Engineering]]></dc:creator>
            <pubDate>Wed, 31 Oct 2018 15:31:01 GMT</pubDate>
            <atom:updated>2020-06-10T14:50:48.971Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qka3YCHuXJD138KOeBZ9wQ.jpeg" /></figure><p>Hi from Vega’s core engineering team! Thanks for coming along on this journey as we explore the very beginnings of turning our vision for Vega into a reality. That vision: to create the building blocks for a new financial system. It sounds lofty, but we have the passion, expertise and curiosity to do it.</p><p><a href="https://vega.xyz/who#team">The Vega team</a> is a mix of blockchain veterans and newbies, with decades of diverse experience. We’re here to build a platform that implements the Vega protocol. That includes trading systems, APIs and a blockchain infrastructure to realise a fully end-to-end decentralised trading environment. Easy!</p><p>Actually, there’s a long road ahead of us, full of complex, interesting challenges and a lot of testing. We’ll be checking in occasionally to explore the code and systems we’re implementing, and to share how we’re handling the intriguing problems that we come across. Expect to see architecture discussions, technical details, and maybe even code snippets.</p><h4>Language choice</h4><p>Vega has a wealth of engineering knowledge and we have leveraged the experience of the team with respect to architecture and design.</p><p>Our team is cross functional, meaning we can swap tasks, work collaboratively, and quickly deliver features. We practice modern agile development and we’re constantly reflecting with the aid of retrospectives and catch ups.</p><p>There are so many programming languages available, it’s tough to narrow down to the best for any project. We took time to consider the landscape, and in the end we chose <a href="https://golang.org/">Golang</a> for Vega’s core systems. <a href="https://golang.org/">Golang</a> (or Go as it’s affectionately known) is a powerful language that provides compiled platform binaries, it’s fast, and it doesn’t need a byte code interpreter on each machine. As a bonus, it’s also the language that our consensus provider is written in, so in our opinion, a perfect match.</p><p>We are also building a browser-based reference trading UI, providing a familiar user experience to other trading platforms. The core of this is built with Javascript using <a href="https://reactjs.org/">React</a> &amp; <a href="https://www.typescriptlang.org/">TypeScript</a>.</p><h4>Consensus provider</h4><p>One of the fundamental parts of the protocol is that it will be able to reach a consensus on ordering of transactions between all nodes in the network. To make this possible, we’ve chosen to use a <a href="https://en.wikipedia.org/wiki/Proof-of-stake">Proof of Stake</a> (PoS) blockchain. Our current PoS blockchain is powered by <a href="https://www.tendermint.com/">Tendermint</a>, for several reasons:</p><ul><li>Our application needs high throughput and low latency, <a href="https://www.tendermint.com/">Tendermint</a> is designed for both</li><li>It works right now, allowing us to start developing Vega immediately</li><li>It’s written in Go, which gives us access to further libraries so that we can build out the complex functionality we need — all the way up to machine learning</li></ul><p>This said, we’re designing the <a href="https://vega.xyz/">Vega protocol</a> to be blockchain agnostic. Our plan is to give the protocol the ability to move forward with constantly evolving PoS research.</p><h4>Matching engine</h4><p>At the heart of any electronic trading platform is a matching engine. This component matches up bids and offers to facilitate trades. One of our founders, Barney, has implemented many such engines in his career. For our first prototype he wrote a super fast, super lightweight matching engine in Go, which is able to process millions of orders, and match a trade in less than 8µs.</p><p>The following is an excerpt from our Go benchmark tests running on a 2.9GHz quad-core Intel Core i7 (Kaby Lake) with 16GB RAM:</p><pre>(n=10000000) Elapsed = 1m18.262835598s, average = 7.826µs; matched 3931651 trades, average 0.3931651 trades per order<br>(n=10000000) bestBid:128 bestOffer:60 lastTradedPrice:80 buyOrderCount:1067604 sellOrderCount:1069094 buyOrderVolume:53380200 sellOrderVolume:53454700 buyPriceLevels:79 sellPriceLevels:84 </pre><p>There are some initial limits to this matching engine. However, for simplicity we added support for ‘good until close’ and ‘execute and eliminate’ order types, but have yet add support for auction periods.</p><h4>API (REST/SSE)</h4><p>In order to interact with the protocol core, we created a simple <a href="https://www.smashingmagazine.com/2018/01/understanding-using-rest-api/">REST based API</a> that would allow clients to place orders, list trades, view positions, and much more. We built this quickly using the excellent Go Gin framework, allowing us to focus on the business logic and not re-invent another HTTP-based REST server or framework.</p><h4>Reference trading UI</h4><p>Our browser-based reference trading UI is built in React and Typescript. [Read more about <a href="https://medium.com/vegaprotocol/typescript-at-vega-785b75708661">our TypeScript implementation</a>.] It uses <a href="https://github.com/palantir">Palantir’s</a> BlueprintJS and Mosaic to rapidly prototype a performant and familiar feeling trading interface. It talks to the Vega REST API to place orders and receives new trades asynchronously via Server Side Events (SSE).</p><h4>Load simulation</h4><p>Barney also designed a simple trading simulator to generate buy and sell orders around the current asking price of Bitcoin in US dollars. Written in Python, it includes all the current Vega team members as named traders. These ‘bots’ place orders against the REST API at a configurable frequency. When demonstrating the platform we see that their trading looks realistic on the reference trading UI.</p><p>The simulation forms part of our initial load testing, and it’s cool to see how well (or badly!) each team member is doing when trading on Vega.</p><h4>Testability</h4><p>As experienced software engineers, we are keen to create a stable implementation of the protocol. One that can be improved without re-writing large portions of code. We’re used to writing independent components and understand that any large software system needs to be designed to allow optimal testability. We aim to use test-driven development where possible. We’ve also started to add platform integration tests to ensure end-to-end behaviour.</p><p>In Vega core we use Go’s excellent built in testing tools, with supporting packages <a href="https://github.com/vektra/mockery">Mockery</a> and <a href="https://github.com/stretchr/testify">Testify</a>. On the Reference trading UI side, we use Javascript tooling including <a href="https://github.com/airbnb/enzyme">Enzyme</a> and <a href="https://jestjs.io/">Jest</a>.</p><h4>What’s coming next?</h4><p>Maybe you’re interested in following us on our journey? If so, please visit <a href="https://vega.xyz/">vega.xyz</a>, sign up to our newsletter, and follow us here, on Medium.</p><p>We’re busy building out even more of the core systems, and look forward to sharing how our design and thinking has evolved over time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=653e8f9f2eba" width="1" height="1" alt=""><hr><p><a href="https://blog.vega.xyz/how-did-we-get-here-the-systems-that-power-vega-part-1-653e8f9f2eba">Engineering the systems that powered Vega in the early days</a> was originally published in <a href="https://blog.vega.xyz/">Vega Protocol</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>