DApp
以太坊JSON RPC
curl -X POST -d '{"jsonrpc":"2.0","method":"eth_gasPrice","params":[],"id":xx}' -H 'Content-Type: application/json' https://exchaintestrpc.[xxx].org
Web3.js及示例
const http = require('http');
const sendCoin = require('./sendCoin').sendCoin;
const server = http.createServer();
server.on('request', async (req, res) => {
if (/^/dapp-api/getCoin/.test(req.url)) {
const address = req.url.replace(/.*=(\w+)/, '$1');
const result = await sendCoin(address);
res.write(JSON.stringify(result));
}
res.end();
});
server.listen(10086, () => {
console.log('');
});
const Web3 = require('web3');
const abi = require('./abi');
const privateKey = require('./privateKey');
const httpProvider = new Web3.providers.HttpProvider('https://exchaintestrpc.[xxx].org');
const web3 = new Web3(httpProvider);
const account = web3.eth.accounts.privateKeyToAccount(privateKey);
const address = account.address;
web3.eth.accounts.wallet.add(account);
const contract = new web3.eth.Contract(abi, '0x2C6dabC8a40EB2df66d4f2D7A250c50E62283F77');
async function getBalance() {
try {
const balance = await contract.methods.getBalance().call({from: address});
return web3.utils.fromWei(balance);
} catch(err) {
console.log(err);
}
return 0;
}
async function sendCoin(receiverAddress) {
try {
const gasPrice = await web3.eth.getGasPrice();
const data = await contract.methods.sendCoin(receiverAddress).send({
from: address,
gasLimit: web3.utils.toHex(8000000),
gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
})
return data;
} catch (err) {
console.log(err);
}
return {};
}
module.exports.getBalance = getBalance;
module.exports.sendCoin = sendCoin;