ethereum / EIPs

The Ethereum Improvement Proposal repository

Home Page:https://eips.ethereum.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ERC827 Token Standard (ERC20 Extension)

AugustoL opened this issue · comments

EIP: 827
Title: ERC827 Token Standard (ERC20 Extension)
Author: Augusto Lemble <me@augustol.com>
Type: Token Standard
Status: Draft
Category: ERC
Created: 2018-01-11
Updated: 2019-05-21

This standard is still a draft and is proven to be unsafe to be used

Simple Summary

A extension of the standard interface ERC20 for tokens with methods that allows the execution of calls inside transfer and approvals.

Abstract

This standard provides basic functionality to transfer tokens, as well as allow tokens to be approved so they can be spent by another on-chain third party. Also it allows to execute calls on transfers and approvals.

Motivation

This extension of the ERC20 interface allows the token to execute a function in the receiver contract contract after the approval or transfer happens. The function is executed by the token proxy, a simple proxy which goal is to mask the msg.sender to prevent the token contract to execute the function calls itself.
The ERC20 token standard is widely accepted but it only allows the transfer of value, ethereum users are available to transfer value and data on transactions, with these extension of the ERC20 token standard they will be able to do the same with ERC20 tokens.

I saw a lot of new standards being proposed in the community and I think the way to improve the current ERC20 standard is with an extension that is fully compatible with the original standard and also add new methods, but keeping it simple at the same time, the code to be added to the ERC20 standard is near 150 lines of code.

When to use each function

  • approveAndCall: Probably the one that you will need, maybe the only one since it only allows the receiver contract to use approved balance. The best practice is to check the allowance of the sender and then do your stuff using the transferFromAndCall method.

  • transferAndCall: There is no way to check that the balance that will be transferred is the correct one, this function is useful when a function dont need to check any transfer of value.

  • transferFromAndCall: Same as transferAndCall, only useful when there is no need to check the transfered amount of tokens and want to spend approved balance.

Specification

Token

Methods

NOTE: Callers MUST handle false from returns (bool success). Callers MUST NOT assume that false is never returned!

name - ERC20

Returns the name of the token - e.g. "MyToken".

OPTIONAL - This method can be used to improve usability,
but interfaces and other contracts MUST NOT expect these values to be present.

function name() constant returns (string name)

symbol - ERC20

Returns the symbol of the token. E.g. "HIX".

OPTIONAL - This method can be used to improve usability,
but interfaces and other contracts MUST NOT expect these values to be present.

function symbol() constant returns (string symbol)

decimals - ERC20

Returns the number of decimals the token uses - e.g. 8, means to divide the token amount by 100000000 to get its user representation.

OPTIONAL - This method can be used to improve usability,
but interfaces and other contracts MUST NOT expect these values to be present.

function decimals() constant returns (uint8 decimals)

totalSupply - ERC20

Returns the total token supply.

function totalSupply() constant returns (uint256 totalSupply)

balanceOf - ERC20

Returns the account balance of another account with address _owner.

function balanceOf(address _owner) constant returns (uint256 balance)

transfer - ERC20

Transfers _value amount of tokens to address _to, and MUST fire the Transfer event.
The function SHOULD revert if the _from account balance does not have enough tokens to spend.

A token contract which creates new tokens SHOULD trigger a Transfer event with the _from address set to 0x0 when tokens are created.

Note Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event.

function transfer(address _to, uint256 _value) returns (bool success)

transferFrom - ERC20

Transfers _value amount of tokens from address _from to address _to, and MUST fire the Transfer event.

The transferFrom method is used for a withdraw workflow, allowing contracts to transfer tokens on your behalf.
This can be used for example to allow a contract to transfer tokens on your behalf and/or to charge fees in sub-currencies.
The function SHOULD revert unless the _from account has deliberately authorized the sender of the message via some mechanism.

Note Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event.

function transferFrom(address _from, address _to, uint256 _value) returns (bool success)

approve - ERC20

Allows _spender to withdraw from your account multiple times, up to the _value amount. If this function is called again it overwrites the current allowance with _value.

Users SHOULD make sure to create user interfaces in such a way that they set the allowance first to 0 before setting it to another value for the same spender.
THOUGH The contract itself shouldn't enforce it, to allow backwards compatibility with contracts deployed before

function approve(address _spender, uint256 _value) returns (bool success)

allowance - ERC20

Returns the amount which _spender is still allowed to withdraw from _owner.

function allowance(address _owner, address _spender) constant returns (uint256 remaining)

ERC827 Proxy

A very simple proxy contract used to forward the calls form the token contract.

  • The proxy is deployed and assigned on the ERC827 token on the ERC827 constructor.
  • The proxy can only execute calls coming form the token contract.

There is a public variable called proxy in the ERC827 token, this can be used to check if the call is coming from the ERC827 token since the proxy can only forward calls from the token contract.

contract ERC827Proxy {

  address public token;
  bytes4 public callContractFunctionSignature = bytes4(
    keccak256("callContract(address,bytes)")
  );

  constructor() public {
    token = address(msg.sender);
  }

  function callContract(
    address _target, bytes memory _data
  ) public payable returns (bool) {
    require(
      msg.sender == address(token),
      "Proxy cant execute calls to the token contract"
    );
    (bool success, bytes memory data) = _target.call.value(msg.value)(_data);
    require(success, "Proxy call failed");
    return true;
  }

}

ERC827 methods

transferAndCall - ERC827

Execute a function on _to with the _data parameter, if the function ends successfully execute the transfer of _value amount of tokens to address _to, and MUST fire the Transfer event.

