How to create a simple smart contract to manage auctions ?

Paulina Lewandowska

07 Dec 2022
How to create a simple smart contract to manage auctions ?

In the previous tutorial you learned how to create a smart contract, which is a wallet. In this tutorial we will try to consolidate the knowledge from the previous tutorial, and expand it with new knowledge. 

So let's get to work. All the things you may not understand will be explained to you later in the text.

Defining variables

Let's start by defining the variables we'll need to make the smart contract work. We certainly need :

  • address of the person to whom the highest bid will be sent,
  • time when the auction in question will end,
  • address of the person who placed the highest bid,
  • why wei is the highest bid,
  • a table of addresses and the amount of money they transferred to the smart contract so that those who did not win the auction can withdraw their money,
  • variable whether the auction is completed or not.
pragma solidity 0.8.11;

contract Auction {

    address payable public beneficiary;

    uint public auctionEndTime;

    address public highestBidder;

    uint public highestBid;

    mapping(address => uint) pendingReturns;

    bool ended;

}

What can you not understand from the above code?

Mapping in solidity is a key-value array, equivalent to dictionary in other languages.

If you don't know why the auctionEndTime variable is given in plain uinta, it's because the time when the auction ends will be given in Unix time.

Let's create a constructor that will take the address to which the highest bid will be sent and how long the auction will last.

constructor(

        uint biddingTime,

        address payable beneficiaryAddress

    ) {

        beneficiary = beneficiaryAddress;

        auctionEndTime = block.timestamp + biddingTime;

    }

What is worth paying attention to ?

  • block.timestamp is a variable that simply means what time it is now given as Unix time of course ;)))

Function for making an offer

Now let's create a function that will be used to submit your bid. The function will return an error if :

  • The auction has ended
  • Our bid will be lower than the highest bid

At the end of the function execution, the function will emit an event that the highest bid has changed. The frontend application can listen to the emitted events on the smartcontest, so that as soon as the highest bid has changed, it can update it in the user interface.

event HighestBidIncreased(address bidder, uint amount);

    event AuctionEnded(address winner, uint amount);

    error AuctionAlreadyEnded();

    error BidNotHighEnough(uint highestBid);

    error AuctionNotYetEnded();

    error AuctionEndAlreadyCalled();

    function bid() external payable {

        if (block.timestamp > auctionEndTime)

            revert AuctionAlreadyEnded();

        if (msg.value <= highestBid)

            revert BidNotHighEnough(highestBid);

        if (highestBid != 0) {

            pendingReturns[highestBidder] += highestBid;

        }

        highestBidder = msg.sender;

        highestBid = msg.value;

        emit HighestBidIncreased(msg.sender, msg.value);

    }

As you can see in the code above, we define ourselves events with parameters that we can emit on the blockchain. To emit an event in solidity we type 

emit + event name and parameters

We have defined our own errors, which if we want to call them we type in revert + the name of our errror and parameters.

You have probably already guessed that instead of ifs and custom errors we could have used requier.

This function checks if the auction has already ended, if msg.value is higher than the highest bid, if so we update the mapping pendingReturns so that the person who placed the highest bid earlier can get his money back. We assign the highest bid to msg.value and the highestBidder to msg.sender, at the end of the function execution we emit an event that informs that the highest bid has been increased.

Function to end the auction, and transfer the highest bid to the benefactor

Now let's create a function so that after the auction ends, the beneficiary's address can send money to his wallet.

This function should:

  • Return an error if the auction has not yet ended,
  • return an error if this function has already been called,
  • change the ended variable to true,
  • emit an event indicating that the auction has ended,
  • transfer an amount of Ethereum equivalent to the highest bid to the benefactor.
function auctionEnd() external {

        if (block.timestamp < auctionEndTime)

            revert AuctionNotYetEnded();

        if (ended)

            revert AuctionEndAlreadyCalled();

        ended = true;

        emit AuctionEnded(highestBidder, highestBid);

        beneficiary.transfer(highestBid);

    }

Function for people who did not win the auction and want their money back

Now, the last function we need to make our contract ready! It will be for addresses that did not win the auction and want to get their money back. Let's consider what such a function should have in it :

  • it should check how much Ethereum you owe in the mapping pendingReturns and assign this value to a variable,
  • it should change how much you owe to 0,
  • it should send as much Ethereum as you have stored in the variable.

Well, let's get to work !

  function withdraw() external{

        uint amount = pendingReturns[msg.sender];

        pendingReturns[msg.sender] = 0;

        payable(msg.sender).transfer(amount);

    }

That's the end of today's tutorial ! Our smart contract is ready. In order to practice and consolidate your knowledge, as a task you can try to replace custom errors with requirs. However, if this is not enough for you, you can also improve this contract so that it can be used to conduct several auctions at once.

Tagi

Most viewed


Never miss a story

Stay updated about Nextrope news as it happens.

You are subscribed

Aethir Tokenomics – Case Study

Kajetan Olas

22 Nov 2024
Aethir Tokenomics – Case Study

Authors of the contents are not affiliated to the reviewed project in any way and none of the information presented should be taken as financial advice.

In this article we analyze tokenomics of Aethir - a project providing on-demand cloud compute resources for the AI, Gaming, and virtualized compute sectors.
Aethir aims to aggregate enterprise-grade GPUs from multiple providers into a DePIN (Decentralized Physical Infrastructure Network). Its competitive edge comes from utlizing the GPUs for very specific use-cases, such as low-latency rendering for online games.
Due to decentralized nature of its infrastructure Aethir can meet the demands of online-gaming in any region. This is especially important for some gamer-abundant regions in Asia with underdeveloped cloud infrastructure that causes high latency ("lags").
We will analyze Aethir's tokenomics, give our opinion on what was done well, and provide specific recommendations on how to improve it.

