It sounds like a misunderstanding.
It's not possible to write a contract that will reach out and spend the sender's funds. You get a transaction hash before the network processes it, and very possibly things are going wrong.
Let's consider three parties:
- Sender
- Beneficiary
- Contract
The sender can send funds to the contract. The contract can forward received funds (or spend its own) to the beneficiary.
It would be fairly common to write a function that receives funds from the sender and sends them on to the beneficiary. In that case, the function must be tagged with the keyword payable
, otherwise, it will throw and revert when Ether is attached.
I'm not certain what coin -= amount
does.
Here's approximately what it would look like to forward received Ether.
function sendPayment(address beneficiary) payable returns(bool success) {
if(msg.value==0) throw;
if(!beneficiary.send(msg.value)) throw;
return true;
}
To forward funds with that function, send it with (roughly) contractInstance.sendPayment(beneficiary, {from: sender, to: contract, value: amount}).then(function(txnHash) ...
Notice I removed amount
from the function. I think the idea is it's implicitly the amount of Ether sent.
Also worth noting. It's important to wait for the transaction to be mined to see the final result.
Hope it helps.
Account address and password alone cannot be used alone. The password you are talking about is used to decrypt the encrypted private key.
There is an article which you can use to send ether from one party to another.
The steps followed are as follows:
- Create Web3j object to connect ethereum server.
- Calculate transaction fee which is essential for doing transaction. Transaction fee will be equal to
gas * gas price
, i.e. minimum gas required for transation is 21000.
- Create credentials object.
Prepare txn by adding the details.
var rawTx = {
nonce: web3.toHex(nonce),
gasLimit: web3.toHex(41334),
gasPrice: web3.toHex(10),
to: addressTo,
from: addressFrom,
value: web3.toHex(100)
}
Sign the txn using the private key
- Serialize the txn and convert it to hex
- Send the raw txn.
For more details you can refer to the documentation of web3j.
Best Answer
This contract works and there is no need to change it.
The user interacting with this contract must send Ether in the transaction in order to trigger a transfer to the
_receiver
. The Ether gets sent to the contract, and lives there prior to transfer from the contract to the_receiver
.I would suggest removing
_amount
and simply usingmsg.value
to send the entire value that is sent in the transaction.Additionally, this can be done with a simple transaction and does not decessarily need a smart contract.