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
答案 0 :(得分:0)
我们希望制定一个简单的ERC-721合同,使令牌的所有者可以(单方面同意)将其交换为任何其他现有令牌。
此实现必须遵循ERC-721标准,并在执行此交换时发出两个Transfer
事件。
让我们从不基于引用实现的基本实现开始,并包括一个mint函数,以便我们可以创建一些令牌来玩:
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);
}
}
现在我们可以添加所需的行为:
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);
}
此实现遵循标准,并会根据需要发出事件。