Home | 简体中文 | 繁体中文 | 杂文 | 知乎专栏 | 51CTO学院 | CSDN程序员研修院 | Github | OSChina 博客 | 腾讯云社区 | 阿里云栖社区 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏多维度架构

15.4. infura.io web3.js 开发

15.4.1. Web3 通过 infura 连接到 Ropsten 测试网络

			
fs = require('fs');
const Web3 = require('web3');
const web3 = new Web3('https://ropsten.infura.io/CsS9shwaAab0z7B4LP2d');
console.log(web3.version)
const abi = fs.readFileSync('output/TokenERC20.abi', 'utf-8');

const contractAddress = "0x70682386d0dE84B1e549DC3c4305CCB2D261b2a8";
const coinbase = "0xB94054c174995AE2A9E7fcf6c7924635FBa8ECF7";
const toAddress = "0xf56b81a2bcb964D2806071e9Be4289A5559BB0fA";

balanceWei = web3.eth.getBalance(coinbase);
console.log(balanceWei);

const contract = new web3.eth.Contract(JSON.parse(abi), contractAddress, { from: coinbase , gas: 100000});

contract.methods.balanceOf(coinbase).call().then(console.log).catch(console.error);
contract.methods.balanceOf(toAddress).call().then(console.log).catch(console.error);	
			
			

15.4.2. 使用 truffle-hdwallet-provider 连接到 https://ropsten.infura.io

			
fs = require('fs');
const Web3 = require('web3');
const HDWalletProvider = require("truffle-hdwallet-provider");
const mnemonic = "drill hunt food team moment mistake bird attitude tunnel ecology sister resist";
const web3 = new Web3(new HDWalletProvider(mnemonic,'https://ropsten.infura.io/CsS8shwaCab0a7B4LP2d'));
console.log(web3.version)
const abi = fs.readFileSync('output/TokenERC20.abi', 'utf-8');

const contractAddress = "0x70682386d0dE84B1e549DC3c4305CCB2D261b2a8";
const coinbase = "0xB94054c174995AE2A9E7fcf6c7924635FBa8ECF7";
const toAddress = "0xf56b81a2bcb964D2806071e9Be4289A5559BB0fA";

balanceWei = web3.eth.getBalance(coinbase);
console.log(balanceWei);

const contract = new web3.eth.Contract(JSON.parse(abi), contractAddress, { from: coinbase , gas: 100000});

contract.methods.balanceOf(coinbase).call().then(console.log).catch(console.log);
contract.methods.balanceOf(toAddress).call().then(console.log).catch(console.log);
			
			

15.4.3. 转账

			
	const coinbase = "0xB94054c174995AE2A9E7fcf6c7924635FBa8ECF7";
	const toAddress = "0xf56b81a2bcb964D2806071e9Be4289A5559BB0fA";			
	const privateKey = "e33ea581d88e0bd2270c0fd109604039a3de59671b6d69882b4cb4688d3dcffd"
	
	var nonce = await web3.eth.getTransactionCount(coinbase);
	var gasPrice = await web3.eth.getGasPrice();
	console.log(`gasPrice: ${gasPrice}\n`)
    var gasLimit = 1000000;
	var transferAmount = 1000;
    var chainId = 1;

    var rawTransaction = {
        "from": coinbase,
        "nonce":  web3.utils.toHex(count),
        "gasPrice": web3.utils.toHex(gasPrice),
        "gasLimit": web3.utils.toHex(gasLimit),
        "to": toAddress,
        "value": "100",
        "data": "0x0",
        "chainId": web3.utils.toHex(chainId)
    };
   
    var privateKey = new Buffer(privateKey, 'hex');
    var tx = new Tx(rawTransaction);
    tx.sign(privateKey);
    var serializedTx = tx.serialize();

    web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')).on('receipt', console.log);
			
			
			
'use strict';
const Web3 = require('web3');

const wsAddress = 'wss://rinkeby.infura.io/ws';
const contractJson = '(taken from solc or remix online compiler)';
const privateKey = '0xOOOX';
const contractAddress = '0xOOOX';
const walletAddress = '0xOOOX';

const webSocketProvider = new Web3.providers.WebsocketProvider(wsAddress);
const web3 = new Web3(new Web3.providers.WebsocketProvider(webSocketProvider));
const contract = new web3.eth.Contract(
  JSON.parse(contractJson),
  contractAddress
);
// change this to whatever contract method you are trying to call, E.G. SimpleStore("Hello World")
const query = contract.methods.SimpleStore('Hello World');
const encodedABI = query.encodeABI();
const tx = {
  from: walletAddress,
  to: contractAddress,
  gas: 2000000,
  data: encodedABI,
};

const account = web3.eth.accounts.privateKeyToAccount(privateKey);
console.log(account);
web3.eth.getBalance(walletAddress).then(console.log);

