<?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[Ante Labs - Medium]]></title>
        <description><![CDATA[Ante is building the Schelling Point for Decentralized Trust. Ante empowers blockchain protocols to write and back incentivized, on-chain tests (“Smart Tests for Smart Contracts”). - Medium]]></description>
        <link>https://medium.com/ante-labs?source=rss----d221c76a88ff---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Ante Labs - Medium</title>
            <link>https://medium.com/ante-labs?source=rss----d221c76a88ff---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 12:20:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/ante-labs" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[AnteUP: Proving Past Usage]]></title>
            <link>https://medium.com/ante-labs/anteup-proving-past-usage-e0701ec2c64f?source=rss----d221c76a88ff---4</link>
            <guid isPermaLink="false">https://medium.com/p/e0701ec2c64f</guid>
            <category><![CDATA[zero-knowledge-proofs]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Ante]]></dc:creator>
            <pubDate>Tue, 02 May 2023 17:54:16 GMT</pubDate>
            <atom:updated>2023-05-02T17:54:16.054Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nuGubUa2HUnTWk62KDjWMQ.png" /></figure><p><a href="https://up.ante.finance/">Ante Usage Proof</a> (AnteUP) allows people to generate a proof of historical interaction with Ante off-chain and verify the correctness of that proof on-chain using <a href="https://axiom.xyz/">Axiom</a>’s ZK-enabled trustless cache of historic Ethereum block hashes.</p><h4>Using AnteUP</h4><ol><li>AnteUP scans the chain for any new addresses interacting with Ante contracts, and generates a proof (off-chain) for any new users.</li><li>When you go to <a href="https://up.ante.finance/">up.ante.finance</a> and connect your wallet or enter an address, AnteUP fetches the corresponding usage proof from the database if available.</li><li>When you click “Verify”, it validates the proof using the AnteUP on-chain verification contract, which returns true if the proof is correct. Since we are calling a view function, verifying the proof using the AnteUP web app costs no gas.</li></ol><h4>How it works</h4><p>How can a smart contract know if a historical transaction is valid or not?</p><p>Each block header in Ethereum contains three distinct hash roots, representing the Merkle Patricia Tries (MPT) of state, transactions, and receipts. Using a transaction proof, the transaction index inside the block, the transactions MPT root extracted from the block header, and the transaction hash, we can verify the validity of a Merkle inclusion proof and extract the complete transaction information.</p><p>However, smart contracts on Ethereum and other chains have no “memory”. They can access the current state of the chain, as well as the previous 256 block hashes. So we could use a Merkle inclusion proof to show that a particular transaction was part of a block that corresponds to a specific block hash, but only for the most recent 256 blocks (~50 minutes) of history. What happens if we want to look back further?</p><p>Enter <a href="https://axiom.xyz/">Axiom</a>. Axiom stores Merkle roots of historical Ethereum block hashes, and uses the succinctness property of zk-SNARKs to prove the those block hashes form a valid commitment chain (<a href="https://docs.axiom.xyz/axiom-architecture/how-axiom-works">read more</a>). (Note: Axiom is currently in a demo phase and will be heading to production in the next few months)</p><p>So now that we have the power of Axiom, we can verify the validity of a historical transaction (at a high level) as follows:</p><ol><li>Use Axiom to verify that a given historical block is valid.</li><li>Use a Merkle inclusion proof to show that a specific transaction was included in that block.</li></ol><p>Let’s dig a little further into the details.</p><p><strong>Proof generation:</strong></p><p>AnteUP uses backend scripts to index all first transactions of distinct addresses that called Ante contracts, generate the corresponding Merkle inclusion proofs for those transactions, and collect block witnesses for the blocks the transactions were included in.</p><p>This can be independently done by anyone but proactively indexing and generating the proofs saves users a time-consuming proof generation step.</p><p>Next, the on-chain proof verification in AnteUP uses 1) block witness, 2) block header, 3) transaction proof, 4) transaction key, and 5) transaction hash.</p><p>To verify the proof on-chain: (<a href="https://etherscan.io/address/0x2ae392dc9Af24CA5FD8E5D5912190f0fC4Ad9D99#readContract%23F4">Verifier contract</a>)</p><ol><li>Use Axiom to verify that a given block hash corresponds to a valid historical block number.</li><li>Verify that the provided block header hashes to the block hash.</li><li>Extract the transactions trie root from block header.</li><li>Use the transaction proof to walk the Merkle-Patricia Trie from the txRoot and extract the transaction information.</li><li>Check that the extracted information is valid by verifying that the hash of the extracted transaction information corresponds to the transaction hash.</li></ol><p>From there, we can perform some kind of action using the transaction information — in AnteUP, we check that the “to” field is an Ante contract as proof of interaction with an Ante contract.</p><p>And that’s it! We can now verify on-chain that a specific address has ever interacted with Ante.</p><h4>Potential Applications</h4><p>AnteUP represents a novel use of Axiom to trustlessly verify on-chain that a past action was taken. This opens up a wide variety of potential use cases:</p><ul><li>Projects could gate new alpha features to past users of the protocol instead of relying on manual whitelists or NFT access passes that might be sold in secondary markets.</li><li>Community rewards — trust-minimized whitelisting of community members for retroactive airdrops, NFTs, etc. instead of project teams maintaining large spreadsheets of addresses.</li><li>Non-token-based governance — Historic protocol usage can be used instead to trustlessly qualify relevant users for governance.</li><li>Trustless reputational systems — proofs of historical transactions could be linked together to form proofs of historical behavior over time.</li></ul><h4>Current Limitations and Potential Developments</h4><p>AnteUP in its current form has several limitations and tradeoffs:</p><ol><li>AnteUP only verifies transaction inclusion in a block and cannot tell if transaction was successful or not. For this, a receipt proof would be needed as well.</li><li>For simplicity, AnteUP only indexes transactions up to currentBlock minus 1024 blocks; future versions could index up to the current block.</li><li>Indexing the transactions/proofs/block witnesses is a fairly slow process that could add up to significant time for heavily-used protocols.</li><li>Giving users tooling to generate their own proofs can reduce reliance on the AnteUP scripts.</li><li>The list of Ante contracts is set/updated by the owner of the AnteUP verifier contract, so users need to trust that the listed contracts are comprehensive.</li><li>AnteUP relies on the continued on-chain storing of Merkle roots to prove historical block validity.</li></ol><h4>Building on AnteUP</h4><p>The core contracts and proof generating/indexing scripts have been open-sourced (<a href="https://github.com/antefinance/ante-up-demo">see repository</a>) and can be used by anyone. To modify AnteUP for your purposes:</p><ol><li>Update backend scripts to target the set of contracts you are interested in.</li><li>Update the <a href="https://etherscan.io/address/0x2ae392dc9Af24CA5FD8E5D5912190f0fC4Ad9D99#readContract%23F4">verifier contract</a> code to check your condition of choice and optionally define actions to be taken after verifying the conditions. Some ideas include generating an on-chain attestation, minting an NFT, allowing a user to use a new version of a protocol, or participate in governance.</li></ol><p>What kinds of interesting applications will you build on AnteUP?</p><p>Special thanks to <a href="https://0xparc.org/">0xPARC</a> and ZK Week at <a href="https://zuzalu.city/">Zuzalu</a> for ideas, brainstorming, OSS, and inspiration!</p><p>Follow Ante on <a href="https://twitter.com/AnteFinance">Twitter</a> and discuss ideas with us in <a href="https://discord.gg/ante">Discord</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0701ec2c64f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ante-labs/anteup-proving-past-usage-e0701ec2c64f">AnteUP: Proving Past Usage</a> was originally published in <a href="https://medium.com/ante-labs">Ante Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Smart Contracts with ChatGPT and Ante]]></title>
            <link>https://medium.com/ante-labs/securing-smart-contracts-with-chatgpt-and-ante-finance-1fb54b36fed3?source=rss----d221c76a88ff---4</link>
            <guid isPermaLink="false">https://medium.com/p/1fb54b36fed3</guid>
            <category><![CDATA[gpt-4]]></category>
            <category><![CDATA[smart-contracts-explained]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[JSeam]]></dc:creator>
            <pubDate>Thu, 13 Apr 2023 18:56:51 GMT</pubDate>
            <atom:updated>2023-04-13T18:57:17.788Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cwAAGHoAJf5Oga7L" /><figcaption>Photo by <a href="https://unsplash.com/@ilgmyzin?utm_source=medium&amp;utm_medium=referral">ilgmyzin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>ChatGPT (GPT4) is surprisingly decent at writing smart contracts compared to ChatGPT (GPT3). Shorter code snippets are ideal as ChatGPT has issues generating longer code snippets, like timeouts or that ChatGPT simply ceases to write stuff. Despite this, ChatGPT is ideal for writing Ante Tests on Ante.</p><h4>What are Ante Tests?</h4><p>Ante Tests are on-chain commitments that are expressed as smart contract code. You may want to check things like, Protocol X will not dump all its protocol tokens into a Uniswap pool. Ante Tests then allow users write smart contract tests to express these commitments onchain. Users can then challenge the commitment or vouch for the commitment by staking tokens.</p><p>An example of a test is shown below , the test below checks that the AAVE token balance in the Aave Ecosystem Reserve remains greater than 15k. An AntePool is then created for the people who would like to challenge or vouch for the commitment. If this test remains true, the challengers of that commitment pay the people who would vouch for that commitment. However, should the test fail, the people who vouch for that commitment would then have to pay the people challenging that commitment. <a href="https://docs.ante.finance/ante/">More details can be found in the Ante Documentation.</a></p><pre>// SPDX-License-Identifier: GPL-3.0-only<br><br>pragma solidity ^0.8.0;<br><br>import {AnteTest} from &quot;../AnteTest.sol&quot;;<br>import {IERC20Metadata} from &quot;@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol&quot;;<br><br>/// @title Checks AAVE balance in Aave Ecosystem Reserve remains &gt;= 15k<br>/// @notice Ante Test to check<br>contract AnteAaveTokenBalanceAbove15K is AnteTest(&quot;Aave Ecosystem Reserve Aave balance remains &gt;= 15k&quot;) {<br>    // https://etherscan.io/address/0x25F2226B597E8F9514B3F68F00f494cF4f286491<br>    address public constant HOLDER_ADDRESS = 0x25F2226B597E8F9514B3F68F00f494cF4f286491;<br><br>    // https://etherscan.io/address/0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9<br>    IERC20Metadata public constant TOKEN = IERC20Metadata(0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9);<br><br>    // Will be set to desired token balance threshold<br>    uint256 public immutable thresholdBalance;<br><br>    constructor() {<br>        thresholdBalance = (15000) * (10**TOKEN.decimals());<br><br>        protocolName = &quot;Aave&quot;;<br><br>        testedContracts = [address(TOKEN), HOLDER_ADDRESS];<br>    }<br><br>    /// @notice test to check if AAVE balance in Aave Ecosystem Reserve is &gt;= 15k<br>    /// @return true if AAVE balance in Aave Ecosystem Reserve is &gt;= 15k<br>    function checkTestPasses() public view override returns (bool) {<br>        return (TOKEN.balanceOf(HOLDER_ADDRESS) &gt;= thresholdBalance);<br>    }<br>}</pre><h4>Using ChatGPT to Generate Tests</h4><p>As you might expect, writing the tests can be fairly laborious and repetitive. Could we use something like ChatGPT to help automate this? Apparently, it is possible. We provide the example above to ChatGPT and provide the prompt.</p><pre>Pretend to be a smart contract engineer, your goal is to find write Ante Test. Ante Test are an onchain test which can be used to test for invariants and provide payouts to users should those invariants break.<br><br>An example of such a test is as follows. &quot;Checks AAVE balance in Aave Ecosystem Reserve remains &gt;= 15k&quot;<br><br>The prompt for the test is <br>```<br>// SPDX-License-Identifier: GPL-3.0-only<br><br>pragma solidity ^0.8.0;<br><br>import {AnteTest} from &quot;../AnteTest.sol&quot;;<br>import {IERC20Metadata} from &quot;@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol&quot;;<br><br>/// @title Checks AAVE balance in Aave Ecosystem Reserve remains &gt;= 15k<br>/// @notice Ante Test to check<br>contract AnteAaveTokenBalanceAbove15K is AnteTest(&quot;Aave Ecosystem Reserve Aave balance remains &gt;= 15k&quot;) {<br>    // https://etherscan.io/address/0x25F2226B597E8F9514B3F68F00f494cF4f286491<br>    address public constant HOLDER_ADDRESS = 0x25F2226B597E8F9514B3F68F00f494cF4f286491;<br><br>    // https://etherscan.io/address/0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9<br>    IERC20Metadata public constant TOKEN = IERC20Metadata(0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9);<br><br>    // Will be set to desired token balance threshold<br>    uint256 public immutable thresholdBalance;<br><br>    constructor() {<br>        thresholdBalance = (15000) * (10**TOKEN.decimals());<br><br>        protocolName = &quot;Aave&quot;;<br><br>        testedContracts = [address(TOKEN), HOLDER_ADDRESS];<br>    }<br><br>    /// @notice test to check if AAVE balance in Aave Ecosystem Reserve is &gt;= 15k<br>    /// @return true if AAVE balance in Aave Ecosystem Reserve is &gt;= 15k<br>    function checkTestPasses() public view override returns (bool) {<br>        return (TOKEN.balanceOf(HOLDER_ADDRESS) &gt;= thresholdBalance);<br>    }<br>}<br>```</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*o4i8e5UMhg2QqAXS_hVb2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*uTpJeKzaRO3nSribsBSA_g.png" /></figure><p>ChatGPT replies with the following, demonstrating that it understood the concept of the AnteTest!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H6Ix1JSLZTr1mdDLUzFJ1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*J9SXBjiCrSM8LqDCXMThNA.png" /></figure><p>Now we provide an unseen smart contract and request that it generates a new Ante Test. The contract is the StargateProxy Contract. We now request that ChatGPT ensures that the estimateFee function is at a reasonable threshold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*mWkmaFpBrz5rq1NSXyTcAg.png" /></figure><pre>Given the Stargate Proxy code shown below, write an AnteTest to check if the estimateFee function is at a reasonable threshold such that it does not consume the user&#39;s token balance when using the contract.<br><br>```<br>// SPDX-License-Identifier: MIT<br><br>pragma solidity ^0.8.17;<br><br>import &quot;@openzeppelin/contracts/access/Ownable.sol&quot;;<br>import &quot;@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol&quot;;<br>import &quot;./interfaces/IStargateReceiver.sol&quot;;<br>import &quot;./interfaces/IStargateProxy.sol&quot;;<br>import &quot;./interfaces/IStargateRouter.sol&quot;;<br>import &quot;./interfaces/IStargateFactory.sol&quot;;<br>import &quot;./interfaces/IStargatePool.sol&quot;;<br>import &quot;./interfaces/IStargateProxyReceiver.sol&quot;;<br>import &quot;./libraries/SwapUtils.sol&quot;;<br><br>contract StargateProxy is Ownable, IStargateReceiver, IStargateProxy {<br>    using SafeERC20 for IERC20;<br>    using Address for address payable;<br><br>    address public immutable router;<br>    address public immutable factory;<br>    mapping(uint16 =&gt; address) public dstAddress;<br><br>    constructor(address _router) {<br>        router = _router;<br>        factory = IStargateRouter(_router).factory();<br>    }<br><br>    function estimateFee(<br>        uint16 dstChainId,<br>        address dstCallTo,<br>        bytes calldata dstCallData,<br>        uint256 dstGasForCall,<br>        uint256 dstNativeAmount,<br>        address from<br>    ) external view returns (uint256) {<br>        address dst = dstAddress[dstChainId];<br>        if (dst == address(0)) revert DstChainNotFound(dstChainId);<br><br>        (uint256 fee, ) = IStargateRouter(router).quoteLayerZeroFee(<br>            dstChainId,<br>            1, /*TYPE_SWAP_REMOTE*/<br>            abi.encodePacked(dst),<br>            abi.encodePacked(from, dstCallTo, dstCallData),<br>            IStargateRouter.lzTxObj(dstGasForCall, dstNativeAmount, abi.encodePacked(from))<br>        );<br>        return fee;<br>    }<br><br>    function updateDstAddress(uint16 dstChainId, address _dstAddress) external onlyOwner {<br>        dstAddress[dstChainId] = _dstAddress;<br>        emit UpdateDstAddress(dstChainId, _dstAddress);<br>    }<br><br>    function transferNative(uint256 amount, TransferParams calldata params) external payable {<br>        if (params.swapTo != address(0)) {<br>            SwapUtils.swapNative(amount, params.swapTo, params.swapData);<br>        }<br>        _transfer(params, payable(msg.sender), msg.value - amount);<br><br>        uint256 balance = address(this).balance;<br>        if (balance &gt; 0) {<br>            payable(msg.sender).sendValue(balance);<br>        }<br>    }<br><br>    function transferERC20(<br>        address token,<br>        uint256 amount,<br>        TransferParams calldata params<br>    ) external payable {<br>        IERC20(token).safeTransferFrom(msg.sender, address(this), amount);<br><br>        if (params.swapTo != address(0)) {<br>            SwapUtils.swapERC20(token, amount, params.swapTo, params.swapData, true, msg.sender);<br>        }<br>        _transfer(params, payable(msg.sender), msg.value);<br>    }<br><br>    function _transfer(<br>        TransferParams calldata params,<br>        address payable from,<br>        uint256 fee<br>    ) internal {<br>        address dst = dstAddress[params.dstChainId];<br>        if (dst == address(0)) revert DstChainNotFound(params.dstChainId);<br><br>        address pool = IStargateFactory(factory).getPool(params.poolId);<br>        if (pool == address(0)) revert PoolNotFound(params.poolId);<br><br>        address token = IStargatePool(pool).token();<br>        IERC20(token).approve(router, params.amount);<br>        IStargateRouter(router).swap{value: fee}(<br>            params.dstChainId,<br>            params.poolId,<br>            params.dstPoolId,<br>            from,<br>            params.amount,<br>            params.dstMinAmount,<br>            IStargateRouter.lzTxObj(params.dstGasForCall, params.dstNativeAmount, abi.encodePacked(from)),<br>            abi.encodePacked(dst),<br>            abi.encodePacked(from, params.dstCallTo, params.dstCallData)<br>        );<br><br>        uint256 balance = IERC20(token).balanceOf(address(this));<br>        if (balance &gt; 0) {<br>            IERC20(token).safeTransfer(msg.sender, balance);<br>        }<br>    }<br><br>    //---------------------------------------------------------------------------<br>    // RECEIVER FUNCTIONS<br>    function estimateGas(<br>        address swapTo,<br>        bytes calldata swapData,<br>        uint16 srcChainId,<br>        bytes calldata srcAddress,<br>        uint256 nonce,<br>        address token,<br>        uint256 amountLD,<br>        bytes calldata payload<br>    ) external payable returns (uint256 gasSpent) {<br>        SwapUtils.swapNative(msg.value, swapTo, swapData);<br><br>        uint256 gas = gasleft();<br>        _sgReceive(srcChainId, srcAddress, nonce, token, amountLD, payload);<br>        return gas - gasleft();<br>    }<br><br>    function sgReceive(<br>        uint16 srcChainId,<br>        bytes calldata srcAddress,<br>        uint256 nonce,<br>        address token,<br>        uint256 amountLD,<br>        bytes calldata payload<br>    ) external {<br>        if (msg.sender != router) revert Forbidden();<br><br>        _sgReceive(srcChainId, srcAddress, nonce, token, amountLD, payload);<br>    }<br><br>    function _sgReceive(<br>        uint16 srcChainId,<br>        bytes calldata srcAddress,<br>        uint256 nonce,<br>        address token,<br>        uint256 amountLD,<br>        bytes calldata payload<br>    ) internal {<br>        address srcFrom = address(bytes20(payload[0:20]));<br>        address to = address(bytes20(payload[20:40]));<br>        if (to != address(0)) {<br>            IERC20(token).safeTransfer(to, amountLD);<br>            try IStargateProxyReceiver(to).sgProxyReceive(srcFrom, token, amountLD, payload[40:]) {} catch (<br>                bytes memory reason<br>            ) {<br>                try IStargateProxyReceiver(to).onReceiveERC20(token, srcFrom, amountLD) {} catch {}<br>                emit CallFailure(srcFrom, to, payload[40:], reason);<br>            }<br>        }<br><br>        uint256 balance = IERC20(token).balanceOf(address(this));<br>        if (balance &gt; 0) {<br>            IERC20(token).safeTransfer(to == address(0) ? srcFrom : to, balance);<br>            if (to != address(0)) {<br>                try IStargateProxyReceiver(to).onReceiveERC20(token, srcFrom, balance) {} catch {}<br>            }<br>        }<br><br>        balance = address(this).balance;<br>        if (balance &gt; 0) {<br>            srcFrom.call{value: balance}(&quot;&quot;);<br>        }<br><br>        emit SGReceive(srcChainId, srcAddress, nonce, token, amountLD);<br>    }<br>}<br>```</pre><p>ChatGPT provides the following Ante Test for the Stargate Proxy contract!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*WwE9jNfyfO-Q6bPfyEwhDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*YGEVKmyhVdcdjiaHcyXAow.png" /></figure><pre>// SPDX-License-Identifier: GPL-3.0-only<br><br>pragma solidity ^0.8.0;<br><br>import {AnteTest} from &quot;../AnteTest.sol&quot;;<br>import {StargateProxy} from &quot;./StargateProxy.sol&quot;;<br>import {IERC20Metadata} from &quot;@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol&quot;;<br><br>/// @title Checks if the estimateFee function in StargateProxy is at a reasonable threshold<br>/// @notice Ante Test to check the estimated fee against user&#39;s token balance<br>contract AnteStargateProxyEstimateFeeTest is AnteTest(&quot;Stargate Proxy Estimate Fee Test&quot;) {<br>    StargateProxy public constant proxy = StargateProxy(0x1234567890123456789012345678901234567890); // Replace with StargateProxy contract address<br>    uint16 public constant DST_CHAIN_ID = 1;<br>    address public constant DST_CALL_TO = 0x0987654321098765432109876543210987654321; // Replace with the destination call address<br>    uint256 public constant DST_GAS_FOR_CALL = 50000;<br>    uint256 public constant DST_NATIVE_AMOUNT = 0;<br><br>    uint256 public constant FEE_THRESHOLD_PERCENT = 1;<br><br>    constructor() {<br>        protocolName = &quot;Stargate Proxy&quot;;<br>        testedContracts = [address(proxy)];<br>    }<br><br>    /// @notice Test to check if the estimated fee is below the threshold percentage of user&#39;s token balance<br>    /// @return true if the estimated fee is below the threshold percentage<br>    function checkTestPasses() public view override returns (bool) {<br>        address user = msg.sender;<br>        uint256 estimatedFee = proxy.estimateFee(DST_CHAIN_ID, DST_CALL_TO, &quot;&quot;, DST_GAS_FOR_CALL, DST_NATIVE_AMOUNT, user);<br><br>        IERC20Metadata token = IERC20Metadata(proxy.router());<br>        uint256 userTokenBalance = token.balanceOf(user);<br>        uint256 feeThreshold = (userTokenBalance * FEE_THRESHOLD_PERCENT) / 100;<br><br>        return (estimatedFee &lt;= feeThreshold);<br>    }<br>}</pre><p>However, there is a catch! While ChatGPT did correctly think of a feeThreshold parameter, the Ante Test can fail unfairly suppose if the user’s token balance is 0. It might be the case that the prompt isn’t very good either. Moreover, it should not be testing the token balance but the amount of tokens to be sent. ChatGPT assumes the dstCallData to be an empty byte input. It should account for an ERC20 since it is going to send ERC20 tokens! It’s a good start.</p><p>Let’s see if we can correct ChatGPT?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*lJPW5r4HPhFBMVv8YOLF8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*5lbOn8hkZMgRTvFu0TSG0g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*ChV1CxNN_RYYyzsAd3TduQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*N94n32kZsD5lyHPnGFgtMg.png" /></figure><pre>// SPDX-License-Identifier: GPL-3.0-only<br><br>pragma solidity ^0.8.0;<br><br>import {AnteTest} from &quot;../AnteTest.sol&quot;;<br>import {StargateProxy} from &quot;./StargateProxy.sol&quot;;<br>import {IERC20Metadata} from &quot;@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol&quot;;<br><br>/// @title Checks if the estimateFee function in StargateProxy is at a reasonable threshold<br>/// @notice Ante Test to check the estimated fee against tokens transferred<br>contract AnteStargateProxyEstimateFeeTest is AnteTest(&quot;Stargate Proxy Estimate Fee Test&quot;) {<br>    StargateProxy public constant proxy = StargateProxy(0x1234567890123456789012345678901234567890); // Replace with StargateProxy contract address<br>    uint16 public constant DST_CHAIN_ID = 1;<br>    address public constant DST_CALL_TO = 0x0987654321098765432109876543210987654321; // Replace with the destination call address<br>    uint256 public constant DST_GAS_FOR_CALL = 50000;<br>    uint256 public constant DST_NATIVE_AMOUNT = 0;<br><br>    uint256 public constant TOKENS_FOR_GAS = 5000;<br>    uint256 public constant FEE_PERCENTAGE = 6; // 0.06% fee<br>    uint256 public constant ONE_HUNDRED_PERCENT = 100000; // 100% in basis points (1 basis point = 0.01%)<br><br>    constructor() {<br>        protocolName = &quot;Stargate Proxy&quot;;<br>        testedContracts = [address(proxy)];<br>    }<br><br>    /// @notice Test to check if the estimated fee is below the threshold percentage of tokens transferred<br>    /// @return true if the estimated fee is below the threshold percentage<br>    function checkTestPasses() public view override returns (bool) {<br>        address user = msg.sender;<br>        uint256 tokensToTransfer = 1000; // Replace with the desired tokens to transfer<br>        <br>        // Create the encoded function call for ERC20 transfer<br>        bytes memory dstCallData = abi.encodeWithSignature(<br>            &quot;transfer(address,uint256)&quot;,<br>            DST_CALL_TO,<br>            tokensToTransfer<br>        );<br><br>        uint256 estimatedFee = proxy.estimateFee(<br>            DST_CHAIN_ID,<br>            DST_CALL_TO,<br>            dstCallData,<br>            DST_GAS_FOR_CALL,<br>            DST_NATIVE_AMOUNT,<br>            user<br>        );<br><br>        uint256 feeThreshold = (tokensToTransfer * FEE_PERCENTAGE) / ONE_HUNDRED_PERCENT;<br><br>        // Add tokens needed for gas to the threshold<br>        feeThreshold += TOKENS_FOR_GAS;<br><br>        return (estimatedFee &lt;= feeThreshold);<br>    }<br>}</pre><p>Right on! It seems like ChatGPT is able to generate a corrected version given sufficient hand holding and prompts. However, there’s still an issue! Because the division by 100000 is used, there’s still a possibility of truncated values. The 6/100000 doesn’t seem correct either but these are trivial to fix. It’s likely that it may create bugs unwittingly, however, humans can also create bug prone code. The code is not very efficient either and work can be done to optimize the solidity code further. While not necessarily perfect, ChatGPT does provide a reasonable starting point for smart contracts. You may think of it as boilerplate code on steroids.</p><p>With Ante and ChatGPT we can now provide an additional layer of security for smart contract protocols. What a time to be alive!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/0*o3STFJHho-oj2Ohh.jpg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fb54b36fed3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ante-labs/securing-smart-contracts-with-chatgpt-and-ante-finance-1fb54b36fed3">Securing Smart Contracts with ChatGPT and Ante</a> was originally published in <a href="https://medium.com/ante-labs">Ante Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s in Ante v0.6?]]></title>
            <link>https://medium.com/ante-labs/whats-in-ante-v0-6-dafe0c31cd10?source=rss----d221c76a88ff---4</link>
            <guid isPermaLink="false">https://medium.com/p/dafe0c31cd10</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[antes]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[web3]]></category>
            <dc:creator><![CDATA[Ante]]></dc:creator>
            <pubDate>Thu, 30 Mar 2023 19:54:42 GMT</pubDate>
            <atom:updated>2023-03-30T19:54:42.844Z</atom:updated>
            <content:encoded><![CDATA[<h4>What is Ante?</h4><p>Ante is a decentralized protocol to translate implicit trust assumptions like “protocol X is solvent” or “team Y won’t rug” into explicit on-chain <strong>commitments</strong> (Ante Tests) that anyone can verify. These new trust-signaling primitives form the potential building blocks for a decentralized trust ratings system.</p><h4>What’s new in Ante v0.6?</h4><p><strong>Test author rewards </strong>— Test authors can claim a share of pool decay (% that challengers pay to stakers over time) for tests they wrote!</p><p><strong>Time-committed staking</strong> — Stakers can timelock their stake to demonstrate greater conviction and alignment</p><p><strong>Challenger payout soft floor</strong> — Challengers can challenge pools with more confidence around potential payout when tests fail</p><p><strong>Variable pool economics </strong>—pool currency, decay rate, payout soft floor, and test author rewards can be set per pool</p><p>All existing Ante v0.5 pools remain usable in their current form. Like v0.5, Ante v0.6 pools are non-upgradeable so their behavior won’t change.</p><h4>Ante v0.6 is live!</h4><p><a href="https://app.ante.finance/">Ante v0.6</a> has been live now for over a month now! Follow Ante on <a href="https://twitter.com/antefinance">Twitter</a> and join the <a href="https://discord.gg/ante">Discord</a> to discuss the latest Ante news.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dafe0c31cd10" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ante-labs/whats-in-ante-v0-6-dafe0c31cd10">What’s in Ante v0.6?</a> was originally published in <a href="https://medium.com/ante-labs">Ante Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ante hosts Blockchain Commitments]]></title>
            <link>https://medium.com/ante-labs/ante-hosts-blockchain-commitments-39574bf7b635?source=rss----d221c76a88ff---4</link>
            <guid isPermaLink="false">https://medium.com/p/39574bf7b635</guid>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[antes]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Ante]]></dc:creator>
            <pubDate>Thu, 30 Mar 2023 19:52:03 GMT</pubDate>
            <atom:updated>2023-03-30T19:52:03.235Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hYLr6Y-Dl2EuczCJ0Lj6hw.png" /></figure><h4>Explaining the Ante protocol</h4><p>Web3 has a trust issue. Too many projects depend on unreliable commitments with no recourse when exploits or rugs cause catastrophic losses. Even well-known actors end up pulling the “<a href="https://twitter.com/veryordinally/status/1632568942374912001">trust us</a>” card. Surely, we can do better.</p><p><a href="http://ante.xyz/">Ante</a> is a decentralized protocol that translates implicit trust assumptions (e.g., “protocol X is solvent” or “team Y won’t rug”) into explicit on-chain commitments: Ante Tests. Ante Tests are made credible via staked assets and can be verified in real time by anyone, paying out trustlessly if the commitment is broken.</p><p>These new on-chain trust signaling primitives form the potential building blocks for a decentralized trust ratings system.</p><h4>How does it work?</h4><p>The core pieces of the Ante protocol are:</p><ul><li><strong>Ante Tests</strong> = on-chain logic that verifies some condition is true/false</li><li><strong>Ante Pools</strong> = 2-sided pools that people stake or challenge assets in, whose payout is determined by the result of the Ante Test</li></ul><p>Staking/challenging activity reveals community trust in the tested conditions and can be used to impute a decentralized trust score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RyqyXY4W5yU4Q_rEit1G5Q.gif" /></figure><h4>What’s the benefit of using Ante?</h4><p><strong>For web3 project teams:</strong> Credibly signal commitment to your most important trust guarantees and earn decay fees off challengers! (<a href="http://use.ante.xyz/">Learn more</a>)</p><p><strong>For web3 users:</strong> Compare projects based on publicly verifiable trust scores or get paid out on objectively defined failures without trusted intermediaries (<a href="https://app.ante.finance/">see live commitments</a>)</p><p><strong>For new web3 developers:</strong> Deploy your first smart contract and potentially get paid for it (<a href="https://docs.ante.finance/">view docs</a>)</p><p><strong>For security experts:</strong> Find flawed commitments and get paid to make web3 safer (<a href="https://app.ante.finance/">see live commitments</a>)</p><h4>Ante: web3-native trust signaling</h4><p>Ante can facilitate trustless alignment between users, projects, auditors, and investors — when there is shared skin in the game, it becomes everyone’s best interest to uphold the commitments defined in Ante Tests.</p><p>Additionally, as an on-chain trust signal available to everyone, builders can reference Ante Tests as a “trust oracle” public good, increasing future interoperability.</p><p>Making trust in the space explicit can help web3 reach its potential! Check out live commitments on the <a href="https://app.ante.finance/">web app</a>, follow Ante on <a href="https://twitter.com/antefinance">Twitter</a>, and join the <a href="https://discord.gg/ante">Discord</a> to discuss the latest Ante news.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39574bf7b635" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ante-labs/ante-hosts-blockchain-commitments-39574bf7b635">Ante hosts Blockchain Commitments</a> was originally published in <a href="https://medium.com/ante-labs">Ante Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ante Test failure investigation: TVL plunge test]]></title>
            <link>https://medium.com/ante-labs/ante-test-failure-investigation-tvl-plunge-test-f5dca73811a4?source=rss----d221c76a88ff---4</link>
            <guid isPermaLink="false">https://medium.com/p/f5dca73811a4</guid>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[antes]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Ante]]></dc:creator>
            <pubDate>Tue, 20 Dec 2022 05:29:17 GMT</pubDate>
            <atom:updated>2022-12-20T05:29:17.164Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XBVIeFL-a65hpSujT8aUHQ.png" /></figure><p>Before we get into the investigation: <a href="https://www.ribbon.finance/">Ribbon</a>’s TVL is at normal levels and funds in their vaults are unaffected.</p><p>Due to Ante v0.5 treating test reversions as failures, a missed edge case caused the <a href="https://app.ante.finance/contract/0x1/0xc7b9768AFa59D4CF820C9f6479fAF0b916c18B9d">Ante Test</a> checking Ribbon vault balances to fail, resulting in funds staked in the test being paid out to test challengers.</p><p>We informed the Ribbon team immediately and began working on an updated version of the test with the edge case removed, which is now staked <a href="https://app.ante.finance/contract/0x1/0x83cA192d41892fDdb62C53576A7CEaB3A4ed90f8">here</a>.</p><p>So why did the test fail?</p><h4>Missed check in the Ante Test</h4><p>To recap, each Ante Test contains a checkTestPasses function that contains the main test logic. The Ribbon TVL test has:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7lne5yg3R80bFOY2FOqzrg.png" /><figcaption><a href="https://github.com/antefinance/ante-community-tests/blob/main/contracts/ribbon/AnteRibbonV2ThetaVaultPlungeTest.sol#L65-L73">AnteRibbonV2ThetaVaultPlungeTest.sol</a>, lines 65–73</figcaption></figure><p>If any of the tested Theta Vault balances drop below its corresponding failure threshold, the test fails. Pretty straightforward so far! What about calculateAssetBalance?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wi4WDJEOTBsnx91sCrxAWw.png" /><figcaption><a href="https://github.com/antefinance/ante-community-tests/blob/main/contracts/ribbon/AnteRibbonV2ThetaVaultPlungeTest.sol#L49-L60">AnteRibbonV2ThetaVaultPlungeTest.sol</a>, lines 49–60</figcaption></figure><p>Funds deposited in Ribbon Theta Vaults can be in one of two locations: the Ribbon vault itself, or <a href="https://www.opyn.co/">Opyn</a>. Summing the two balances should give a true picture of total Ribbon vault assets. Indeed, this is how the Ribbon vault’s own totalBalance function works.</p><p>Each week, Ribbon closes out its Opyn position in closeRound and opens a new position in rollToNextOption. During this window (~1.5 hrs), 100% of funds live in the Ribbon vault.</p><p>One might assume that during this time, opynVault.collateralAmounts[0] would return the value 0.</p><pre>[delegatecall][15796][Controller].getVault(<br>  _owner=[Ribbon Finance: ETH Covered Call V2], <br>  _vaultId=63<br>) → ((<br>  shortOtokens=[], <br>  longOtokens=[], <br>  collateralAssets=[], <br>  shortAmounts=[], <br>  longAmounts=[], <br>  collateralAmounts=[]<br>))</pre><p><a href="https://tx.eth.samczsun.com/ethereum/0x33507436546cee4328d480cf7cdba14ef493328d13d24401fb87794917bd34dd">Uh-oh</a>.</p><p>It turns out that when the Opyn vault is settled, it doesn’t just zero out the collateral amounts, it straight-up deletes it. You can follow the call trace <a href="https://tx.eth.samczsun.com/ethereum/0x9daaff2b54b4413f7939b3db0ffb75f2aef29d8c342bbe8d9349159614844950">here</a>:</p><ol><li>RibbonThetaVaultWithSwap.closeRound → VaultLifecycleWithSwap.settleShort → Controller.operate → _runActions on ActionType.SettleVault</li><li>This calls _settleVault, which includes the <a href="https://github.com/opynfinance/GammaProtocol/blob/841f81d9d05da9d27277b5775edfbb48c4012d2a/contracts/core/Controller.sol#L963">line</a> delete vaults[_args.owner][_args.vaultId];, clearing out the collateralAssets array</li></ol><p>Any time the test tries to access opynVault.collateralAsset[0] during an Opyn vault change, it will revert with panic code 0x32(array accessed at an out-of-bounds or negative index).</p><p>If otherwise unchecked, this revert would typically bubble back up to the Ante Pool and revert the checkTest transaction. But Ante Pool doesn’t ignore reversions.</p><h4>Test reversions treated as failures</h4><p>In Ante v0.5, Ante Pools treat test reversions as failures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QJh8kOqNkGRDUZXMTLRHUg.png" /><figcaption><a href="https://github.com/antefinance/ante-v05-core/blob/v0.5/contracts/AntePool.sol#L567-L573">AntePool.sol</a>, lines 567–573</figcaption></figure><p>This design choice was made in Ante v0.5 to guard against attacks such as <a href="https://consensys.github.io/smart-contract-best-practices/attacks/denial-of-service/#gas-limit-dos-on-a-contract-via-unbounded-operations">block stuffing</a> that could be used to prevent a test from failing.</p><p>However, the tradeoff is that if a test could be made to revert, an attacker could trigger test failure. Ante v0.5&#39;s <a href="https://github.com/antefinance/ante-v05-core/tree/v0.5/audit">audits</a> noted this possibility in the form of a <a href="https://docs.soliditylang.org/en/v0.8.12/control-structures.html#try-catch">63/64 gas forwarding</a> attack. While none of the current live tests are believed to be vulnerable to the gas forwarding exploit, a flawed test that reverts could still trigger false test failure as it did with the Ribbon test.</p><p>When the challenger <a href="https://etherscan.io/tx/0x33507436546cee4328d480cf7cdba14ef493328d13d24401fb87794917bd34dd">checked the test</a> during the the short period each week (&lt;1% of the time) where the test would revert, the test was treated as having failed and the payout triggered.</p><h4>Resolving the revert edge case</h4><p>The updated Ribbon Theta Vault TVL Plunge Ante Test makes several changes. First, the test checks that collateralAssets is not empty and ignores it if it is, avoiding the revert scenario.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-DA0aAJ2hVUtxOHF7OyBeQ.png" /></figure><p>The updated test was tested on a mainnet fork against the <a href="https://docs.google.com/spreadsheets/d/1cj-iwutySJm0xUEo0WAGAgjH7XPwZiLgDqDkpVIIYFM/edit?usp=sharing">historical blocks</a> where the previous test failed and successfully avoided test reversion, confirming the edge case was removed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-F8w83rDJPVMtZiyu4HBrQ.png" /></figure><h4>Making the test reflect current vaults</h4><p>At the time the original test was written, there were only two V2 Theta Vaults (ETH and WBTC covered calls). When adding the additional Theta Vaults that had been introduced since then to the test, the original method of determining vault asset using vaultParams no longer worked for all potential Theta Vaults.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Dx6M4p9pOK-mSY19awxbw.png" /><figcaption>No on-chain reference was 100% reliable for determining vault asset</figcaption></figure><p>Thus, the updated test also stores the vault asset so that it can be referenced reliably under the assumption that each Ribbon vault’s collateral asset will not change (valid under the current implementation of the vaults).</p><p>The stETH vault, in particular, uses a different balance calculation formula due to being able to take user deposits in WETH and stETH but depositing wstETH in Opyn, as well as stETH and wstETH having a variable exchange rate. To accommodate the stETH vault, the updated test supports multiple vault assets and includes a conversion check for wstETH. Here’s what the final calculateVaultBalance looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oog4rDvXdAUzq-2VgglGAg.png" /></figure><h4>Future proofing the test</h4><p>In addition to the technical fixes, the updated test also allows an admin to add new vaults to test as well as sunset deprecated vaults. This can prolong the test’s life by allowing it to continue reflecting the actual portfolio of Ribbon Theta Vaults. However, doing so responsibly would require maintenance by a trusted individual/entity. The updated test will still work as intended on its current set of vaults without maintenance.</p><p>As the various vault intricacies have shown, additional future proofing could also be done by having a standard way to safely measure TVL on-chain. Ante community members are currently discussing various ways to prototype standardized TVL “oracles” that builders could reference.</p><h4>The path forward</h4><p>The updated Ribbon Theta Vault Test is live: check it out <a href="https://app.ante.finance/contract/0x1/0x83cA192d41892fDdb62C53576A7CEaB3A4ed90f8"><strong>here</strong></a>! Special thanks to <a href="https://www.zellic.io/">Zellic</a> and the Ribbon team for reviewing the updated test.</p><p>In Ante v0.6 (in audit), test reversions are NOT treated as failures, eliminating false test failures due to reversion.</p><p>Ante Tests provide the flexibility to encode elements of trust and make them available on-chain so that others can build upon them in a decentralized way. Decentralized trust ratings are still in their early stages, but thanks to the Ribbon team and community for being an early partner in pioneering this new form of on-chain trust signaling!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5dca73811a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ante-labs/ante-test-failure-investigation-tvl-plunge-test-f5dca73811a4">Ante Test failure investigation: TVL plunge test</a> was originally published in <a href="https://medium.com/ante-labs">Ante Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ante x Zellic: Aligned Auditing]]></title>
            <link>https://medium.com/ante-labs/ante-x-zellic-aligned-auditing-142925717cb2?source=rss----d221c76a88ff---4</link>
            <guid isPermaLink="false">https://medium.com/p/142925717cb2</guid>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[auditing]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[zellic]]></category>
            <category><![CDATA[antes]]></category>
            <dc:creator><![CDATA[Ante]]></dc:creator>
            <pubDate>Thu, 03 Nov 2022 20:47:48 GMT</pubDate>
            <atom:updated>2023-05-08T14:33:50.808Z</atom:updated>
            <content:encoded><![CDATA[<p>Smart contract auditors have an image problem. During the exuberance of the bull market, the shortage of strong auditors and resulting audit prices brought in a flood of entrants focused around quick scalable code audits to meet the insane demand. However, this came at a price: average audit quality suffered, with many of 2021 and 2022’s hacks involving audited protocols!</p><p>At the end of the day, there is a mismatch between auditor incentives and protocol safety. Auditors get paid upon completion of the audit, but there is no penalty for missing bugs or reward for continued safe protocol operation. So how do you tell the good audits from the bad? If you’re not a smart contract expert, you don’t… until it’s too late. It’s no surprise then that community trust in audits is tenuous at best.</p><h3>samczsun on Twitter: &quot;glad they had a spare bus for the internhttps://t.co/Bf1Sa2OBFe / Twitter&quot;</h3><p>glad they had a spare bus for the internhttps://t.co/Bf1Sa2OBFe</p><p>Of course, the real victims of protocol failures are the end users who trusted both the project team and auditors. But does it have to be this way?</p><ul><li>What if auditors were incentivized to make sure a protocol is safe past the completion of an audit?</li><li>What if protocols that break after being audited could recoup part of their audit fees?</li><li>What if there was a hard-to-fake way to signal trust on-chain?</li></ul><h3>A bit whale-ish AF ⚙️ on Twitter: &quot;now if only there was some kind of on-chain non-custodial pool that could make programmatic payouts upon proof of rektness... oh wait ⚙️ / Twitter&quot;</h3><p>now if only there was some kind of on-chain non-custodial pool that could make programmatic payouts upon proof of rektness... oh wait ⚙️</p><p>As it turns out, we already know of an on-chain primitive that allows trustless alignment between parties… Ante Tests!</p><p>We’ve seen DeFi protocols like Ribbon and MetaStreet as well as NFT projects like DeFi Girls and Anoncats use staked Ante Tests to make on-chain commitments backed by crypto.</p><p><strong>Auditors can stake Ante Tests as financial proof of auditor confidence.</strong></p><p>Why does this make sense?</p><ol><li>Auditors are already familiar with the protocol codebase through the audit process. They (along with protocol teams) are ideally positioned to identify protocol invariants that should not break and define them on-chain using Ante Tests.</li><li>Staking Ante Tests creates extended alignment between auditor and protocol. If the protocol breaks and the Ante Test fails, the auditor’s stake is paid out to challengers (e.g. protocol users). It’s like slashing bad auditors!</li><li>This allows good auditors to make credible claims about their quality, because they now have skin in the game.</li></ol><p>To take the first step towards better auditor-project alignment, our friends at Zellic have staked Ante’s Ante Tests as a signal of confidence behind their <a href="https://medium.com/ante-finance/ante-v0-5-zellic-audit-walkthrough-859dc9c74a47">audit of Ante v0.5</a>. Check them out <a href="https://v05.app.ante.finance/contract/0x1/0xDC99AD0b3FDdAE6522e26c33439a0b0b476172c5">here</a> and <a href="https://v05.app.ante.finance/contract/0x1/0x2EdC35B39BFBca6A52eA35612C2684D3D7654763">here</a>.</p><p>Between an auditor who stakes part of their fee behind the success of your project and an auditor who doesn’t, who would you trust more?</p><p>The actions of a few audit firms lost a lot of user trust and put a black mark on the entire profession. Ante Tests let you start trusting — and verifying — your auditors again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=142925717cb2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ante-labs/ante-x-zellic-aligned-auditing-142925717cb2">Ante x Zellic: Aligned Auditing</a> was originally published in <a href="https://medium.com/ante-labs">Ante Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ante v0.5 Zellic Audit Walkthrough]]></title>
            <link>https://medium.com/ante-labs/ante-v0-5-zellic-audit-walkthrough-859dc9c74a47?source=rss----d221c76a88ff---4</link>
            <guid isPermaLink="false">https://medium.com/p/859dc9c74a47</guid>
            <category><![CDATA[zellic]]></category>
            <category><![CDATA[antes]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[audit]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Ante]]></dc:creator>
            <pubDate>Mon, 08 Aug 2022 21:24:16 GMT</pubDate>
            <atom:updated>2022-11-21T21:38:46.116Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jtIaemvfbidkXmnRfTK_Qw.png" /></figure><p>As a team trying to increase trust in a trustless space, Ante strongly believes in conducting regular internal and 3rd-party code audits as a part of any protocol’s comprehensive security stance. With quality audit slots massively backlogged earlier this year, though, we released our own <a href="https://medium.com/ante-finance/ante-v0-5-code-tour-f3ead9acf9fd">internal audit</a> of Ante v0.5 in late March. Well, you no longer have to take our word that Ante is SAFU — we’re excited to finally announce the results of our audit by Zellic!</p><h4>About Zellic</h4><p><a href="http://zellic.io/">Zellic</a> was founded by members of the #1 ranked competitive hacking (CTF) team in ZA WARUDO. They gained significant attention when they teamed up with <a href="https://twitter.com/samczsun">samczsun</a> in investigating the Wormhole hack and are regularly called upon to investigate ongoing hacks.</p><h3>Findings</h3><p>The audit was conducted on the <a href="https://github.com/antefinance/ante-v0-core/tree/fdd0d8d68a5697415cde511aa5dc98c469871bb7"><strong>ante-v0–core</strong></a> repo, commit fdd0d8d68a5697415cde511aa5dc98c469871bb7. 5 findings were reported, with 1 critical severity, 1 high severity, 1 medium severity, and 2 low severity.</p><h4>Finding 1: <strong>Ability to force tests to fail with gas limit (Critical)</strong></h4><p>One quirk of the EVM is that by default, only up to 63/64 of the remaining gas can be allocated to an external call. This was implemented in EIP114 in order to reduce the attack surface area for call stack depth related exploits; however, Solidity also contains a <a href="https://docs.soliditylang.org/en/v0.8.12/control-structures.html#try-catch">quirk</a> where try/catch reverts before the last 1/64 of gas is consumed. This means that there could be a scenario in which gas is manually set to an amount:</p><ol><li>low enough that the external call to checkTestPasses on the Ante Test reverts due to lack of gas</li><li>high enough that the overall checkTest call to the Ante Pool is still able to complete with the 1/64 remaining gas</li></ol><p>An Ante Pool where this condition can be satisfied can generate a false test failure, incorrectly allocating staker funds to challengers.</p><p><strong>Risk Analysis</strong></p><p>Before you get too alarmed, all funds currently staked in Ante are SAFU!</p><p>To check if any of the currently deployed Ante Pools are at risk of being exploited, we checked current gas usage for each test’s checkTestPasses call vs. the gas required to complete the outer _checkTestNoRevert and checkTest calls. Basically, if the cost of checkTestPasses exceeds the cost of the remaining computations by over <strong>63x</strong>, the exploit can be triggered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pjZcrjMhO6E_fnY8tel7qQ.png" /><figcaption>Gas usage analysis on current Ante Pools with the most AVL</figcaption></figure><p>Based on our gas analysis, the largest ratio reached is ~15x, with most tests falling in the 0.2–2x range. This means that even the most computationally expensive Ante Tests currently deployed have a safety factor of over 4x. Based on this, we believe that user funds in Ante v0.5 are not currently at risk from this exploit.</p><p>That being said, we have some advice for any Ante Test writers in v0.5:</p><ol><li><strong>Keep it simple</strong>— this exploit becomes feasible when checkTestPasses is gas-intensive, so keeping the actual test logic simple makes it highly unlikely to exploit.</li><li><strong>Check your tests</strong>— the minimum amount of gas used after the external call is somewhere around ~110,000 units. If the cost of checkTestPasses exceeds 63x that amount, or ~6,930,000 units, the exploit can be triggered. We’re adding a simple script to the community test repo that makes it easy for test writers to check gas usage for v0.5 Ante Tests.</li></ol><p><strong>The Fix</strong></p><p>We evaluated a number of approaches for fixing this attack vector and decided that in Ante v0.6, we plan on implementing magic return values from the Ante Test in a way that allows the Ante Pool to distinguish between an intentional value and a revert due to out-of-gas error. This does mean that v0.5 Ante Tests remain vulnerable to this exploit, but as mentioned, we will be providing test writers with a tool to simulate gas usage of their tests to minimize the chance of an exploitable Ante Test being deployed.</p><h4>Finding 2: Number of challengers is constrained by block gas limit (High)</h4><p>When an Ante Test is checked and found to fail, the Ante Pool calculates the amount of challenger capital eligible for payout in an internal function _calculateChallengerEligibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EVaDcLEprGJaBevKoDjliw.png" /><figcaption>AntePool.sol, lines 549–563</figcaption></figure><p>Notably, this was implemented with a loop through the array of challengers, meaning that the amount of gas used scales linearly with the number of challengers — basically a O(n) computation.</p><p>Since the gas in a single block is limited, if the number of challengers gets too high, you could perform a block stuffing attack and basically cause the checkTest call to fail. The result: an attacker can prevent an Ante Test from failing.</p><p><strong>Attack scenarios:</strong></p><ul><li>A staker realizes that a test is going to fail and uses this attack to prevent the checkTest call from triggering test failure until they have unstaked their funds</li><li>A challenger could prevent a test from failing while additional users continue staking the test, adding to the potential payout challengers receive once the test fails</li></ul><p>This is a previously known issue as mentioned in our <a href="https://docs.ante.finance/antev05/about/security#known-issues">Docs</a> and specifically excluded from the Ante bug bounty. However, Zellic was able to help quantify the feasibility of this attack vector. Zellic’s analysis found that the number of challengers required to hit the gas limit would be somewhere on the scale of <strong>~3,000 challengers</strong>, costing a potential attacker roughly <strong>$60k USD</strong> in challenged funds and gas fees at the time of the audit.</p><p><strong>The fix:</strong></p><p>We instituted a maximum number of challengers that can challenge each Ante Pool. While it seems unlikely that any test would hit 800+ challengers in the near term, we are also paying particular attention in future versions of the protocol to performing calculations in constant time vs. linear time when possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ReCTHcU0NoH7YWsso79-Mg.png" /></figure><p>The fix is implemented and is live in the v0.5 contracts on Avalanche and all subsequent chains (v0.5 Ante Tests deployed on Ethereum remain vulnerable to this block stuffing attack).</p><h4>Finding 3: Bypassable minimum challenger stake (Low)</h4><p>When challenging an Ante Test, we enforce a minimum challenger stake (0.01 ETH) to discourage malicious challengers from putting a trivial challenge stake in each pool in order to run generalized front-running bots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1yPaMwtT7hvu32c40bZhHg.png" /></figure><p>However, we did not check that when a challenger removes partial challenged funds, the remaining funds still exceed the minimum challenger stake. Thus, a challenger could bypass the minimum challenger stake by staking the minimum amount, then withdrawing everything except 1 base unit (0.00000001 ETH).</p><p>This by itself is a fairly inconsequential bug, but when combined with Finding 2, it reduces the cost of a block stuffing attack on Ante to the previously stated $60k range.</p><p><strong>The fix</strong></p><p>We added a check on unstake that checks that the amount remaining after unstake is greater than the minimum challenge; otherwise, the entire challenged amount must be removed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rWQCTgMEwJ8qW3fq6WaWmg.png" /></figure><p>The fix is implemented and is live in the v0.5 contracts on Avalanche and all subsequent chains (v0.5 Ante Tests deployed on Ethereum still exhibit this bug).</p><h4>Finding 4: Reentrant checkTest allows pool draining (Medium)</h4><p>Because checkTest does not prohibit reentrancy, an attacker could write a malicious Ante Test that makes an external call to an attacker contract. This could enable an attacker to call checkTest on a failing test multiple times, claiming the 5% first verifier bounty multiple times and draining the Ante Pool. To be exploitable, an Ante Test would need to:</p><ol><li>be able to return false without reverting</li><li>not have a view or pure checkTestPasses function</li><li>call a function on the tested contract that then makes an external call to an attacker-controlled contract</li></ol><p>No live Ante Tests satisfy these requirements and so no user funds are currently at risk for this particular attack.</p><p><strong>The fix</strong></p><p>We implemented ReentrancyGuard on AntePool and added the nonReentrant modifier to all relevant functions in AntePool to close off this attack vector.</p><blockquote>A brief aside on our philosophical approach to the possibility of malicious Ante Tests: the Ante team strongly believes that community-driven test writing is essential to reaching code coverage at scale. Where we can (e.g. implementing the nonReentrant fix) we try to implement checks/safeguards, but as an open-source protocol, we also can’t entirely prevent people from writing bad or even malicious Ante Tests. We <em>do</em> believe that Ante Tests’ simple nature makes it easier to understand and spot malicious tests. We are also exploring various ways to rate the quality of Ante Tests (e.g. beyond the minimum bar of “isn’t trivially true” and “works roughly as intended”, tests that are resistant to flash loan manipulation and minimize external attack vectors would be considered higher quality) in a decentralized and scalable way.</blockquote><h4>Finding 5: Late challengers receive no payout (Low)</h4><p>Challengers that stake funds within 12 blocks of test failure are not eligible for payouts. Because AntePool only tracks the block number of the most recent challenge, this produces one minor edge case where if a long-time challenger happens to add additional funds within 12 blocks of a test failure, they will receive no payout, even for their older challenge.</p><p>The 12-block window was implemented in order to discourage generalized front-running (e.g. scenario where someone monitors for checkTest and is able to “steal” the 5% first verifier bounty)</p><p>We decided that the benefits of keeping the 12-block delay outweigh the low risk of a late challenger.</p><h3>Conclusion</h3><p>Code security is a never-ending process, and getting trusted 3rd-party audits should be a part of every responsible protocol’s security toolbox. The Ante team would like to thank the Zellic team for being super-responsive to work with and for their thorough auditing. You can read their full report <a href="https://github.com/antefinance/ante-v0-core/blob/v0.5/audit/2022-05-22%20Ante%20v0.5%20Zellic%20Audit%20Report.pdf">here</a>.</p><p>Also, we have some cool new stuff in the works, including Ante v0.6! Follow us on <a href="https://twitter.com/antefinance">Twitter</a> and join the <a href="http://discord.ante.xyz/">Discord</a> to stay on top of the latest Ante news. We are looking forward to continuing to work with such a high quality partner in Zellic!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=859dc9c74a47" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ante-labs/ante-v0-5-zellic-audit-walkthrough-859dc9c74a47">Ante v0.5 Zellic Audit Walkthrough</a> was originally published in <a href="https://medium.com/ante-labs">Ante Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ante Test Series #6: Dai Peg Test]]></title>
            <link>https://medium.com/ante-labs/ante-test-series-6-dai-peg-test-2a3a6a3ee59a?source=rss----d221c76a88ff---4</link>
            <guid isPermaLink="false">https://medium.com/p/2a3a6a3ee59a</guid>
            <category><![CDATA[dai]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <dc:creator><![CDATA[delalunia]]></dc:creator>
            <pubDate>Fri, 10 Jun 2022 21:15:22 GMT</pubDate>
            <atom:updated>2022-06-10T21:15:21.893Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello there and gm frens!! We’re here today to talk about one of our most popular and simple, yet useful tests that one can write, a price peg test. If you missed our last writeup about Olympus, feel free to find it <a href="https://medium.com/ante-finance/ante-test-series-5-olympus-v2-53fae9a47b9f">here</a>!</p><p>One of our community members, <a href="https://github.com/waynebruce0x">waynebruce</a>, wrote a peg test for the Dai stablecoin, <a href="https://github.com/antefinance/ante-community-tests/blob/main/contracts/dai/Ante_DaiPegTest.sol">Dai Peg Test</a>, a while back, and we’ll go over it today!</p><p>Dai by <a href="https://makerdao.com/en/">MakerDao</a>, was designed to counter one of the problems other cryptocurrencies were having, which was unstable prices. Dai aims to change that by being a decentralized, unbiased cryptocurrency that is pegged to the US dollar. This brought along the term stablecoin, and as long as the Keepers maintain the 1 US Dollar target price, then the goal has been achieved.</p><p>Now to the Ante Test in question. This turns out to revolve around 1 crucial point, is the price of Dai within reasonable bounds as described by the Maker Protocol and understood by its users.</p><p>To get to that point, let’s start with the checkTestPasses() function:</p><pre>function checkTestPasses() public view override returns (bool) {<br>    (, int256 price, , , ) = priceFeed.latestRoundData();<br>    return (95000000 &lt; price &amp;&amp; price &lt; 105000000);<br>}</pre><p>We can see that we’ll return true if the price is between 0.95 and 1.05 US Dollars.</p><p>This price we get by using latestRoundData() from Chainlink’s <a href="https://docs.chain.link/docs/get-the-latest-price/">aggregator interface</a>.</p><p>Moving on up, we see that the constructor for the Ante Test initializes the protocol, Dai, the contract in question, Dai’s address, and the Dai/USD <a href="https://etherscan.io/address/0xAed0c38402a5d19df6E4c03F4E2DceD6e29c1ee9">aggregator</a> deployed by Chainlink.</p><pre>constructor() {<br>    protocolName = &quot;DAI&quot;;<br>    testedContracts = [DaiAddr];<br>    priceFeed = AggregatorV3Interface(0xAed0c38402a5d19df6E4c03F4E2DceD6e29c1ee9);    }</pre><p>And that’s it to this Dai Peg Ante Test! At it’s core, there’s just 2 important parts to a peg test, the value that the peg needs to be held at, and getting that value.</p><p>What’s interesting here will be analyzing what could cause a failure in this test.</p><p>The first way this test could fail is if DAI’s price fluctuates outside its range of 0.95 and 1.05. If the test is checked at that time, then it can fail. And this has happened before, looking at CoinGecko’s <a href="https://www.coingecko.com/en/coins/dai/usd#panel">historical chart for Dai</a>, back in November of 2019 and March of 2020.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H5SXZ5sxyUf1hpETyL6_iA.png" /><figcaption>Value of Dai from Nov 2019 to Feb 2022</figcaption></figure><p>As the price is what determines whether or not the test fails, the second critical piece then is how we fetch the price, in this case, the Chainlink Aggregator. If an attacker were able to manipulate or trick the aggregator to return a value that doesn’t actually represent the true Dai price, than the test could also fail.</p><p>Food for thought anyway, it’s always good to consider what different ways a test can fail and see if we can make sure that these points are carefully considered when writing an Ante Test!</p><p>As the skeleton for this test is relatively basic, it can be expanded to incorporate different types of pegs depending on what is being called for.</p><p>For example, regarding Tether, this <a href="https://github.com/antefinance/ante-community-tests/blob/main/contracts/tether/Ante_USDTPegTest.sol">Ante Test</a> written by <a href="https://github.com/raddy">raddy</a> outlines the fact we care more about the dropping of Tether value, so the test is written to only check if its value drops below 0.90 US dollar.</p><p>And then moving even further! This <a href="https://github.com/antefinance/ante-community-tests/blob/main/contracts/iron/AnteIronPegTest.sol">Iron Peg Holds Test</a> written by <a href="https://github.com/a-deva">a-deva</a> highlights how we can take a simple peg test and take it even further! This one is a bit more complicated to go through in this post, so we’ll revisit it another time to go deeper into it.</p><p>And that’s it for this week! Please feel free to come and check out the various tests that have already been written in the <a href="https://github.com/antefinance/ante-community-tests">Ante Community Github</a>. Join us at our <a href="https://discord.com/invite/ante">Discord</a> to talk web3, interesting protocols, Ante Tests, or just hang out! And follow us on <a href="https://twitter.com/AnteFinance">Twitter</a> to see the latest news and updates we have! Till next time everybody!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a3a6a3ee59a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ante-labs/ante-test-series-6-dai-peg-test-2a3a6a3ee59a">Ante Test Series #6: Dai Peg Test</a> was originally published in <a href="https://medium.com/ante-labs">Ante Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ante Test Explained: LlamaPay]]></title>
            <link>https://medium.com/ante-labs/ante-test-explained-llamapay-ed5c16be721b?source=rss----d221c76a88ff---4</link>
            <guid isPermaLink="false">https://medium.com/p/ed5c16be721b</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[antes]]></category>
            <dc:creator><![CDATA[Ante]]></dc:creator>
            <pubDate>Thu, 12 May 2022 22:07:28 GMT</pubDate>
            <atom:updated>2022-05-12T22:07:28.141Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MqgU60DZjpYYAR1M-xgtsA.png" /></figure><p><em>This post is intended to be a technical overview of the LlamaPay Ante Test and its mechanics.</em></p><h3>Background</h3><p><a href="https://llamapay.io/"><strong>LlamaPay</strong></a> is a multi-chain protocol that makes it easy to automate streaming payment transactions. Payers can deposit funds and create payment streams, while recipients can withdraw the funds they have accumulated at any time, eliminating the need for regular manual transactions by the payer. LlamaPay also simplifies the process of pausing/resuming streams, and is significantly more gas efficient than other similar products at the time of writing.</p><p><a href="https://www.ante.finance/"><strong>Ante</strong></a> hosts on-chain commitments (”Ante Tests”) staked with crypto that check key, live assumptions (e.g. multisig balance, protocol solvency) and pay out when code fails. This aligns teams and users — responsible teams can demonstrate “skin in the game” by staking their Ante Tests (which anyone can also challenge or stake), boosting their “<strong>Decentralized Trust Score</strong>”. Making code trust explicit results in a safer, more composable Web3 ecosystem: developers can reference Ante trust scores to build more safely on top of protocols, and users can more clearly see community trust in real-time.</p><h3>AnteLlamaPayTest</h3><p><a href="https://github.com/antefinance/ante-community-tests/blob/main/contracts/llamapay/AnteLlamaPayTest.sol">Code</a>; <a href="https://app.ante.finance/#/contract/0x18fCb9704D596Ac3cf912F3Bd390579b8c22684F">Live test</a></p><p><strong>AnteLlamaPayTest</strong> checks that the last payer update always falls before the current block timestamp. This is important because if this invariant was violated, someone could claim more funds than they they should be able to — it would be like time traveling and stealing future earnings to use now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YAqhNVdqYGFpT9PvTaaD6g.png" /><figcaption>Time travel problems? Better call the llamas!</figcaption></figure><p>How do we check that this invariant holds across each stream represented by an arbitrary token-payer combination? A naive approach might be to loop through all tokens and payers. However, this could easily become expensive as LlamaPay grows and eventually become susceptible to a block stuffing attack. Also, LlamaPay instances contain no iterable list of payers (only mappings), so we have no easy way to loop through all payers in a LlamaPay contract. Deploying an Ante Test for each LlamaPay instance is another possibility, but also gets expensive.</p><p>What we ended up implementing is the first example of an Ante Test that can take user input and use it when checking the test!</p><h4>How it works</h4><p>Due to the simple nature of Ante v0.5, AntePool calls checkTest without allowing any parameters to be passed in. We can still incorporate user input parameters by adding state variables and setter functions to the AnteTest itself (there are other considerations that we’ll discuss later).</p><p>The two key variables we take user input for are:</p><ul><li>tokenAddress - used to determine which LlamaPay instance to check</li><li>payerAddress - used to determine which payer to check</li></ul><p>These are set using the setTokenAddress and setPayerAddress functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xIq-fjR226ZzeDVY" /><figcaption>AnteLlamaPayTest.sol, lines 64–77</figcaption></figure><p>In checkTestPasses, we check for the corresponding LlamaPay instance for the token address provided, then compare the last payer update timestamp for the specified payer against the current block timestamp.</p><h3>AnteLlamaPayTestChallengerWrapper</h3><p><a href="https://github.com/antefinance/ante-community-tests/blob/main/contracts/llamapay/AnteLlamaPayTestChallengerWrapper.sol">Code</a></p><p>Some of you may have already spotted an issue with the AnteLlamaPayTest above. If a user needs to make a call to the AnteTest to set the appropriate parameters to check, followed by a separate call to the AntePool to check the test, a challenger could potentially be front-run while trying to verify the transaction. Imagine a malicious actor preventing the LlamaPay test from failing by front-running the verification transaction and changing the test parameters checked. In order to address this scenario, we implemented a wrapper contract that allows a user to challenge and verify the LlamaPay Ante Test without being frontrun.</p><h4>How it works</h4><p>AnteLlamaPayTestChallengerWrapper is basically a passthrough for most challenger functions, with one key difference: it allows user to set parameters and check test in the same transaction, avoiding the front-running issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*taszoG9O38U8BLlO" /><figcaption>AnteLlamaPayTestChallengerWrapper.sol, lines 80–86</figcaption></figure><p>The reason we include challenger functions in the wrapper is because the v0.5 AntePool checks that msg.sender has challenged the pool, so a user needs to challenge the pool through the wrapper in order to be eligible to check the test using the wrapper.</p><p>Another consequence of AntePool using msg.sender to track users is that if we were to implement a single shared wrapper contract, any stake/challenge coming from the wrapper looks like it’s coming from the same source to the Ante Pool. This means that in order to allow multiple users to interact with the Ante Pool, the wrapper would need to keep track of each challenger’s state including accumulated decay fees, etc. To minimize the complexity of the wrapper contract, we opted to instead make each wrapper Ownable so that only a single user can use it to interact with the LlamaPay pool. Each challenger will need to deploy their own version of the wrapper contract in order to check the LlamaPay test in a frontrun-resistant way.</p><h3>How to use the LlamaPay Ante Test</h3><h4><strong>Staking</strong></h4><p>If you are staking the LlamaPay Ante Test, you can interact with the pool the same way you would with any other Ante Test; either via <a href="https://app.ante.finance/#/contract/0x18fCb9704D596Ac3cf912F3Bd390579b8c22684F">web app</a> or <a href="https://etherscan.io/address/0x18fCb9704D596Ac3cf912F3Bd390579b8c22684F">directly</a> (e.g. via Etherscan).</p><h4><strong>Challenging</strong></h4><ol><li>Deploy the <a href="https://github.com/antefinance/ante-community-tests/blob/main/contracts/llamapay/AnteLlamaPayTestChallengerWrapper.sol">AnteLlamaPayTestChallengerWrapper</a> contract with the LlamaPay Ante Test and Ante Pool addresses as arguments; currently <a href="https://etherscan.io/address/0x62ca84def073e6788b4f68e387617e50c8d36ebf">0x62ca84def073e6788b4f68e387617e50c8d36ebf</a> and <a href="https://etherscan.io/address/0x18fCb9704D596Ac3cf912F3Bd390579b8c22684F">0x18fCb9704D596Ac3cf912F3Bd390579b8c22684F</a></li><li>Use the challenge() wrapper function to interact with the Ante Pool (e.g. via Etherscan or other preferred method)</li><li>To withdraw challenged funds, use the withdrawChallenge() or withdrawChallengeAll() wrapper functions</li></ol><h4><strong>Checking the Test</strong></h4><p>Using the wrapper you deployed, call setParamsAndCheckTest(), passing in the token address and payer address to check. If the test fails, you can use the claim() function to claim your share of the payout.</p><h3>Conclusion</h3><p>We all know DeFi can be a dangerous place. Smart contracts can be opaque to your average DeFi user, and bad actors abound. Ante helps make code risk explicit, helping you make informed decisions about which protocols you use. Staking their tests shows a core team’s alignment with the community and their commitment to responsible code security. It’s a hard-to-fake signal of confidence in their code (literally skin in the game).</p><p>If you would like to learn more about how Ante could be useful for your protocol team, please reach out to us at <a href="https://signup.ante.xyz/">signup.ante.xyz</a>, read the docs at <a href="http://docs.ante.finance/">docs.ante.finance</a>, or follow the team on <a href="https://twitter.com/AnteFinance">Twitter</a> and join our <a href="https://discord.gg/ante">Discord</a> for more web3 security discussion!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed5c16be721b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ante-labs/ante-test-explained-llamapay-ed5c16be721b">Ante Test Explained: LlamaPay</a> was originally published in <a href="https://medium.com/ante-labs">Ante Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ante Tests Explained: Ribbon Finance]]></title>
            <link>https://medium.com/ante-labs/ante-tests-explained-ribbon-finance-b41bfc597109?source=rss----d221c76a88ff---4</link>
            <guid isPermaLink="false">https://medium.com/p/b41bfc597109</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[antes]]></category>
            <category><![CDATA[ribbon]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Ante]]></dc:creator>
            <pubDate>Thu, 31 Mar 2022 06:21:09 GMT</pubDate>
            <atom:updated>2022-03-31T06:21:09.014Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G-PoBMOLcTR0GJC-eFW0cA.png" /></figure><p>This post is intended to be a technical overview of the Ribbon Ante Tests and their mechanics.</p><h3>Background</h3><p><a href="https://www.ribbon.finance/"><strong>Ribbon</strong></a> is a DeFi protocol that helps users access DeFi structured products. Their Theta Vault product offers yield through an automated options strategy (the main V2 products at the moment automate weekly covered call strategies).</p><p><a href="https://www.ante.finance/"><strong>Ante</strong></a> hosts real-time incentivized on-chain smart contract tests (”Ante Tests”) that pay out when code fails. This aligns teams and users and makes code trust explicit, resulting in a safer, more composable Web3 ecosystem. Responsible protocol teams can explicitly put “skin in the game” by staking their Ante Tests (which anyone can also challenge or stake), boosting their “<strong>Decentralized Trust Score</strong>”. In turn, developers can reference Ante trust scores to build more safely on top of protocols, and users can more clearly see community trust in protocols real-time.</p><h3>Ribbon TVL Plunge Test</h3><p><a href="https://github.com/antefinance/ante-community-tests/blob/main/contracts/ribbon/AnteRibbonV2ThetaVaultPlungeTest.sol">Code</a>; <a href="https://app.ante.finance/#/contract/0xc7b9768AFa59D4CF820C9f6479fAF0b916c18B9d">Live test</a></p><p><strong>AnteRibbonV2ThetaVaultPlungeTest</strong> checks that the TVL for any tested Ribbon V2 Theta Vault doesn’t fall by 90% from the time the test is deployed. While TVL is an imperfect metric for overall protocol success, it is a useful proxy for any number of catastrophic scenarios such as:</p><ul><li>Ribbon usage has declined precipitously</li><li>Ribbon funds have been drained by a hack/exploit</li></ul><p>Basically, if the TVL in the Ribbon V2 Theta Vaults has plunged over 90%, something catastrophic has likely befallen Ribbon.</p><h3>How it works</h3><p>The test checks the <a href="https://etherscan.io/address/0x25751853Eab4D0eB3652B5eB6ecB102A2789644B">ETH Covered Call V2</a> and <a href="https://etherscan.io/address/0x65a833afDc250D9d38f8CD9bC2B1E3132dB13B2F">WBTC Covered Call V2</a> Theta Vaults. Upon instantiating the Ante Test, the test iterates through the list of vaults and calculates the precise failure threshold for each vault by multiplying the current balance by the drop threshold — 10%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3p1-kVkllwW5LAyf7qq7fQ.png" /><figcaption>AnteRibbonV2ThetaVaultPlungeTest.sol, lines 38–44</figcaption></figure><p>When checkTestPasses() is called by a challenger, the test iterates through the same set of vaults and compares each vault’s balance to its corresponding failure threshold. If any of the vaults’ TVL is below its threshold, then the entire Ante Test fails and challengers can claim funds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*racoqnCZePvnnsTXK74TZA.png" /><figcaption>AnteRibbonV2ThetaVaultPlungeTest.sol, lines 65–73</figcaption></figure><p>Let’s take a closer look at how vault balances are calculated in the calculateAssetBalance() helper function. The underlying tokens controlled by the vault are split between two main contracts through the vault lifecycle:</p><ul><li>Opyn <em>MarginPool</em> contract when underlying has been used to mint call options</li><li>Ribbon vault contract in basically any other situation: if Ribbon users deposit mid-cycle; if all the options don’t sell out that week; if its auction profits; if users have queued for withdrawal but not withdrawn yet; if options have been settled for the week and not yet used to mint next week’s options</li></ul><p>The sum of these two balances represent the total current asset balance “in” a Ribbon vault (technically, tokens could also be held very briefly in the EasyAuction contract after people buy options but it is promptly transferred back to the Ribbon vault).</p><blockquote>Note that we also assume that there is only one type of collateral asset in a Theta Vault. This is currently true for the two vaults tested by this Ante Test, but as the contracts are upgradeable we can’t guarantee this will always be the case.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WWeQkGMUNnNxPvQ2XBCi8Q.png" /><figcaption>AnteRibbonV2ThetaVaultPlungeTest.sol, lines 49–60</figcaption></figure><p>The reason we don’t just use Ribbon’s totalBalance() function and roll our own calculation logic in an independent calculateAssetBalance() function is because we can increase the surface area of potential vulnerabilities covered.</p><p>If we were to use the internal Ribbon state to calculate balance, since the contracts are upgradeable, there is a potential situation where an attacker could seize upgrade permissions then replace the contract with a malicious one that steals the funds but doesn’t change vaultState.lockedAmount. Another possible attack vector could be a bug in the RibbonV2 Theta Vaults which allows an attacker to steal funds but leaves vaultState.lockedAmount unchanged. In either of these cases, an Ante Test checking Ribbon’s internal state variables for balance could show the test still passing even though funds were no longer SAFU.</p><blockquote>As a general principle, writing test logic that doesn’t depend strongly on the tested contract’s own internal state helps make the test more robust against false negatives.</blockquote><h3>Ribbon Multisig Token Test</h3><p><a href="https://github.com/antefinance/ante-community-tests/blob/main/contracts/ribbon/AnteRibbonMultisigRBNTest.sol">Code</a>; <a href="https://app.ante.finance/#/contract/0x64408eF5356f229b3E007370A3aB099cf63e5F18">Live test</a></p><p><strong>AnteRibbonMultisigRBNTest</strong> checks that the Ribbon multisig wallet always holds at least 1 million $RBN. Failure would indicate a catastrophic scenario with a &gt;99% drop in RBN balance (currently ~140M), which could mean that the multisig had been hacked or the team had rugged.</p><h3>How it works</h3><p>The failure threshold is set in the constructor of the test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wfOTJghjn9YagFrR7ulOiw.png" /><figcaption>AnteRibbonMultisigRBNTest.sol, lines 27–32</figcaption></figure><p>The balance check is super straightforward: as long as the Ribbon multisig address still holds 1M or greater of $RBN, the test passes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_U_NaiWG56SikKmHjW8C4g.png" /><figcaption>AnteRibbonMultisigRBNTest.sol, lines 36–38</figcaption></figure><p>Pretty simple, right? But these are often the kind of fundamental assumptions that we want to make sure hold true for a protocol.</p><h3>Conclusion</h3><p>We all know DeFi can be a dangerous place. Smart contracts can be opaque to your average DeFi user, and bad actors abound. Ante helps make code risk explicit, helping you make informed decisions about which protocols you use. Staking their tests could show a core team’s alignment with the community and their commitment to responsible code security. It’s a hard-to-fake signal of confidence in their code (literally skin in the game).</p><p>If you would like to learn more about how Ante could be useful for your protocol team, please reach out to us at <a href="https://signup.ante.xyz/">signup.ante.xyz</a>, read the docs at <a href="http://docs.ante.finance/">docs.ante.finance</a>, or follow the team on <a href="https://twitter.com/AnteFinance">Twitter</a> and join our <a href="https://discord.gg/ante">Discord</a> for more web3 security discussions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b41bfc597109" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ante-labs/ante-tests-explained-ribbon-finance-b41bfc597109">Ante Tests Explained: Ribbon Finance</a> was originally published in <a href="https://medium.com/ante-labs">Ante Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>