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

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!

Nextrope as Sponsor at ETH Warsaw 2024: Highlights

Miłosz

04 Oct 2024
Nextrope as Sponsor at ETH Warsaw 2024: Highlights

ETH Warsaw has established itself as a significant event in the Web3 space, gathering developers, entrepreneurs, and investors in the heart of Poland’s capital each year. The 2024 edition was filled with builders and leaders united in advancing decentralized technologies.

Leading Event of Warsaw Blockchain Week

As a blend of conference and hackathon, ETH Warsaw aims to push the boundaries of innovation. For companies and individuals eager to shape the future of tech, the premier summit during Warsaw Blockchain Week offers a unique platform to connect and collaborate.

Major Milestones in Previous Editions

  • Over 1,000 participants attended the forum
  • 222 hackers competed, showcasing groundbreaking technical skills
  • $119,920 in bounties was awarded to boost promising solution development

Key Themes at ETH Warsaw 2024

This year’s discussions were centered around shaping the adoption of blockchain. To emphasize that future implementation requires a wide range of voices, perspectives, and understanding, ETH Warsaw 2024 encouraged participation from individuals of all backgrounds. As the industry stands on the cusp of a potential bull market, building resilient products brings substantial impact. Participants mutually raised an inhibitor posed by poor architecture or suspicious practices.

Infrastructure and Scalability

  • Layer 2 (L2) solutions
  • Zero-Knowledge Proofs (ZKPs)
  • Future of Account Abstraction in Decentralized Applications (DApps)
  • Advancements in Blockchain Interoperability
  • Integration of Artificial Intelligence (AI) and Machine Learning Models (MLMs) with on-chain data

Responsibility

With the premise of robust blockchain systems, we delved into topics such as privacy, advanced security protocols, and white-hacking as essential tools for maintaining trust. Discussions also included consensus mechanisms and their role in the entire infrastructure, beginning with transparent Decentralized Autonomous Organizations (DAOs).

Legal Policies

The track on financial freedom led to the transformative potential of decentralized finance (DeFi). We tackled the challenges and opportunities of blockchain products within a rapidly evolving regulatory landscape.

Mass Adoption

Conversations surrounding accessible platforms underscored the need to simplify onboarding for new users, ultimately crafting solutions that appeal to mainstream audiences. Contributors explored ways to improve user experience (UX), enhance community management, and support Web3 startups.

ETH Legal, co-organized with PKO BP and several leading law firms, studied the implementation of the MiCA guidelines starting next year and affecting the market. It aimed to dissect the complex policies that govern digital assets.

Currently, founders navigate a patchwork of regulations that vary by jurisdiction. There is a clear need for structured protocols that ensure consumer protection and market integrity while attracting more users. Legal experts broke down the implications of existing and anticipated changes on decentralized finance (DeFi), non-fungible tokens (NFTs), business logic, and other emerging technologies.

The importance of ETH Legal extended beyond theoretical discussions. It served as a vital forum for stakeholders to connect and share insights. Thanks to input from renowned experts in the field, attendees left with a deeper understanding of the challenges ahead.

Warsaw Blockchain Week: Nextrope’s Engagement

The Warsaw Blockchain Week 2024 ensured a wide range of activities, with a packed schedule of conferences, hackathons, and networking opportunities. Nextrope actively engaged in several side events throughout the week and recognized the immense potential to foster connections.

Side Events Attended by Nextrope

  • Elympics on TON
  • Aleph Zero Opening Party
  • Cookie3 x NOKS x TON Syndicate
  • Solana House

Nextrope’s Contribution to ETH Warsaw 2024

At ETH Warsaw 2024, Nextrope proudly positioned itself as a Pond Sponsor of the conference and hackathon, reflecting the event's mission. Following a strong track record of partnerships with large financial institutions and startups, we seized the opportunity to share our reflections with the community.

Together, we continue to innovate toward a more decentralized and inclusive future. By actively participating in open conversations about regulatory and technological advancements, Nextrope solidifies its role as an exemplar of dedication, forward-thinking, and technological resources.