web3.eth.accounts.signTransaction(tx, privateKey).then(signed => {
  const tran = web3.eth
    .sendSignedTransaction(signed.rawTransaction)
    .on('confirmation', (confirmationNumber, receipt) => {
      console.log('=> confirmation: ' + confirmationNumber);
    })
    .on('transactionHash', hash => {
      console.log('=> hash');
      console.log(hash);
    })
    .on('receipt', receipt => {
      console.log('=> reciept');
      console.log(receipt);
    })
    .on('error', console.error);
});
			
			

15.4.4. 执行合约

			
const fs = require('fs');
const Web3 = require('web3');
const web3 = new Web3("https://mainnet.infura.io/CsS9shwaAab0z7B4LP2d");
const Tx = require('ethereumjs-tx');

const abi = [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_status","type":"bool"}],"name":"setAirdropStatus","outputs":[{"name":"status","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"airdropStatus","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_mintedAmount","type":"uint256"}],"name":"mintAirdropToken","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_value","type":"uint256"}],"name":"burn","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_lock","type":"bool"}],"name":"setLock","outputs":[{"name":"status","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_address","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"airdropCurrentTotal","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"target","type":"address"},{"name":"mintedAmount","type":"uint256"}],"name":"mintToken","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"}],"name":"burnFrom","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_amount","type":"uint256"}],"name":"setAirdropAmount","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"frozenAccount","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"airdropTotalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"touched","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"target","type":"address"},{"name":"freeze","type":"bool"}],"name":"freezeAccount","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"lock","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"airdropAmount","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"initialSupply","type":"uint256"},{"name":"tokenName","type":"string"},{"name":"tokenSymbol","type":"string"},{"name":"decimalUnits","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Burn","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"target","type":"address"},{"indexed":false,"name":"frozen","type":"bool"}],"name":"FrozenFunds","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"target","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"AirDrop","type":"event"}];
const address = "0x3e827461Cc53CAE366175A291ed7c629F87CfF39";
const key = "19A57E4F6274AF1E0B9C3F8F7E3503876A850AFEE1912B8B9C5D9358EDEA0362"

const contractAddress = "0x44cCf3d1601427Fe0B0f7588eD058216830cd13C";
const contract = new web3.eth.Contract(abi, contractAddress, { "from": address});

contract.methods.balanceOf(address).call().then(function(balance){
    console.log(balance)
});

contract.methods.decimals().call().then(function(decimals){
    console.log(decimals)
});
    
web3.eth.getGasPrice().then(function(gasPrice){
    var price = Number(gasPrice);

    web3.eth.getTransactionCount(address).then(function(nonce){
        var amount = "1000000";
        contract.methods.mintAirdropToken(amount).estimateGas().then(function(gas){
            var rawTransaction = {
                "nonce": web3.utils.toHex(nonce),
                "from": address,
                "to": contractAddress,
                "gas": web3.utils.toHex(gas),
                "gasPrice": web3.utils.toHex(price),
                // "gasLimit": this.web3.utils.toHex(gasLimit.gasLimit),
                "value": "0x0",
                "data": contract.methods.mintAirdropToken(amount).encodeABI()
            };

            console.log(rawTransaction);
            
            var privateKey = new Buffer.from(key, 'hex');
            var tx = new Tx(rawTransaction);
            tx.sign(privateKey);
            var serializedTx = tx.serialize();

            web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')).on('receipt', function(txhash){
                console.log(txhash);
            }); 
        });
    });
});

web3.eth.getGasPrice().then(function(gasPrice){
    var price = Number(gasPrice);

    web3.eth.getTransactionCount(address).then(function(nonce){
        var amount = "10";
        contract.methods.setAirdropAmount(amount).estimateGas().then(function(gas){
            var rawTransaction = {
                "nonce": web3.utils.toHex(nonce),
                "from": address,
                "to": contractAddress,
                "gas": web3.utils.toHex(gas),
                "gasPrice": web3.utils.toHex(price),
                "value": "0x0",
                "data": contract.methods.setAirdropAmount(amount).encodeABI()
            };

            console.log(rawTransaction);
            
            var privateKey = new Buffer.from(key, 'hex');
            var tx = new Tx(rawTransaction);
            tx.sign(privateKey);
            var serializedTx = tx.serialize();

            web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')).on('receipt', function(txhash){
                console.log(txhash);
            }); 
        });
    });
});

web3.eth.getGasPrice().then(function(gasPrice){
    var price = Number(gasPrice);

    web3.eth.getTransactionCount(address).then(function(nonce){
        var status = true;
        contract.methods.setAirdropStatus(status).estimateGas().then(function(gas){
            var rawTransaction = {
                "nonce": web3.utils.toHex(nonce),
                "from": address,
                "to": contractAddress,
                "gas": web3.utils.toHex(gas),
                "gasPrice": web3.utils.toHex(price),
                "value": "0x0",
                "data": contract.methods.setAirdropStatus(status).encodeABI()
            };
            console.log(rawTransaction);
            
            var privateKey = new Buffer.from(key, 'hex');
            var tx = new Tx(rawTransaction);
            tx.sign(privateKey);
            var serializedTx = tx.serialize();

            web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')).on('receipt', function(txhash){
                console.log(txhash);
            }); 
        });
    });
});