Develop Functions For Use Case

Published by Marianne Poser on

We define our first function, where the user can swap the collected coins to a key. So, the first call is a transfer from the user to the owner of twenty coins and secondly, there is a transfer from the owner to the user of one key.

As a second function, we define the function to open the treasure box with five keys. So, the owner gets five keys from the user and then the smart contract mints a new NFT, which is directly transferred to the user. To make the ID of the new NFT unique, the treasureCount variable is first incremented and is then used as the ID of the NFT. This step is crucial to ensure that each NFT has a unique ID.

Complete Code

//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";

contract TreasureBox is ERC1155 {

    uint256 public constant COINS = 0;
    uint256 public constant KEYS = 1;

    address public owner;
    uint256 public treasureCount;

    constructor() ERC1155("https://treasureboxprojekt/treasure/{id}.json") {
        //Minting fungible Token
        _mint(msg.sender, COINS, 10**9, "");
        _mint(msg.sender, KEYS, 10**4, "");

        owner = msg.sender;
        treasureCount = 2;
    function swapCoinsForKey() public {
        _safeTransferFrom(msg.sender, owner, COINS, 20, "");
        _safeTransferFrom(owner, msg.sender, KEYS, 1 , "");

    function openTreasureBox() public{
        _safeTransferFrom(msg.sender, owner, KEYS, 5, "");
        _mint(msg.sender, treasureCount, 1, "");