Let's look at how to send ether to any address. To send ether, you need to use the web3.eth.sendTransaction() method. This method can be used to send any kind of transaction but is mostly used to send ether because deploying a contract or calling a method of contract using this method is cumbersome as it requires you to generate the data of the transaction rather than automatically generating it. It takes a transaction object that has the following properties:
- from: The address for the sending account. Uses the web3.eth.defaultAccount property if not specified.
- to: This is optional. It's the destination address of the message and is left undefined for a contract-creation transaction.
- value: This is optional. The value is transferred for the transaction in wei as well as the endowment if it's a contract-creation transaction.
- gas: This is optional. It's the amount of gas to use for the transaction (unused gas is refunded). If not provided, then it's automatically determined.
- gasPrice: This is optional. It's the price of gas for this transaction in wei, and it defaults to the mean network gas price.
- data: This is optional. It's either a byte string containing the associated data of the message or in the case of a contract-creation transaction, the initialization code.
- nonce: This is optional. It's an integer. Every transaction has a nonce associated with it. A nonce is a counter that indicates the number of transactions sent by the sender of the transaction. If not provided, then it is automatically determined. It helps prevent replay attacks. This nonce is not the nonce associated with a block. If we are using a nonce greater than the nonce the transaction should have, then the transaction is put in a queue until the other transactions arrive. For example, if the next transaction nonce should be 4 and if we set the nonce to 10, then geth will wait for the middle six transactions before broadcasting this transaction. The transaction with nonce 10 is called a queued transaction, and it's not a pending transaction.
Let's look at an example of how to send ether to an address:
var txnHash = web3.eth.sendTransaction({
from: web3.eth.accounts[0],
to: web3.eth.accounts[1],
value: web3.toWei("1", "ether")
});
Here, we send one ether from account number 0 to account number 1. Make sure that both the accounts are unlocked using the unlock option while running geth. In the geth interactive console, it prompts for passwords, but the web3.js API outside of the interactive console will throw an error if the account is locked. This method returns the transaction hash of the transaction. You can then check whether the transaction is mined or not using the getTransactionReceipt() method.
You can also use the web3.personal.listAccounts(), web3.personal.unlockAccount(addr, pwd), and web3.personal.newAccount(pwd) APIs to manage accounts at runtime.