[Ethereum] How to get a string value from msg.data in the fallback function

bytescalldatafallback-functionsoliditystring

Im trying to do what The DAO did and do something when a sender sent money to my contract address. But im not sure how to.
The something I want to do is to just create a new user in a mapping with the string sent in the msg.data object.

I have heard about the fallback function, and thought I could extract the msg.data. But that seems to be bytes. Do I have to convert it? If so how do you do that?

Here is my code:

Premium.sol

struct User {
    address user;
    bool paid;
}

mapping(string => User) PremiumUsers;
address owner;


function Premium() {
    owner = msg.sender;
}

function () {
  var mail = byteconverterToString(msg.data);
  var newUser = PremiumUsers[mail];
  newUser.user = msg.sender;
  newUser.paid = true;
}

Best Answer

IF the fallback function only gets 2300 gas, it can't write to contract storage and here are 2 ideas.

Option 1

You could add an explicit function like receiveEther(string senderName) in the contract. web3.js can be used like contractInstance.receiveEther("name of the sender", {value: web3.toWei(1, "ether"), ...}) and the contract could access the sender name and msg.value easily without parsing the ABI.

Option 2

If you want to avoid having a function the user has to call, then in your contract fallback function you emit an event with msg.data. The app listens for the event and can then parse and store the event data in a database, or if you want to store the data in the contract, the app makes a transaction to the contract to store the data.

A difference with option1 is that storing the data in the contract is a second transaction. It is easier for the user that they don't need to call a function, but the app needs to be built robustly so that the data gets stored (whatever is listening for the event might go down).

Related Topic