├── ERCTokenImplementation.sol ├── LICENSE ├── README.md ├── TradeImplementationExample.java └── experiments └── auction └── ERC875Auction.sol /ERCTokenImplementation.sol: -------------------------------------------------------------------------------- 1 | contract ERC165 2 | { 3 | /// @notice Query if a contract implements an interface 4 | /// @param interfaceID The interface identifier, as specified in ERC-165 5 | /// @dev Interface identification is specified in ERC-165. This function 6 | /// uses less than 30,000 gas. 7 | /// @return `true` if the contract implements `interfaceID` and 8 | /// `interfaceID` is not 0xffffffff, `false` otherwise 9 | function supportsInterface(bytes4 interfaceID) external view returns (bool); 10 | } 11 | 12 | contract ERC875 /* is ERC165 */ 13 | { 14 | event Transfer(address indexed _from, address indexed _to, uint256[] tokenIndices); 15 | 16 | function name() constant public returns (string name); 17 | function symbol() constant public returns (string symbol); 18 | function balanceOf(address _owner) public view returns (uint256[] _balances); 19 | function transfer(address _to, uint256[] _tokens) public; 20 | function transferFrom(address _from, address _to, uint256[] _tokens) public; 21 | 22 | //optional 23 | //function totalSupply() public constant returns (uint256 totalSupply); 24 | function trade(uint256 expiryTimeStamp, uint256[] tokenIndices, uint8 v, bytes32 r, bytes32 s) public payable; 25 | //function ownerOf(uint256 _tokenId) public view returns (address _owner); 26 | } 27 | 28 | pragma solidity ^0.4.17; 29 | contract Token is ERC875 30 | { 31 | uint totalTickets; 32 | mapping(address => uint256[]) inventory; 33 | uint16 ticketIndex = 0; //to track mapping in tickets 34 | uint expiryTimeStamp; 35 | address owner; // the address that calls selfdestruct() and takes fees 36 | address admin; 37 | uint transferFee; 38 | uint numOfTransfers = 0; 39 | string public name; 40 | string public symbol; 41 | uint8 public constant decimals = 0; //no decimals as tickets cannot be split 42 | 43 | event Transfer(address indexed _from, address indexed _to, uint256[] tokenIndices); 44 | event TransferFrom(address indexed _from, address indexed _to, uint _value); 45 | 46 | modifier adminOnly() 47 | { 48 | if(msg.sender != admin) revert(); 49 | else _; 50 | } 51 | 52 | function() public { revert(); } //should not send any ether directly 53 | 54 | // example: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], "MJ comeback", 1603152000, "MJC", "0x007bEe82BDd9e866b2bd114780a47f2261C684E3" 55 | function Token( 56 | uint256[] numberOfTokens, 57 | string evName, 58 | uint expiry, 59 | string eventSymbol, 60 | address adminAddr) public 61 | { 62 | totalTickets = numberOfTokens.length; 63 | //assign some tickets to event admin 64 | expiryTimeStamp = expiry; 65 | owner = msg.sender; 66 | admin = adminAddr; 67 | inventory[admin] = numberOfTokens; 68 | symbol = eventSymbol; 69 | name = evName; 70 | } 71 | 72 | function getDecimals() public pure returns(uint) 73 | { 74 | return decimals; 75 | } 76 | 77 | // price is 1 in the example and the contract address is 0xfFAB5Ce7C012bc942F5CA0cd42c3C2e1AE5F0005 78 | // example: 0, [3, 4], 27, "0x2C011885E2D8FF02F813A4CB83EC51E1BFD5A7848B3B3400AE746FB08ADCFBFB", "0x21E80BAD65535DA1D692B4CEE3E740CD3282CCDC0174D4CF1E2F70483A6F4EB2" 79 | // price is encoded in the server and the msg.value is added to the message digest, 80 | // if the message digest is thus invalid then either the price or something else in the message is invalid 81 | function trade(uint256 expiry, 82 | uint256[] tokenIndices, 83 | uint8 v, 84 | bytes32 r, 85 | bytes32 s) public payable 86 | { 87 | //checks expiry timestamp, 88 | //if fake timestamp is added then message verification will fail 89 | require(expiry > block.timestamp || expiry == 0); 90 | //id 1 for mainnet 91 | bytes12 prefix = "ERC800-CNID1"; 92 | bytes32 message = encodeMessage(prefix, msg.value, expiry, tokenIndices); 93 | address seller = ecrecover(message, v, r, s); 94 | 95 | for(uint i = 0; i < tokenIndices.length; i++) 96 | { // transfer each individual tickets in the ask order 97 | uint index = uint(tokenIndices[i]); 98 | require((inventory[seller][index] > 0)); // 0 means ticket sold. 99 | inventory[msg.sender].push(inventory[seller][index]); 100 | inventory[seller][index] = 0; // 0 means ticket sold. 101 | } 102 | seller.transfer(msg.value); 103 | } 104 | 105 | 106 | //must also sign in the contractAddress 107 | //prefix must contain ERC and chain id 108 | function encodeMessage(bytes12 prefix, uint value, 109 | uint expiry, uint256[] tokenIndices) 110 | internal view returns (bytes32) 111 | { 112 | bytes memory message = new bytes(96 + tokenIndices.length * 2); 113 | address contractAddress = getContractAddress(); 114 | for (uint i = 0; i < 32; i++) 115 | { // convert bytes32 to bytes[32] 116 | // this adds the price to the message 117 | message[i] = byte(bytes32(value << (8 * i))); 118 | } 119 | 120 | for (i = 0; i < 32; i++) 121 | { 122 | message[i + 32] = byte(bytes32(expiry << (8 * i))); 123 | } 124 | 125 | for(i = 0; i < 12; i++) 126 | { 127 | message[i + 64] = byte(prefix << (8 * i)); 128 | } 129 | 130 | for(i = 0; i < 20; i++) 131 | { 132 | message[76 + i] = byte(bytes20(bytes20(contractAddress) << (8 * i))); 133 | } 134 | 135 | for (i = 0; i < tokenIndices.length; i++) 136 | { 137 | // convert int[] to bytes 138 | message[96 + i * 2 ] = byte(tokenIndices[i] >> 8); 139 | message[96 + i * 2 + 1] = byte(tokenIndices[i]); 140 | } 141 | 142 | return keccak256(message); 143 | } 144 | 145 | function name() public view returns(string) 146 | { 147 | return name; 148 | } 149 | 150 | function symbol() public view returns(string) 151 | { 152 | return symbol; 153 | } 154 | 155 | function getAmountTransferred() public view returns (uint) 156 | { 157 | return numOfTransfers; 158 | } 159 | 160 | function isContractExpired() public view returns (bool) 161 | { 162 | if(block.timestamp > expiryTimeStamp) 163 | { 164 | return true; 165 | } 166 | else return false; 167 | } 168 | 169 | function balanceOf(address _owner) public view returns (uint256[]) 170 | { 171 | return inventory[_owner]; 172 | } 173 | 174 | function myBalance() public view returns(uint256[]) 175 | { 176 | return inventory[msg.sender]; 177 | } 178 | 179 | function transfer(address _to, uint256[] tokenIndices) public 180 | { 181 | for(uint i = 0; i < tokenIndices.length; i++) 182 | { 183 | require(inventory[msg.sender][i] != 0); 184 | //pushes each element with ordering 185 | uint index = uint(tokenIndices[i]); 186 | inventory[_to].push(inventory[msg.sender][index]); 187 | inventory[msg.sender][index] = 0; 188 | } 189 | } 190 | 191 | function transferFrom(address _from, address _to, uint256[] tokenIndices) 192 | adminOnly public 193 | { 194 | bool isadmin = msg.sender == admin; 195 | for(uint i = 0; i < tokenIndices.length; i++) 196 | { 197 | require(inventory[_from][i] != 0 || isadmin); 198 | //pushes each element with ordering 199 | uint index = uint(tokenIndices[i]); 200 | inventory[_to].push(inventory[_from][index]); 201 | inventory[_from][index] = 0; 202 | } 203 | } 204 | 205 | function endContract() public 206 | { 207 | if(msg.sender == owner) 208 | { 209 | selfdestruct(owner); 210 | } 211 | else revert(); 212 | } 213 | 214 | function getContractAddress() public view returns(address) 215 | { 216 | return this; 217 | } 218 | } 219 | 220 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 AlphaWallet 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ERC875-Example 2 | An example implementation of our new ERC spec draft. 3 | 4 | Create your own here: https://alphawallet.github.io/ERC875-token-factory/index 5 | 6 | Test it out here: https://rinkeby.etherscan.io/address/0xffab5ce7c012bc942f5ca0cd42c3c2e1ae5f0005 7 | 8 | Referenced here: https://github.com/ethereum/EIPs/issues/875 9 | 10 | contract ERC 11 | { 12 | event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); 13 | event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); 14 | 15 | function name() constant returns (string name); 16 | function symbol() constant returns (string symbol); 17 | function balanceOf(address _owner) public view returns (uint256[] _balances); 18 | function transfer(address _to, uint256[] _tokens) public; 19 | function transferFrom(address _from, address _to, uint256[] _tokens) public; 20 | 21 | //optional 22 | function totalSupply() constant returns (uint256 totalSupply); 23 | function trade(uint256 expiryTimeStamp, uint256[] tokenIndices, uint8 v, bytes32 r, bytes32 s) public payable 24 | function ownerOf(uint256 _tokenId) public view returns (address _owner); 25 | } 26 | 27 | ## Summary 28 | A simple non fungible token standard that allows batching tokens into lots and settling p2p atomic transfers in one transaction. 29 | 30 | ## Purpose 31 | While other standards allow the user to transfer a non-fungible token, they require one transaction per token, this is heavy on gas and partially responsible for clogging the ethereum network. There are also few definitions for how to do a simple atomic swap. 32 | 33 | ## Rinkeby example 34 | This standard has been implemented in an example contract on rinkeby: https://rinkeby.etherscan.io/address/0xffab5ce7c012bc942f5ca0cd42c3c2e1ae5f0005 35 | 36 | ## Specification 37 | 38 | ### function name() constant returns (string name) 39 | 40 | returns the name of the contract e.g. CarLotContract 41 | 42 | ### function symbol() constant returns (string symbol) 43 | 44 | Returns a short string of the symbol of the in-fungible token, this should be short and generic as each token is non-fungible. 45 | 46 | ### function balanceOf(address _owner) public view returns (uint256[] balance) 47 | 48 | Returns an array of the users balance. 49 | 50 | ### function transfer(address _to, uint256[] _tokens) public; 51 | 52 | Transfer your unique tokens to an address by adding an array of the token indices. This compares favourable to ERC721 as you can transfer a bulk of tokens in one go rather than one at a time. This has a big gas saving as well as being more convenient. 53 | 54 | ### function transferFrom(address _from, address _to, uint256[] _tokens) public; 55 | 56 | Transfer a variable amount of tokens from one user to another. This can be done from an authorised party with a specified key e.g. contract owner. 57 | 58 | ## Optional functions 59 | 60 | ### function totalSupply() constant returns (uint256 totalSupply); 61 | 62 | Returns the total amount of tokens in the given contract, this should be optional as assets might be allocated and issued on the fly. This means that supply is not always fixed. 63 | 64 | ### function ownerOf(uint256 _tokenId) public view returns (address _owner); 65 | 66 | Returns the owner of a particular token, I think this should be optional as not every token contract will need to track the owner of a unique token and it costs gas to loop and map the token id owners each time the balances change. 67 | 68 | ### function trade(uint256 expiryTimeStamp, uint256[] tokenIndices, uint8 v, bytes32 r, bytes32 s) public payable 69 | 70 | A function which allows a user to sell a batch of non-fungible tokens without paying for the gas fee (only the buyer has to). This is achieved by signing an attestation containing the amount of tokens to sell, the contract address, an expiry timestamp, the price and a prefix containing the ERC spec name and chain id. A buyer can then pay for the deal in one transaction by attaching the appropriate ether to satisfy the deal. 71 | 72 | This design is also more efficient as it allows orders to be done offline until settlement as opposed to creating orders in a smart contract and updating them. The expiry timestamp protects the seller against people using old orders. 73 | 74 | This opens up the gates for a p2p atomic swap but should be optional to this standard as some may not have use for it. 75 | 76 | Some protections need to be added to the message such as encoding the chain id, contract address and the ERC spec name to prevent replays and spoofing people into signing message that allow a trade. 77 | 78 | 79 | 80 | 81 | # Donations 82 | If you support the cause, we could certainly use donations to help fund development: 83 | 84 | 0xbc8dAfeacA658Ae0857C80D8Aa6dE4D487577c63 85 | 86 | -------------------------------------------------------------------------------- /TradeImplementationExample.java: -------------------------------------------------------------------------------- 1 | package tapi.utils; 2 | 3 | import org.web3j.crypto.ECKeyPair; 4 | import org.web3j.crypto.Sign; 5 | import java.math.BigInteger; 6 | import java.nio.ByteBuffer; 7 | import java.nio.ShortBuffer; 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | /** 12 | * Created by sangalli on 12/2/18. 13 | */ 14 | 15 | class TransactionDetails 16 | { 17 | BigInteger value; 18 | List ticketIndices; 19 | Sign.SignatureData signatureData; 20 | } 21 | 22 | public class TradeImplementationExample 23 | { 24 | 25 | private static final String contractAddress = "fFAB5Ce7C012bc942F5CA0cd42c3C2e1AE5F0005"; 26 | 27 | public static void main(String[] args) 28 | { 29 | short[] ticketPlaces = new short[]{3, 4}; 30 | //zero timestamp means unlimited 31 | byte[] msg = encodeMessageForTrade(BigInteger.ONE, BigInteger.ZERO, ticketPlaces); 32 | List indices = new ArrayList<>(); 33 | for(int i = 0; i < ticketPlaces.length; i++) 34 | { 35 | indices.add(BigInteger.valueOf(ticketPlaces[i])); 36 | } 37 | TransactionDetails td = createTrade(msg, indices, BigInteger.ONE); 38 | 39 | System.out.println("Price: 1 "); 40 | System.out.println("expiry: 0 (does not expiry)"); 41 | System.out.println("Signature v value: " + td.signatureData.getV()); 42 | System.out.println("Signature r value: 0x" + bytesToHex(td.signatureData.getR())); 43 | System.out.println("Signature s value: 0x" + bytesToHex(td.signatureData.getS())); 44 | System.out.println("Ticket indices: 3, 4"); 45 | } 46 | 47 | public static byte[] encodeMessageForTrade(BigInteger price, BigInteger expiryTimestamp, short[] tickets) 48 | { 49 | byte[] priceInWei = price.toByteArray(); 50 | byte[] expiry = expiryTimestamp.toByteArray(); 51 | ByteBuffer message = ByteBuffer.allocate(96 + tickets.length * 2); 52 | byte[] leadingZeros = new byte[32 - priceInWei.length]; 53 | message.put(leadingZeros); 54 | message.put(priceInWei); 55 | byte[] leadingZerosExpiry = new byte[32 - expiry.length]; 56 | message.put(leadingZerosExpiry); 57 | message.put(expiry); 58 | byte[] prefix = "ERC800-CNID1".getBytes(); 59 | byte[] contract = hexStringToBytes(contractAddress); 60 | message.put(prefix); 61 | message.put(contract); 62 | ShortBuffer shortBuffer = message.slice().asShortBuffer(); 63 | shortBuffer.put(tickets); 64 | 65 | return message.array(); 66 | } 67 | 68 | private static String bytesToHex(byte[] bytes) 69 | { 70 | final char[] hexArray = "0123456789ABCDEF".toCharArray(); 71 | char[] hexChars = new char[bytes.length * 2]; 72 | for ( int j = 0; j < bytes.length; j++ ) 73 | { 74 | int v = bytes[j] & 0xFF; 75 | hexChars[j * 2] = hexArray[v >>> 4]; 76 | hexChars[j * 2 + 1] = hexArray[v & 0x0F]; 77 | } 78 | String finalHex = new String(hexChars); 79 | return finalHex; 80 | } 81 | 82 | private static byte[] hexStringToBytes(String s) 83 | { 84 | int len = s.length(); 85 | byte[] data = new byte[len / 2]; 86 | for (int i = 0; i < len; i += 2) 87 | { 88 | data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) 89 | + Character.digit(s.charAt(i + 1), 16)); 90 | } 91 | return data; 92 | } 93 | 94 | public static TransactionDetails createTrade(byte[] message, List indices, BigInteger price) 95 | { 96 | try 97 | { 98 | //Note: you can replace with your own key instead of using same key generated from BigInteger.ONE 99 | Sign.SignatureData sigData = Sign.signMessage(message, 100 | ECKeyPair.create(BigInteger.ONE)); 101 | TransactionDetails TransactionDetails = new TransactionDetails(); 102 | TransactionDetails.ticketIndices = indices; 103 | TransactionDetails.value = price; 104 | 105 | byte v = sigData.getV(); 106 | 107 | String hexR = bytesToHex(sigData.getR()); 108 | String hexS = bytesToHex(sigData.getS()); 109 | 110 | byte[] rBytes = hexStringToBytes(hexR); 111 | byte[] sBytes = hexStringToBytes(hexS); 112 | 113 | BigInteger r = new BigInteger(rBytes); 114 | BigInteger s = new BigInteger(sBytes); 115 | 116 | TransactionDetails.signatureData = new Sign.SignatureData(v, r.toByteArray(), s.toByteArray()); 117 | 118 | return TransactionDetails; 119 | } 120 | catch(Exception e) 121 | { 122 | e.printStackTrace(); 123 | return null; 124 | } 125 | } 126 | 127 | } 128 | -------------------------------------------------------------------------------- /experiments/auction/ERC875Auction.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.21; 2 | 3 | contract ERC875Interface { 4 | function trade(uint256 expiry, uint256[] tokenIndices, uint8 v, bytes32 r, bytes32 s) public payable; 5 | function passTo(uint256 expiry, uint256[] tokenIndices, uint8 v, bytes32 r, bytes32 s, address recipient) public; 6 | function name() public view returns(string); 7 | function symbol() public view returns(string); 8 | function getAmountTransferred() public view returns (uint); 9 | function balanceOf(address _owner) public view returns (uint256[]); 10 | function myBalance() public view returns(uint256[]); 11 | function transfer(address _to, uint256[] tokenIndices) public; 12 | function transferFrom(address _from, address _to, uint256[] tokenIndices) public; 13 | function approve(address _approved, uint256[] tokenIndices) public; 14 | function endContract() public; 15 | function contractType() public pure returns (string); 16 | function getContractAddress() public view returns(address); 17 | } 18 | 19 | contract ERC875Auction 20 | { 21 | address public beneficiary; 22 | uint public biddingEnd; 23 | bool public ended; 24 | uint public minimumBidIncrement; 25 | address public holdingContract; 26 | uint256[] public contractIndices; 27 | 28 | mapping(address => uint) public bids; 29 | 30 | // Events that will be fired on changes. 31 | event HighestBidIncreased(address bidder, uint amount); 32 | event AuctionEnded(address winner, uint highestBid); 33 | 34 | address public highestBidder; 35 | uint public highestBid; 36 | 37 | modifier onlyBefore(uint _time) {require(now < _time); _;} 38 | modifier onlyAfter(uint _time) {require(now > _time); _;} 39 | modifier notBeneficiary(address addr) {require(addr != beneficiary); _;} 40 | modifier bidIsSufficientlyHiger(uint value) {require(value > (highestBid + minimumBidIncrement)); _;} 41 | modifier notAlreadyEnded() {require(ended == false); _;} 42 | modifier addressHasSufficientBalance(address bidder, uint value) {require(bidder.balance >= value); _;} 43 | modifier auctionHasEnded() {require(ended == true); _;} 44 | modifier organiserOrBeneficiaryOnly() 45 | { 46 | if(!(msg.sender == beneficiary || msg.sender == holdingContract)) revert(); 47 | else _; 48 | } 49 | 50 | constructor( 51 | uint _biddingTime, 52 | address _beneficiary, 53 | uint _minBidIncrement, 54 | address _ERC875ContractAddr, 55 | uint256[] _tokenIndices 56 | ) public 57 | { 58 | beneficiary = _beneficiary; 59 | biddingEnd = block.timestamp + _biddingTime; 60 | minimumBidIncrement = _minBidIncrement; 61 | ended = false; 62 | holdingContract = _ERC875ContractAddr; 63 | contractIndices = _tokenIndices; 64 | } 65 | 66 | // Auction participant submits their bid. 67 | // This only needs to be the value for this single use auction contract 68 | function bid(uint value) 69 | public 70 | onlyBefore(biddingEnd) 71 | notBeneficiary(msg.sender) // beneficiary can't participate in auction 72 | bidIsSufficientlyHiger(value) // bid must be greater than the last one 73 | addressHasSufficientBalance(msg.sender, value) // check that bidder has the required balance 74 | { 75 | bids[msg.sender] = value; 76 | highestBid = value; 77 | highestBidder = msg.sender; 78 | emit HighestBidIncreased(highestBidder, highestBid); 79 | } 80 | 81 | // Contract can be killed at any time - note that no assets are held by the contract 82 | function endContract() public organiserOrBeneficiaryOnly 83 | { 84 | selfdestruct(beneficiary); 85 | } 86 | 87 | /// End the auction - called by the winner, send eth to the beneficiatiary and send ERC875 tokens to the highest bidder 88 | /// Can only be called by the winner, who must attach the ETH amount to the transaction 89 | function auctionEnd() 90 | public 91 | onlyAfter(biddingEnd) 92 | notAlreadyEnded() payable 93 | { 94 | require(!ended); 95 | require(msg.value >= highestBid); 96 | require(msg.sender == highestBidder); 97 | 98 | ERC875Interface tokenContract = ERC875Interface(holdingContract); 99 | 100 | //Atomic swap the ERC875 token(s) and the highestBidder's ETH 101 | bool completed = tokenContract.transferFrom(beneficiary, highestBidder, contractIndices); 102 | //only have two outcomes from transferFromContract() - all tokenss are transferred or none (uses revert) 103 | if (completed) beneficiary.transfer(msg.value); 104 | 105 | ended = true; 106 | emit AuctionEnded(highestBidder, highestBid); 107 | } 108 | 109 | // Start new auction 110 | function startNewAuction( 111 | uint _biddingTime, 112 | address _beneficiary, 113 | uint _minBidIncrement, 114 | address _ERC875ContractAddr, 115 | uint256[] _tokenIndices) public 116 | auctionHasEnded() 117 | { 118 | beneficiary = _beneficiary; 119 | biddingEnd = block.timestamp + _biddingTime; 120 | minimumBidIncrement = _minBidIncrement; 121 | ended = false; 122 | holdingContract = _ERC875ContractAddr; 123 | contractIndices = _tokenIndices; 124 | bids.delete(); 125 | highestBid = 0; 126 | highestBidder = 0; 127 | } 128 | } 129 | --------------------------------------------------------------------------------