This method is payable, which means that ethers can be sent when calling it, but the transfer of ether needs to be handled in the call is executed after transfer since the one who receives the ether is the token contract and not the token receiver.

The function SHOULD revert if the call to _to address fails or if _from account balance does not have enough tokens to spend.
The ERC20 transfer method is called before the _call(_to, _data).

Note Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event.

Important Note Do not use this method with fallback functions that receive the value transferred as parameter, there is not way to verify how much value was transferred on the fallback function.

  function transferAndCall(
    address _to, uint256 _value, bytes memory _data
  ) public payable returns (bool) {
    super.transfer(_to, _value);
    _call(_to, _data);
    return true;
  }

transferFromAndCall - ERC827

Execute a function on _to with the _data parameter, if the function ends successfully execute the transfer of _value amount of tokens from address _from to address _to, and MUST fire the Transfer event.

This method is payable, which means that ethers can be sent when calling it, but the transfer of ether needs to be handled in the call is executed after transfer since the one who receives the ether is the token contract and not the token receiver.

The transferFromAndCall method is used for a withdraw workflow, allowing contracts to transfer tokens on your behalf before executing a function.
The ERC20 transferFrom method is called before the _call(_to, _data).
This can be used for example to allow a contract to transfer tokens on your behalf and/or to charge fees in sub-currencies.
The function SHOULD revert if the call to _to address fails or if the _from approved balance by _from to msg.sender is not enough to execute the transfer.

Note Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event.

Important Note Do not use this method with fallback functions that receive the value transferred as parameter, there is not way to verify how much value was transferred on the fallback function.

  function transferFromAndCall(
    address _from, address _to, uint256 _value, bytes memory _data
  ) public payable returns (bool) {
    super.transferFrom(_from, _to, _value);
    _call(_to, _data);
    return true;
  }

approveAndCall - ERC827

Execute a function on _spender with the _data parameter, if the function ends successfully allows _spender to withdraw from your account multiple times, up to the _value amount. If this function is called again it overwrites the current allowance with _value.

This method is payable, which means that ethers can be sent when calling it, but the transfer of ether needs to be handled in the call is executed after transfer since the one who receives the ether is the token contract and not the token receiver.

Clients SHOULD make sure to create user interfaces in such a way that they set the allowance first to 0 before setting it to another value for the same spender.
The ERC20 approve method is called before the _call(_spender, _data).
The function SHOULD revert if the call to _spender address fails.
THOUGH The contract itself shouldn't enforce it, to allow backwards compatibility with contracts deployed before

  function approveAndCall(
    address _spender, uint256 _value, bytes memory _data
  ) public payable returns (bool) {
    super.approve(_spender, _value);
    _call(_spender, _data);
    return true;
  }

Events

Transfer - ERC20

MUST trigger when tokens are transferred, including zero value transfers.

event Transfer(address indexed _from, address indexed _to, uint256 _value)

Approval - ERC20

MUST trigger on any successful call to approve(address _spender, uint256 _value).

event Approval(address indexed _owner, address indexed _spender, uint256 _value)

Past Issues

The main issue that has been recognized by the community is that the standard does not follow the assumption about executing calls in behalf of a token contract, every smart contract that handle token balances assume the token contract will execute only the common methods and maybe a callback that is implemented by the token itself. This standard break that rule and allow the execution of arbitrary calls making it hard to integrate in current solutions.
UPDATE
This was solved by adding a simple proxy to the token and forwarding the calls coming from the token contract, the proxy ensure that the calls come only from the token contract and allows this to be verified on chain, this prevents the token address to be used as msg.sender allowing the integration with current solutions.

Discussion channel

https://gitter.im/ERC827

Revisions

  • 2019/02/19: Simple proxy integrated in token contract to forward calls to any other contract.
  • 2018/06/28: Changed implementation link in zeppelin-solidity for windingtree/erc827 repository.
  • 2018/06/27: Added warning, current issued of the standard and public channel link.
  • 2018/04/17: Rename of functions to avoid function overloading and added payable modifier to ERC827 functions.
  • 2018/02/13: Added CC0 copyright
  • 2018/02/13: Added complete function code and notes abouts usage of each function
  • 2018/01/11: Initial Draft

Implementation

ERC827 Interface in Winding Tree

[ERC827 Standard Token implementation in Winding Tree](https://github.com/windingtree/erc827/blob/master/contracts/ERC827/ERC827.sol

Copyright

Copyright and related rights waived via CC0

I really like the fact that it remains fully ERC20 compatible, and does not force receivers of the token to implement a certain function to signal that they accept them.

One question though: what is the rationale behind making the external call before the transfer or approval? I would have expected the call to occur afterwards, so the receiver of the tokens can check the transferred/approved balance and act upon it on that same call. And by throwing if the call goes wrong, the transfer gets rolled back all the same.

@spalladino In the approveData method the call is executed after the approve and in the transfer methods the call is executed before the transfer. At first all calls were executed before the ERC20 methods, but I changed the order in the approveData because I think the next call to be executed after an approve will want to have the amount to be transfered already approved, doing this you can execute a transferFrom inside the call and if all the things you wanted to do and check went fine you claim the tokens.

I think the order of the function call in approveData is not explained correctly in the issue, Im going to update it.

You are right that if the call fails the transfer and transferFrom will be reverted, the order can be changed and it will have the same effect I guess.

I have no problem on changing the order :)

Oops sorry, I misunderstood the order in approveData. As for the order in transferData and transferDataFrom, I'd follow the same approach of transfer-then-call as in approve, for the same reasons you mention. WDYT?

I agree, im going to change the description in the issue.

I like this. Where do you envision this standard relative to ERCs 20, 223, and 777? It seems like 827 is a fantastic stopgap that's 20-compatible that should be adopted relatively quickly before the community gets around to ratifying 223 or 777.