Evaluation Summary

Aethir Tokenomics Structure

The total supply of ATH tokens is capped at 42 billion ATH. This fixed cap provides a predictable supply environment, and the complete emissions schedule is listed here. As of November 2024 there are approximately 5.2 Billion ATH in circulation. In a year from now (November 2025), the circulating supply will almost triple, and will amount to approximately 15 Billion ATH. By November 2028, today's circulating supply will be diluted by around 86%.

From an investor standpoint the rational decision would be to stake their tokens and hope for rewards that will balance the inflation. Currently the estimated APR for 3-year staking is 195% and for 4-year staking APR is 261%. The rewards are paid out weekly. Furthermore, stakers can expect to get additional rewards from partnered AI projects.

Staking Incentives

Rewards are calculated based on the staking duration and staked amount. These factors are equally important and they linearly influence weekly rewards. This means that someone who stakes 100 ATH for 2 weeks will have the same weekly rewards as someone who stakes 200 ATH for 1 week. This mechanism greatly emphasizes long-term holding. That's because holding a token makes sense only if you go for long-term staking. E.g. a whale staking $200k with 1 week lockup. will have the same weekly rewards as person staking $1k with 4 year lockup. Furthermore the ATH staking rewards are fixed and divided among stakers. Therefore Increase of user base is likely to come with decrease in rewards.
We believe the main weak-point of Aethirs staking is the lack of equivalency between rewards paid out to the users and value generated for the protocol as a result of staking.

Token Distribution

The token distribution of $ATH is well designed and comes with long vesting time-frames. 18-month cliff and 36-moths subsequent linear vesting is applied to team's allocation. This is higher than industry standard and is a sign of long-term commitment.

  • Checkers and Compute Providers: 50%
  • Ecosystem: 15%
  • Team: 12.5%
  • Investors: 11.5%
  • Airdrop: 6%
  • Advisors: 5%

Aethir's airdrop is divided into 3 phases to ensure that only loyal users get rewarded. This mechanism is very-well thought and we rate it highly. It fosters high community engagement within the first months of the project and sets the ground for potentially giving more-control to the DAO.

Governance and Community-Led Development

Aethir’s governance model promotes community-led decision-making in a very practical way. Instead of rushing with creation of a DAO for PR and marketing purposes Aethir is trying to make it the right way. They support projects building on their infrastructure and regularly share updates with their community in the most professional manner.

We believe Aethir would benefit from implementing reputation boosted voting. An example of such system is described here. The core assumption is to abandon the simplistic: 1 token = 1 vote and go towards: Votes = tokens * reputation_based_multiplication_factor.

In the attached example, reputation_based_multiplication_factor rises exponentially with the number of standard deviations above norm, with regard to user's rating. For compute compute providers at Aethir, user's rating could be replaced by provider's uptime.

Perspectives for the future

While it's important to analyze aspects such as supply-side tokenomics, or governance, we must keep in mind that 95% of project's success depends on demand-side. In this regard the outlook for Aethir may be very bright. The project declares $36M annual reccuring revenue. Revenue like this is very rare in the web3 space. Many projects are not able to generate any revenue after succesfull ICO event, due to lack fo product-market-fit.

If you're looking to create a robust tokenomics model and go through institutional-grade testing please reach out to contact@nextrope.com. Our team is ready to help you with the token engineering process and ensure your project’s resilience in the long term.

Nextrope Partners with Hacken to Enhance Blockchain Security

Miłosz

21 Nov 2024
Nextrope Partners with Hacken to Enhance Blockchain Security

Nextrope announces a strategic partnership with Hacken, a renowned blockchain security auditor. It marks a significant step in delivering reliable decentralized solutions. After several successful collaborations resulting in flawless smart contract audits, the alliance solidifies the synergy between Nextrope's innovative blockchain development and Hacken's top-tier security auditing services. Together, we aim to set new benchmarks, ensuring that security is an integral part of blockchain technology.

Strengthening Blockchain Security

The partnership aims to fortify the security protocols within blockchain ecosystems. By integrating Hacken's comprehensive security audits with Nextrope's cutting-edge blockchain solutions, we are poised to offer unparalleled security features in our projects.

"Blockchain security should never be an afterthought"

"Our partnership with Hacken underscores our dedication to embedding security at the core of our blockchain solutions. Together, we're building a safer future for the industry."

said Mateusz Mach, CEO of Nextrope

About Nextrope

Nextrope is a forward-thinking blockchain development house specializing in creating innovative solutions for businesses worldwide. With a team of experienced developers and blockchain experts, Nextrope delivers high-quality, scalable, and secure blockchain applications tailored to meet the unique needs of each client.

About Hacken

Hacken is a leading blockchain security auditor known for its rigorous smart contract audits and security assessments. With a mission to make the industry safer, Hacken provides complex security services that help companies identify and mitigate vulnerabilities in their applications.

Looking Ahead

As a joint mission, both Nextrope and Hacken are committed to continuous innovation. We look forward to the exciting opportunities this partnership will bring and are eager to implement a more secure blockchain environment for all.

For more information, please contact:

Nextrope

Hacken

Join us on our journey to deliver top-notch blockchain tech and a safer future for the industry!