0

Function to exchange ERC721 Tokens between two addresses. I am implementing this on truffle and openzeppelin 2.10. Two different tokens should be exchanged between two addresses.

Here's my contract function for exchanging ERC721 tokens:

function exchangeStars(uint256 token1, uint256 token2, address starOwner2) public { require(this.ownerOf(token1) == msg.sender);

    transferFrom(msg.sender, starOwner2, token1);
    transferFrom(starOwner2, msg.sender, token2);
}

This is the test I am writing for creating Tokens and exchanging between two addresses.

describe('Exchange Stars', () =>  {
    let token1 = 101;
    let token2 = 202;

    it('User 1 creates Star', async() => {
      await this.contract.createStar(starName, story, ra, dec, mag, token1, {from: account1});
      assert.equal(await this.contract.ownerOf.call(token1), account1);
    });

    it('User 2 creates Star', async() => {
      await this.contract.createStar(starName2, story, ra, dec, mag, token2, {from: account2});
      assert.equal(await this.contract.ownerOf.call(token2), account2);
    });

    it('Users exchange Stars', async() => {
      await this.contract.exchangeStars(token1, token2, account2);
      assert.equal(await this.contract.ownerOf.call(token2), account2);
      console.log(await this.contract.ownerOf.call(token2));
    });

  });

Here's the result for my tests:

Exchange Stars
  √ User 1 creates Star (129ms)
  √ User 2 creates Star (116ms)
  1) Users exchange Stars
> No events were emitted
Sagar Atalatti
  • 486
  • 1
  • 8
  • 21

1 Answers1

0

Problem

We want to make a simple ERC-721 contract where owners of tokens can (with unilateral consent) exchange them for any other existing token.

This implementation must follow ERC-721 standards and emit two Transfer events when this exchange is performed.

Solution

Let's start with a basic implementation based no the reference implementation and including a mint function so that we can create a few tokens to play with:

pragma solidity 0.5.1;

import "https://github.com/0xcert/ethereum-erc721/src/contracts/tokens/nf-token.sol";

contract ExchangeableTokens is ERC721 {

    /**
    * @dev Mints a new NFT.
    * @param _to The address that will own the minted NFT.
    * @param _tokenId of the NFT to be minted by the msg.sender.
    */
    function mint(
        address _to,
        uint256 _tokenId
    )
        external
        onlyOwner
    {
        super._mint(_to, _tokenId);
    }
}

Now we can add the desired behavior:

function exchangeStars(uint256 myToken, uint256 theirToken, address them) 
    public
{
    require (idToOwner[myToken] == msg.sender);
    require (idToOwner[theirToken] == them);
    require (them != address(0));
    _transfer(them, myToken);
    _transfer(msg.sender, theirToken);
}

Discussion

This implementation follows the standard and does emit the events as required.

William Entriken
  • 37,208
  • 23
  • 149
  • 195