Thoughts?

I really like this, thanks a lot! What do you think about overloading transfer, approve and transferFrom functions considering the new bytes _data argument?

@shrugs yes I agree, less code is safer and easier to test, and I think this new methods fulfill the needs that the rest of the standards are trying to cover.

@facuspagnuolo but if we do that we will change the ERC20 function signatures and it wont be ERC20 compatible anymore, right? I think we cant have functions with the same name and different arguments, or we can? 🤔

@AugustoL as far as I know, if we provide an overloaded function changing the amount of parameters, I think it won't change the signature of the ERC20 functions, for example:

  • ERC20 transfer function will keep being: keccak256("transfer(address,uint256)")
  • ERC827 transfer function will be: keccak256("transfer(address,uint256,bytes)")

am I right?

@facuspagnuolo I think you are, let me do a quick test! 👀

Another quick thing, we might want to distinguish between throw and revert in the spec

@facuspagnuolo I changed the method names to be the same as ERC20 but with the data argument and the signature is different so there is not issue on having the same name but with the _data argument.

I think that allowing the token contract to call any function at any address is much less useful than calling some sort of tokensReceived method on the receiving contract (as in ERC223/777). Receiving contracts have no way of knowing that the calling address is a token contract, so they can't really do anything useful with the passed in data.

A big part of this is that msg.sender will always be the token address, where a tokensReceived method knows the intended sender from the passed in arguments. There is also no explicit way to link the token transfer to the function call, which really limits the possibilities.

It also seems like it could have unintended consequences to allow a token to call any arbitrary data. For example, if tokenA is accidentally transferred to an ERC827 token contract, anyone would be able to claim these tokens by simply calling tokenA.transfer(self, value) from the ERC827 token.

@abandeali1 thanks for the feedback! But I think this is more useful because you dont need to have any specific method in the receiver contract to call it, but if the contract has it you can still use it, so you can call any other contract and make use of the tokenFallback function. In fact I think we can say that this token is also ERC223-Receiver compatible ?

There is way to know who executed the transaction, you can send a signature of the msg.sata as a parameter and verify the signer in the contract that is receiving the call form the token. you can also use tx.origin but I understand that is not recommended.

And if there is tokens transfered to this contract they can be claimed by anyone, I dont see any problem there, at least they are not stuck there, which I think is the main problem, having tokens that are not able to being used.

@AugustoL this is partially true. The major difference is that in ERC223/777, from and value are always passed to the tokensReceived callback, so receiving contacts can rely on those arguments with the assumption that the token conforms to the standard. With ERC827, what is preventing me from telling the receiving contract that I transferred 10000000 tokens when I actually only transferred 1?

To the second point, this particular case might not be that bad. But this is just a single example of unintended consequences, and I can't confidently say that there aren't other cases out there that would lead to a worse outcome.

As of yesterday's release of zeppelin, those links in the above post no longer work because the contract code has been migrated into separate directories:

https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC827/ERC827Token.sol

Thanks @strotter ! fixed :)

I find one important problem with this standard. The call to the receiver's contract is not authenticated. The receiver's contract cannot tell if the data received comes in fact from the sender or anyone else. I see people will start using it in this way:

