Blockchain – How to Send Data to Another Address with Solidity

ethereumjssoliditytestrpc

I have been practicing writing smart contracts using solidity and testrpc. How can I write and test a simple script that will send a message (e.g. "hello world") to another user on the blockchain. All the smart contracts I've written so far just involve mutating data from one address. Where will the messages get stored, and how will users read the messaged? I'm having great confusion understanding the high level architecture of this problem, and would greatly appreciate any input.

Best Answer

Data is always stored in the smart contract. So, technically, you won't be sending a message to another address, but you would be sending said message to the contract, and then the recipient would be able to access it.

Here's an extremely simplified example:

contract Messenger {

  mapping (address => string) message;

  function sendMessage(address _recipient, string _message){
    message[_recipient] = _message;
  }

  function readMessage() returns (string) {
    return message[msg.sender];
  }

}

As I mentioned, this is an extremely simplified example to illustrate what I'm saying and it won't do as a "chat app", having said that...

In this example you have a mapping which stores a given message for a user. Basically, anyone could call the sendMessage function, providing an address (the recipient of the message) and the message itself.

Then, the receiver simply calls readMessage() which will lookup the message mapped to his address.

So, as you can see, address A is not sending a message to address B directly, as a matter of fact, you can't "communicate" from an External Account (a human) to another External Account directly, except for sending ether. There has to be a smart contract in between which will receive a command and do whatever it was programmed for. In this case, it receives a message and recipient and stores that data so the recipient can later access it.

Related Topic