token.transfer(receiver,amount, abiEncodingOf(received(sender ,amount))
The receiver contract would have a method received(address sender, uint amount).
The security of this pattern is obviously completely broken.

It would be much much useful if the receiver would receive the arguments token, sender and amount right from the token contract, and not from the supposedly sender.

The pattern that uses approve/transferFrom can also lead to common mistakes if a honest sender uses token.transferFrom(receiver,amount), and then a malicious user uses token.transfer(receiver,0,simData) just to simulate the previous transferFrom() has a data argument.

Also this standard will break any other future standard that tries to fix this problem and try to notify a receiver with authenticated source/amount information. Once you allow the token to emit any message, you cannot authenticate anything later.

Still another problem is that you can use the token to send messages to itself. If the token contract is owner of tokens, then you can use this to steal the tokens from the token contract.

Very bad standard IMHO.

Now that I read the previous comments, I note that ALL that I said has been already said in a previous comment by @abandeali1

@SergioDemianLerner Thanks for your feedback!

We require that the the _spender and _to cant be the token address itself but I didnt had any note about that in the spec.

If the contract have any other tokens or assets they are open for grabs, I dont see a problem there since the contract in my opinion in only responsible of handling the internal balances.

Authentication is something that I think it can be done from the other contract too, without requiring the contract to be called to have a function to receive tokens.

How do you see message signing/verification being used in the receiver contract for authentication? If you need to authenticate a user it can send a signature of a hash generated inside the function and verify the real sender there.

I use a lot more transferFrom (with _data param) and approval to check the availability of the value that the sender is willing to transfer, and claiming it afterwards. The use of transfer (with _data param) can be useful for some cases, but I see much more utility in transferFrom & approve strategy for transferring value.

@AugustoL To be clear,

I use a lot more transferFrom (with _data param) and approval to check the availability of the value that the sender is willing to transfer, and claiming it afterwards. The use of transfer (with _data param) can be useful for some cases, but I see much more utility in transferFrom & approve strategy for transferring value.

You are talking about a pattern like this?

token.approve(receiver, value, keccak256("canRecieve(sender)");

Contract Receiver {
  function canReceive(address sender) public {
    uint256 allowedValue = tokenContract.allowance(sender, self);
    tokenContract.transferFrom(sender, self, allowedValue);
    doBusinessLogic();
  }

  function doBusinessLogic() { ... }
}

This would require the receiving contract be aware of the token contract address. It would be nice if the sender and value were passed as arguments so we would not need to do the approval-allowance-transferFrom dance.

@dadeg Something like that, yes! Keep in mind that you can send the value in the call data and you also can instantiate a ERC20 token using the msg.sender address.

token.approve(receiver, value, keccak256("canRecieve(sender, value)");

Contract Receiver {
  function canReceive(address sender, uint256 value) public {
    ERC20 tokenContract = ERC20(msg.sender);
    uint256 allowedValue = tokenContract.allowance(sender, value);
    tokenContract.transferFrom(sender, value, allowedValue);
    doBusinessLogic();
  }

  function doBusinessLogic() { ... }
}

Although I would recommend to have some way to specify the token address in the contract itself, if not it can be called from any ERC827 token.

Thanks! I am unsure if sending value is a wise idea, considering there is no guarantee that the value mentioned in the _data argument matches the value argument in the original approve call: token.approve(receiver, 10, keccak256("canReceive(sender, 1000)"))

As long as the receiving contract knows the address of the token contract, this approve-allowance-transferFrom pattern seems like a strong guarantee that nothing bad will happen. Even if the user initially screws up the approve() call, like typo-ing the _data string, token.approve(receiver, 10, keccak256("someTypoFunction(sender, 1000)")), they can recover by simply calling canReceive directly themselves, or calling approve again with the correct data signature. And the rest of the pattern is hardcoded in a single transaction to limit the UI/UX complications.

Edit: To add on to this, There is no risk of a malicious actor calling receiver.canReceive because the method is hardcoded to just check the token for the allowance from any arbitrary user. The assumption being that a user wouldn't call approve previously unless they actually intended on having the receiver take ownership of all the tokens immediately.

Please correct me if I'm wrong, but doesn't this standard mean that the resulting 827 tokens will not be compatible with most (all?) ERC223 #223 receiver contracts (to the extent they exist)? ERC223 requires that the receiving contract accept tokenFallback from pre-approved sending contract addresses to validate that the second argument 'value' represents a guaranteed transfer to the receiver. In this case, however, the invocation of tokenFallback will be composed by the caller of the transfer(with bytes) function. You can't know that they are not nefarious and crediting themselves with more tokens than they are indeed transferring.

This is essentially the same argument that @SergioDemianLerner and @abandeali1 made - and I concur. For the "transfer" function, this is at least useless and quite possibly dangerous. For the "approve", it works because the receiver then has to call transferFrom and can inspect the implementation of transferFrom to ensure they are satisfied with its behavior.

What happened to the old "approveAndCall" pattern? OpenZeppelin/openzeppelin-contracts#346

@yarrumretep as far as I can tell, the current implementation of microraiden, which is a #223 receiver contract, is susceptible to this attack:

https://github.com/raiden-network/microraiden/blob/master/contracts/contracts/RaidenMicroTransferChannels.sol#L149

But I wonder if this an issue with ERC827, or with #223 receivers (and #777 receivers for that matter). They probably shouldn't trust that tokens have been transferred. Otherwise they need to implement a white/black list to be safe.

Since when is it a good idea to execute arbitrary calls to contracts? Let alone make that part of a token standard?

Just popping in since I heard "microraiden".

Basically re-iterating what @abandeali1, @SergioDemianLerner and @yarrumretep mentioned.

In the spec you have this function:

function transfer(address _to, uint256 _value, bytes _data) returns (bool success)

You describe it as:

Execute a function on _to with the _data parameter, if the function ends successfully execute the
transfer of _value amount of tokens to address _to, and MUST fire the Transfer event.

The function SHOULD revert if the call to _to address fails or if _from account balance does not have enough tokens to spend.
The ERC20 transfer method is called before the _to.call(_data).

So essentialy I can do an ERC20 transfer of 1 token to contract _to but in the data I provide to it say I sent it 1 million tokens.

@LefterisJP i think your example highlights a weakness in the target contract, not in this token standard.

@dadeg As a 'receiving' contract under this standard as described above all I effectively get is a ping that my balance may change in the future by some unspecified amount. Because the standard does not mandate anything about the contents of the _data (nor could it really control that without a significant on-chain burden), the receiver isn't guaranteed anything in particular about the arguments passed therein and their relation to the 827 token contract's actual anticipated transfer. Receiver can't even keep his old balance and compare to verify because the actual transfer is not completed until after his call.

Any contract expecting to receive ERC223 tokens (with some kind of tokenFallback function) would not be able to receive tokens that implemented this function without specific precautions to prevent callers invoking tokenFallback in the _data parameter. tokenFallback value parameter can be trusted with sending contract source inspection. _data cannot be trusted to report the quantity of the transfer.

Also, couldn't this pattern of calling out prior to making data changes open this function to reentrancy issues?

The approveAndCall variant above, on the other hand, seems more reasonable and useful to me. There is no incentive to 'lie' about the amount being approved in the _data invocation - because the amount is either approved or not in the sending contract. Although it takes more gas than the 223 method, the only trust that must be verified before accepting calls from a sending token is that the tranferFrom function functions as advertised (and the rest of the token behaves in an ERC20 way). This is, in essence, a way to chain 2 calls together (approve and then doSomethingWithThisApproval). Existing ERC20 handlers expecting the approve/doSomething pattern might even be usable directly without modification (if they have a doSomething variant that doesn't depend on msg.sender).

@yarrumretep "Receiver can't even keep his old balance and compare to verify because the actual transfer is not completed until after his call."

This is interesting. If a user called approve, would the receiving contract be able to inspect the allowed amount (by calling allowance on the token) within the same transaction, or would it fail (or return 0) because the approve call does not finish until the receiving contract returns?

@dadeg not only inspect, but modify. Receiver can consume the allowance in the call directly.

@yarrumretep ok, that seems like a good thing. Would a receiving contract be able to do the same sort of inspection on a transfer call? Seems so. But there would be no way to guarantee the _data had the correct sender address. Transfer seems useless like you said.

Although a 223 tokenFallback receiver would have the same issue. There is no guarantee that tokenFallback is being called by a trustworthy 223 token contract. Even inspecting the source code of the caller would be problematic.

@yarrumretep @dadeg @LefterisJP @ptrwtts Thanks for the discussion and your feedback!

A quick summary of each function and their capabilities:

  • approve: Probably the one that you will need, maybe the only one since it allows the receiver contract to use "authenticated" balance. No issues here.
  • transfer: There is no way to check that the balance that will be transfered is the correct one, this function executed after the token transfer is useful when a function dont need to check any transfer of value.
  • transferFrom: Same as transfer, only useful when there is no need to check the transfered amount of tokens and want to spend approved balance.

To work with this standard a developer must understand all capabilities of each function and the big problems of using a wrong function can bring.

I think it would be enough to add a section in the proposal with this information.

What do you think? am I missing something? you would add something else?

I also though in removing the functions, but there are use cases for them and if they are used correctly it wont bring any issues. It should also be a decision of the developer which functions of this standard he needs and if he wants to add only approve he can do it.

@AugustoL what would be the difference between ERC677 ? it seems pretty much the same

@rstormsf The ERC677 adds only a call after transfer and the contract receiver need to have implemented the tokenFallback function, ERC827 dont ask the receiver contractto have any fallback function implemented since it can use approveAndCall strategy to work with authenticated/allowed balance.

ok, I see...hmmm. so technically, I can send a transfer of 10 tokens and have some data that would send even more tokens like 1mm if the user accidentally got malicious data parameter.
I think in that case, I'd prefer ERC777

Yes, thats why you should use the transfer method with a fallback function to that will receive the value transfered as parameter. You should use approve in that case.
I added some notes about howto/when use each function, if you do it that way you shouldnt have any issue.

I have found the transfer data very useful in discovering Proof of Valuation.. Thanks to the ERC827, I am able to attach a CCVO (Certificate of Valuation and Acknowldgment) to my ERC20 Token which provides critical reference to supporting documentation that verifies the VALUE assigned to the token.

Is there an example of ERC827 receiver?

@facundomedica for example over tx.origin:

ERC827 public token;

function payForTask(uint256 taskId, uint256 tokenAmount) public {
    token.transferFrom(tx.origin, this, tokenAmount);
    tasks[taskId].reward += tokenAmount;
}

You should call:

const data = contract.methods.payForTask(taskId, amount).encodeABI();
token.methods.approve(contract.options.address, amount, data).send();

@k06a should I add an address check? So I know that the tokens being received are coming from my deployed token and not somebody else's token.

@facundomedica token should be specified inside contract. May be a contact address.

@k06a Okay, I think I understood. That call will be called by the approve function. So if that function is called from other contract that is not the "real one" the transferFrom will just fail because of not having the required allowance. Thanks!

Hey, guys, if you wanna upgrade already launched token for example to support ERC827, this can be made without holders transition if your token is at least Pausable: https://medium.com/bitclave/the-easy-way-to-upgrade-smart-contracts-ba30ba012784

Let's make ERC827 approve method payable?

function approve(address _spender, uint256 _value, bytes _data) public payable returns (bool) {
    require(_spender != address(this));
    super.approve(_spender, _value);
    require(_spender.call.value(msg.value)(_data));
    return true;
}

I wanna chain this operations into single tx:

  1. Approve MyToken to MySmartContract
  2. Buy MyToken for ETH in Bancor
  3. MySmartContract to call transferFrom to receive MyTokens

PR: OpenZeppelin/openzeppelin-contracts#838

Hi Everyone,

I am a contributor on vyper (vyperlang/vyper#738) and was pointed here to the fact that function overloading gets used. Could we consider another alternative like renaming of the functions for clarity?

Vyper purposefully does not support function overloading, and probably never will. Consider that this is to be a standard, I don't think forcing all underlying contract languages to have function overloading seems reasonable like a reasonable standard. Function overloading is quite risky from an auditing perspective, specially in this case because of the additional call happening on each of the methods (function overloading introduces a lot of ambiguity).

@jacqueswww thx for bringing up that! If function overloading does not allow the implementation of this standard in vyper I think the function names should be changed. Im going to try to change it in the implementation of zeppelin-solidity first before change the standard doc here.

@AugustoL what about making ERC827 approve method payable?

Does the _data in ERC827 functions means that the for the *.call(_data) to work the invoker has to be a contract .

Thank you , it will be great if we add a line in the spec telling that , if the *.call(_data) , has to work , the programmer has to be sure that , the "whoever".call(_data) , the whoever parameter passed should be a contract and 827 is intended to enable contracts to work more efficiently .

Other wise a naive person like me will get confused .

@vu3mmg k06a it can be any address, account or contract. The only address that cant be use is the ERC827 token itself.

@AugustoL basic query , due to my ignorance I am asking this .
if the address is that of an account , the invocation of whoever.call(_data ) will fail ? since the account address does not have the method /ABI encoded in _data ?

@vu3mmg yes it will fail.

@AugustoL agree about both types of addresses, but why do you think target can't be ERC827 contract itself?

I think ERC 827 may break ERC20 , since ERC 20 does not differentiate between accounts or contracts and for practical purpose ERC 827 needs "contract address" . Is this understanding correct .

ERC827 do not needs "contract address". Think of ERC87 as a way to combine in single transaction calls of approve and transferFrom.

@k06a but execution of approve() and transferFrom() will not happen properly if the caller is not a contract , with given ABI?.
But in case of ERC 20 , it will happen , irrespective of the address type , since the result is just a value adjustment in a mapping ? nothing goes out .
I dont doubt the utility of ERC827 , we are implementing some use cases using the same. Hence hit on the issues

@vu3mmg if you want to execute a function in an account it will fail, if you want to only transfer token value you can execute the common ERC20 methods without the _data argument and the call wont be executed.

A PR to fix the issues Vyper is having on Open Zeppelin:
OpenZeppelin/openzeppelin-contracts#871

@AugustoL . Thank you . That resolves the issue. It will be great that if you can explicitly add couple of lines in the standard pointing to the overloading of methods . Otherwise a new reader might get confused. Also could you please point out that ERC 827 methods will fail if it is invoked on an account .
I understand that one of the main purpose of ERC 827 is to manage transfers between contracts efficiently and add the notion of purpose .

@elie222 maybe to keep both method names?

According to OpenZeppelin/openzeppelin-contracts#887, I suggest to add the abstract methods increaseApproval and decreaseApproval to ERC827 interface so that we enforce the need for an ERC827 token to provide an implementation of these methods.
From this:

To this:

Is there any list of tokens already supporting ERC827?

@k06a I am planning on using a variation of ERC827. I need to be 100% sure (without using tx.origin) that all my functions in the receiver contract will have the actual sender as the last parameter. I have come up with this :

contract AuthERC827Token is ERC827Token {
    event AuthEnabled(address indexed sender);
    event AuthDisabled(address indexed sender);

    mapping (address => bool) public usesAuth;

    modifier checkAuth(address _receiver, bytes _data) {
        if (usesAuth[_receiver]) {
            require(_authSender(_data, msg.sender));
        }
        _;
    }

    function enableAuthentication() external returns (bool) {
        require(!usesAuth[msg.sender]);

        usesAuth[msg.sender] = true;
        emit AuthEnabled(msg.sender);
        return true;
    }

    function disableAuthentication() external returns (bool) {
        require(usesAuth[msg.sender]);

        usesAuth[msg.sender] = false;
        emit AuthDisabled(msg.sender);
        return true;
    }

    function approve(address _spender, uint256 _value, bytes _data) 
        public 
        checkAuth(_spender, _data) 
        returns (bool) 
    {
        return super.approve(_spender, _value, _data);
    }

    // do the same for transfer, transferFrom, increaseApproval, decreaseApproval
    // ...

    /**
    *@dev Checks if the last 20 bytes in _data match msg.sender
    *@param _data bytes ABI-encoded contract call that needs to be checked
    *@return true if the last 20 bytes in _data match msg.sender
    */
    function _authSender(bytes _data, address _actualSender) internal pure returns (bool) {
        require(_data.length >= 36);

        bytes memory senderAddress = new bytes(20);
        uint256 dataLength = _data.length;
        dataLength = dataLength - 20;

        for(uint256 i=0; i<=19; i++) {
            senderAddress[i] = _data[dataLength + i];
        }
        return (keccak256(senderAddress) == keccak256(_actualSender));
    }
} 

Receiver contracts register themselves to use the auth check. When that happens, all the functions in the receiving contract that need to work with tokens, should have an address as the last parameter. That address will always be the initiator of the transaction (can be a contract too ... so better than using tx.origin checks, or adding signatures to the _data). Example of receiving function :

function useTokens(uint256 _tokenAmount, address _sender) public returns (bool) {
      if (msg.sender != address(token)) {
          _sender = msg.sender;
      }
      require(token.allowance(_sender, address(this)) >= _tokenAmount);
      // transferFrom + more logic 
      // ....
}

I want to reduce gas gost for _authSender (it's at 5600 right now) but I'm not that good at assembly. Let me know what you guys think.

@mad2sm0key why do you need this check at all, why not to use tx.origin? I think you can also avoid require(token.allowance...) because transferFrom call will check this case.

@k06a tx.origin will not work for contracts that own tokens. tx.origin will be the address that initiated the transaction, not the address of the contract owning the tokens. You are right about the allowance check, thanks.

@mad2sm0key what do you think about this idea? #1003

@ProphetDaniel The increase and decrease approval funcitons are not taken in count in this standard because It tries to be extend only ERC20 methods functionality, in zeppelin we have the the ERC827 file that only extend the three methods of ERC20. The ERC827 token standard implementation is an extension of the ERC20 token standard that zeppelin use.

I just modified the ERC827 standard based on the discussions we had about function overloading and use of payable modifiers, the PRs introducing those changes are:

OpenZeppelin/openzeppelin-contracts#871
OpenZeppelin/openzeppelin-contracts#838

The standard is still a draft and I think that with these changes and after months of being reviewed and being used by the community in open source libraries we can start thinking about making it final, but I really dont know how to measure the maturity and decide weather if ready or not.

Hey, I have an idea how to avoid tx.origin touching by transferring tokens over token smart contract itself. This scheme is also proposed in #1003 – where this several calls moved from web3 into token smart contract.

ERC827 public token;

// Example 1
function payForTask(uint256 taskId, uint256 tokenAmount) public {
    token.transferFrom(msg.sender, this, tokenAmount);
    tasks[taskId].reward += tokenAmount;
}

// Example 2
function creditAccount(address beneficiary, uint256 tokenAmount) public {
    token.transferFrom(msg.sender, this, tokenAmount);
    balances[beneficiary] += tokenAmount;
}

You should call:

const payForTaskData = contract.methods.payForTask(taskId, amount).encodeABI();
const approveAndCallData = token.methods.approveAndCall(contract.options.address, amount, payForTaskData).encodeABI();
token.methods.transferAndCall(token.options.address, amount, approveAndCallData).send();

Would you consider to harmonize function names and conventions with ERC721?

@fulldecent yes of course. what do you have in mind?

Here are the changes I would make.

  • Use a proper interface specification, see for example: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md#specification
  • Check that the interface is valid in Remix IDE (for example, this standard currently uses constant which is deprecated)
  • Require ERC165 support
  • Use name safeTransferFrom
  • In safeTransferFrom call onERC827Received on recipient and throw unless getting the magic value or the recipient is a plain account
  • Use the callback function AFTER the transfer is successful (this avoids reentrancy attack)
  • Use RFC 2119 language
  • Remove acceptAndCall, I do not see a market demand for this
  • Specify what happens if decimals is not implemented

Break backwards compatibility with ERC-20, be bold:

  • Make approve payable
  • Remove transfer function, only use transferFrom and safeTransferFrom -- RATIONALE: the wallets should hide this extra complexity from the use. Less functions is good. By dropping transfer we reduce the risk that somebody will send money on their own behalf when they meant to send money from another account they have approve access to.
  • Throw if transfer fails, do not return a bool
  • ORIGINAL RESEARCH: consider changing approve to approve(_to, _old, _new) and it throws if the current approved amount is not _old
  • Make total supply optional

I still not understand what it means, but can I use wallet erc20 to recieve erc827?

You fail to implement #223 while implementing #667
transferFrom and approve should be abolished
Search before posting and stop posting dupes.

We wrote a blog post, how replacing ERC20 with ERC827, can lead to unexpected reentrancy attacks:
https://medium.com/chainsecurity/why-erc827-can-make-you-vulnerable-to-reentrancy-attacks-and-how-to-prevent-them-61aeb4beb6bf

The example is an OpenZeppelin Crowdsale. Feel free to give feedback.

@ritzdorf it seems you successfully shooted in your own leg.

@ritzdorf because using transferAndCall absolutely not needed in _deliverTokens. Really I don’t know where transferAndCall should be used – the main gem of ERC827 is approveAndCall which allows to chain ‘approveandtransferFromcalls fromaccount address` in a single transaction. To deposit smart contracts with tokens in a single tax.

@k06a Thanks for the clarification.

  1. Given that potential use cases of transferAndCall are unclear, I see the value of our article in clarifying how it should not be used.
  2. Similar issues apply to approveAndCall, however, given that this functionality does not exist in ERC20 (as you said), we would have had to construct an example with vulnerable code to use it. If you have concrete cases, where approveAndCall is called from a smart contract we would be happy to check.

Overall, our intention was just to notify people that special care is needed when using these functions inside a smart contract.

It also seems like it could have unintended consequences to allow a token to call any arbitrary data. For example, if tokenA is accidentally transferred to an ERC827 token contract, anyone would be able to claim these tokens by simply calling tokenA.transfer(self, value) from the ERC827 token.
#827 (comment)

anybody care explaining why this would happen?

don't get why tokenA transferred into a ERC827 can be claimed by anybody

@DiveInto because tokenA smart contract itself can contain any amount of token* (incl tokenA). And smart contract looks like any other account when trying to contact another token smart contract methods. He will be the msg.sender of any call he is going to perform with data.

This seems unsafe for any external contract using #677 and defining two ways users could interact with it.

Imagine I put #827 into DEX by normal means (deposit function, which calls transferFrom(me)) and this DEX also supported #677 tokenFallback. Now a bad actor could transferAndCall or approveAndCall with parameters to: 0xDEX, value: 0, data: [ func: 0xtokenFallbackHashBytes4, from: 0xThem, value: 0xALot, data: [ 0xSthSth ] ].

Now if the DEX implementation doesn't store the information on how much of every ERC20 it should own and compare that with erc20.balanceOf(this) when tokenFallback is called, a bad actor could just withdraw 0xALot of this token.

@mg6maciej The token contract fills in the amount and form fields in the callback. The user doesn't get to set them.

@MicahZoltu Many do (#223, #667, #721, #777), but not this one. This one warns:

Important Note Do not use this method with fallback functions that receive the value transfered as parameter, there is not way to verify how much value was transfered on the fallback function.

This is exactly what a bad actor will not not do. Instead they will try to find contracts where they can abuse it.

commented

Same post as OpenZeppelin/openzeppelin-contracts#1044.
Proposal discussions should be continued here.

It is a really bad practice to allow the abuse of CUSTOM_CALL in token standard with anythingAndCall.

<address>.call.value(msg.value)(_data)

Users are allowed to pass arbitrary data, leading to call any function with any data on any contract address.

Attackers could call any contract in the name of vulnerable contract with CUSTOM_CALL.

This vulnerability will make these attacking scenarios possible:

  • Attackers could steal almost each kind of tokens belong to the vulnerable contract [1] [2] as also mentioned by @k06a

  • Attackers could steal almost each kind of tokens approved to the vulnerable contract

  • Attackers could bypass the auth check in vulnerable contract by proxy of contract itself in special situation [3] (edit: current openzeppelin implementation is not affected with the help of require(_to != address(this));)

  • Attackers could pass fake values as parameter to cheat with receiver contract [4] as mentioned by @mg6maciej

We (SECBIT) think that the ERC827 proposal should be discussed further in community before OpenZeppelin putting the implementation in the repo. Many developers could use this code without knowledge of hidden danger.

@p0n1, first three issues can be solved by denying _to to be equal to this. Also approveAndCall should be used for avoiding wrong arguments issues, other methods are really not reliable, and I think they are not needed at all.

@p0n1 what k06a says has been already implemented in the zeppelin implementation

commented

@p0n1, first three issues can be solved by denying _to to be equal to this.
@p0n1 what k06a says has been already implemented in the zeppelin implementation

@k06a @AugustoL haha. I don't think so.

Adding require(_to != address(this)); will only protect contract token itself.

In this case for example, only TE-FOOD Token will be protected but ERC20 (MOAT Token) will not be.

That's why I said "could steal almost each kind of tokens".

Third issue could be solved actually.

@p0n1 Thanks for speaking up. I'm currently discussing reasons to abandon proposals like #827 and #1003 with @AugustoL in a private channel. If we don't find consensus or there will be no more replies, I'll seek support from the community at large.

@p0n1 maybe also check first 4 bytes of _data and deny signatures of transfer and transferFrom ERC20 methods?

@mg6maciej @p0n1 I think the token shouldnt care about other tokens, it is not like every contract will take in count how to recover tokens when you arent supposed to send it there.
ERC20 smart contracts that received tokens they are lost. At least here they are at least still in circulation.
In case that we decide to add a recovery method for tokens. How will you implement it? We can add it to the issue.
If you want contact me privately and we can discuss it together. Im open for everything that will improve the standard without adding to much complexity.

@mg6maciej both #827 and #1003 will be not needed in case #1035 will be implemented in EVM. This will allow batching account transactions without chaining them.

@AugustoL I think allowing token creator to reclaim any tokens from smart contract is the best possible solution to resolve this kind of issue: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/CanReclaimToken.sol

commented

@AugustoL It appears to be not really a critical economic problem in most case when considering the tokens stuck at the contract balance got stolen by anyone else. But we still need to be careful with other unknown scenarios. People could combine ERC827 with other codebase.

We found many deployed contracts using ERC827 or ERC223 _custom_fallback allowed version.

https://github.com/sec-bit/awesome-buggy-erc20-tokens/blob/master/csv/custom-call-abuse.o.csv

Most of them in the list are just code learned from the recommend code templates by now.

@p0n1 I agree this is not too much of a problem with another tokens accidentally sent to ERC827 contract.
I'm concerned mostly with something like this: https://gist.github.com/mg6maciej/8af66a0cfb6ac318fa8cedeb4fd246d3
This code is safe for ERC20, ERC223, ERC667 and ERC777, but anyone putting ERC827 will lose them to an attacker.
If you look at this code as a base for DEX like EtherDelta, but with support for ERC677 and ERC777, you may immediately notice the problem. Attacker can grab all the ERC827 tokens, fill orders that want to buy these tokens for different tokens, do it multiple times if they want to fill more orders, after that withdraw all these ERC827 tokens, transfer to another exchange and sell them one more time.

I created a gitter channel to discuss about ERC827 standard, implementations and governance of the standard.

https://gitter.im/ERC827/Lobby

I also created a public calendar on google calendar for ERC827 community calls, maybe to happen once every two weeks, where anyone in the community can join. The first call will be 5 of june at 5pm GMT +2.

Link to the call: https://calendar.google.com/event?action=TEMPLATE&tmeid=NjU5a2VnZmxsaTBycXVxdXQzYmJkcGpzZDkgbjg3bDdvcXVmMTQybmY4MGxlMGtoM3J2cThAZw&tmsrc=n87l7oquf142nf80le0kh3rvq8%40group.calendar.google.com

Link to the ERC827 calendar: https://calendar.google.com/calendar?cid=bjg3bDdvcXVmMTQybmY4MGxlMGtoM3J2cThAZ3JvdXAuY2FsZW5kYXIuZ29vZ2xlLmNvbQ

Is this bug actually a feature if a token is only meant to be used within a particular ecosystem, targeting specific contracts that don't have a tokenFallback function, and not freely traded or sent to arbitrary contracts? This issue pretty much guarantees that ERC827 tokens couldn't be listed on decentralized exchanges, and would therefore be less vulnerable to securitization if the token is meant to be a marker within a limited system, and not a tradeable store of value subject to market forces and speculation.

I just added a PR with a proposal with changes over current standard that adds more control to the receiver contract allowing it to specify which functions can be executed over it from the token contract.

windingtree/erc827#2

Let's just add ERC827Caller contract:

contract ERC827Caller {
    function makeCall(address _target, bytes _data) external payable returns (bool) {
        // solium-disable-next-line security/no-call-value
        return _target.call.value(msg.value)(_data);
    }
}

And use it this way:

contract ERC827Token {
    ERC827Caller internal caller_;

    constructor() public {
        caller_ = new ERC827Caller();
    }

    function approveAndCall(
        address _spender,
        uint256 _value,
        bytes _data
    )
        public
        payable
        returns (bool)
    {
        require(_spender != address(this));

        super.approve(_spender, _value);
        require(caller_.makeCall.value(msg.value)(_spender, _data));

        return true;
    }
}

@k06a I dont see how forwarding the calls trough another contract will fix the current issue of allowing arbitrary calls executed by default to any contract from the token contract.

I think the solution in the PR windingtree/erc827#2 might be better because it removes the allowance of arbitrary calls from the token contract by default, but any contract can allow the execution of specific functions on it.

Here is the summary of the PR:

The receiver contract where the callback function will be executed now needs to allow the execution of that callback itself, if the sender attempt to execute a callback that is not allowed on a receiver contract it will fail.
The callbacks can be allowed to certain address or they can be public, which means that anyone can execute it. There is also the option for a receiver contract to allow the execution of any function from any address.

I invite you to create a proposal with the changes you suggest on the windingtree/erc827 repository where we can test it against another proposals.