web3.js简介与入门

这篇具有很好参考价值的文章主要介绍了web3.js简介与入门。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

区块链,当前无论是在国内还是国外都是一个比较时髦的概念,在国内由于政策及市场成熟度的原因,技术氛围还没有那么浓厚。可是在国外,区块链的学习及使用正在如火如荼进行着。

想让自己与国际接轨,或者想了解一下区块链吗,如果你是前端开发人员或者熟悉Javascript,来这里看一下web3的系列文章吧,你可以通过本文的一系列教程快速掌握相应的技术与概念。

Web3.js是ETH提供给开发人员将其APP运行在ETH上的javascript类库。在底层上,它通过RPC地用与本地节点进行通信。当然,web3.js可以与任意暴露了RPC接口的ETH节点进行连接,实现二次开发。

本系列文章默认读者熟悉javascript语言,了解NODEJS。对对象及后端服务有一定认识。

废话到这,现在开始。

首先我们需要将web3.js引入到我们的项目中

首先安装必要的组件:

npm install -save web3@4.0.3
npm install -save @ethereumjs/common@3.2.0
npm install -save eth-web3-tx

下面是一些常用的方法调用 包括对eth 代币 以及交易的相关操作:文章来源地址https://www.toymoban.com/news/detail-799212.html

const {Web3} = require('web3')
const {Common, Chain, Hardfork} = require("@ethereumjs/common");
const LegacyTransaction = require('eth-web3-tx').LegacyTransaction;
const rpcURL = 'https://eth-mainnet.public.blastapi.io' // RPC URL  如果地址不能使用了 请去 https://infura.io 注册账号获取免费的
const your_private_key =  Buffer.from('bef5467f1ee820f0d879c191aeb0df1cf41c1fb05565ea0143de274ee94a5aa3', 'hex');
const your_wallet_address = '0x3444e807aB03C9D27c23E7E8f147a9878272490B'
const usdt_address = "0xdAC17F958D2ee523a2206206994597C13D831ec7"
const wbtc_address = "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599"
const web3 = new Web3(rpcURL);
const uniswap_router3_address = '0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45'
const erc20_abi = [{"constant":false,"inputs":[{"name":"_evilUser","type":"address"}],"name":"addBlackList","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_upgradedAddress","type":"address"}],"name":"deprecate","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_blackListedUser","type":"address"}],"name":"destroyBlackFunds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"amount","type":"uint256"}],"name":"issue","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"pause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"amount","type":"uint256"}],"name":"redeem","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_clearedUser","type":"address"}],"name":"removeBlackList","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"newBasisPoints","type":"uint256"},{"name":"newMaxFee","type":"uint256"}],"name":"setParams","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":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"unpause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"_initialSupply","type":"uint256"},{"name":"_name","type":"string"},{"name":"_symbol","type":"string"},{"name":"_decimals","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"amount","type":"uint256"}],"name":"Issue","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"amount","type":"uint256"}],"name":"Redeem","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"newAddress","type":"address"}],"name":"Deprecate","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"feeBasisPoints","type":"uint256"},{"indexed":false,"name":"maxFee","type":"uint256"}],"name":"Params","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_blackListedUser","type":"address"},{"indexed":false,"name":"_balance","type":"uint256"}],"name":"DestroyedBlackFunds","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_user","type":"address"}],"name":"AddedBlackList","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_user","type":"address"}],"name":"RemovedBlackList","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":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[],"name":"Pause","type":"event"},{"anonymous":false,"inputs":[],"name":"Unpause","type":"event"},{"constant":true,"inputs":[],"name":"_totalSupply","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":"","type":"address"}],"name":"allowed","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"who","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balances","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"basisPointsRate","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"deprecated","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_maker","type":"address"}],"name":"getBlackListStatus","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"isBlackListed","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"MAX_UINT","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"maximumFee","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"paused","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"upgradedAddress","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"}]
const uniswap_router3_abi = [{"inputs":[{"internalType":"address","name":"_factoryV2","type":"address"},{"internalType":"address","name":"factoryV3","type":"address"},{"internalType":"address","name":"_positionManager","type":"address"},{"internalType":"address","name":"_WETH9","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"WETH9","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"approveMax","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"approveMaxMinusOne","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"approveZeroThenMax","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"approveZeroThenMaxMinusOne","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"callPositionManager","outputs":[{"internalType":"bytes","name":"result","type":"bytes"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"paths","type":"bytes[]"},{"internalType":"uint128[]","name":"amounts","type":"uint128[]"},{"internalType":"uint24","name":"maximumTickDivergence","type":"uint24"},{"internalType":"uint32","name":"secondsAgo","type":"uint32"}],"name":"checkOracleSlippage","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"path","type":"bytes"},{"internalType":"uint24","name":"maximumTickDivergence","type":"uint24"},{"internalType":"uint32","name":"secondsAgo","type":"uint32"}],"name":"checkOracleSlippage","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"bytes","name":"path","type":"bytes"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMinimum","type":"uint256"}],"internalType":"struct IV3SwapRouter.ExactInputParams","name":"params","type":"tuple"}],"name":"exactInput","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"tokenIn","type":"address"},{"internalType":"address","name":"tokenOut","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMinimum","type":"uint256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"}],"internalType":"struct IV3SwapRouter.ExactInputSingleParams","name":"params","type":"tuple"}],"name":"exactInputSingle","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"bytes","name":"path","type":"bytes"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"amountInMaximum","type":"uint256"}],"internalType":"struct IV3SwapRouter.ExactOutputParams","name":"params","type":"tuple"}],"name":"exactOutput","outputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"tokenIn","type":"address"},{"internalType":"address","name":"tokenOut","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"amountInMaximum","type":"uint256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"}],"internalType":"struct IV3SwapRouter.ExactOutputSingleParams","name":"params","type":"tuple"}],"name":"exactOutputSingle","outputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"factoryV2","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"getApprovalType","outputs":[{"internalType":"enum IApproveAndCall.ApprovalType","name":"","type":"uint8"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"token0","type":"address"},{"internalType":"address","name":"token1","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"amount0Min","type":"uint256"},{"internalType":"uint256","name":"amount1Min","type":"uint256"}],"internalType":"struct IApproveAndCall.IncreaseLiquidityParams","name":"params","type":"tuple"}],"name":"increaseLiquidity","outputs":[{"internalType":"bytes","name":"result","type":"bytes"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"token0","type":"address"},{"internalType":"address","name":"token1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint256","name":"amount0Min","type":"uint256"},{"internalType":"uint256","name":"amount1Min","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"internalType":"struct IApproveAndCall.MintParams","name":"params","type":"tuple"}],"name":"mint","outputs":[{"internalType":"bytes","name":"result","type":"bytes"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"previousBlockhash","type":"bytes32"},{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"","type":"bytes[]"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"","type":"bytes[]"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"results","type":"bytes[]"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"positionManager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"pull","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"refundETH","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermit","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermitAllowed","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermitAllowedIfNecessary","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"selfPermitIfNecessary","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"}],"name":"swapExactTokensForTokens","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"amountInMax","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"}],"name":"swapTokensForExactTokens","outputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"sweepToken","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amountMinimum","type":"uint256"}],"name":"sweepToken","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"uint256","name":"feeBips","type":"uint256"},{"internalType":"address","name":"feeRecipient","type":"address"}],"name":"sweepTokenWithFee","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"feeBips","type":"uint256"},{"internalType":"address","name":"feeRecipient","type":"address"}],"name":"sweepTokenWithFee","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"int256","name":"amount0Delta","type":"int256"},{"internalType":"int256","name":"amount1Delta","type":"int256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"uniswapV3SwapCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"unwrapWETH9","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountMinimum","type":"uint256"}],"name":"unwrapWETH9","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"feeBips","type":"uint256"},{"internalType":"address","name":"feeRecipient","type":"address"}],"name":"unwrapWETH9WithFee","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"uint256","name":"feeBips","type":"uint256"},{"internalType":"address","name":"feeRecipient","type":"address"}],"name":"unwrapWETH9WithFee","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"name":"wrapETH","outputs":[],"stateMutability":"payable","type":"function"},{"stateMutability":"payable","type":"receive"}]

function uint8ToHex(uint8arr) {
    let hexStr = "";
    for (let i = 0; i < uint8arr.length; i++) {
        let hex = uint8arr[i].toString(16);
        hex = hex.length === 1 ? "0" + hex : hex; // 需要补0
        hexStr += hex;
    }
    return hexStr;
}

function contract_call(txObject,call_back=null){
    if (call_back == null){
        call_back = function (txHash){
            console.log('txHash:', txHash)
        }
    }

    web3.eth.getTransactionCount(your_wallet_address).then((txCount) => {
        web3.eth.estimateGas(txObject).then((gaslimit)=>{
            txObject['nonce'] = web3.utils.toHex(txCount)
            txObject['gasLimit'] = web3.utils.toHex(gaslimit)
            txObject['gasPrice'] = web3.utils.toHex(web3.utils.toNumber(web3.utils.toWei('10', 'gwei')))
            const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.Istanbul })
            const tx = LegacyTransaction.fromTxData(txObject, { common })
            signedTx = tx.sign(your_private_key)
            const serializedTx = signedTx.serialize()
            const tes = serializedTx.valueOf()
            const raw = '0x' + uint8ToHex(tes)
            web3.eth.sendSignedTransaction(raw).then(call_back)
        });
    })
}

/*
    获取指定账户的eth余额
    your_wallet_address: 指定账户地址

    :return:账户余额
*/
function getEthBalance(your_wallet_address){
    web3.eth.getBalance(your_wallet_address).then(( wei) => {
            // 余额单位从wei转换为ether
            balance = web3.utils.fromWei(wei, 'ether')
            console.log("balance: " + balance)
        }
    )
}

/*
    获取指定账户的erc20代币余额
    erc20_address:erc20合约地址
    owner_address: 指定账户地址

    :return:账户erc20代币余额
*/
function getErc20Balance(erc20_address, owner_address){
    var MyContract = new web3.eth.Contract(erc20_abi, erc20_address);
    MyContract.methods.balanceOf(owner_address).call()
        .then((erc20_qty)=>{
            console.log(erc20_address + "   balance: " + erc20_qty)
        });
}
/*
    获取ERC20代币的授权量
    erc20_address:代币合约地址
    owner_address:授权主体
    contract_address: 被授权方地址

 */
function getErc20Allowance(erc20_address, owner_address,contract_address){
    var MyContract = new web3.eth.Contract(erc20_abi, erc20_address);
    MyContract.methods.allowance(owner_address,contract_address).call()
        .then((allowance)=>{
            console.log(erc20_address + "\n"+owner_address+"\n"+contract_address+"\n   allowance: " + allowance)
        });
}

/*
    """
    发送指定数量的eth给指定地址
    to_address:接收方地址
    amount:发送eth数量

    """
 */
function transferEth(toAddress,amount){
    const txObject = {
        to:       toAddress,
        value:    web3.utils.toHex(web3.utils.toNumber(web3.utils.toWei(amount, 'ether'))),
    }
    contract_call(txObject)
}

/*
    发送erc20代币给指定地址指定数量
    erc20_address:erc20代币合约地址
    to_address:接收方地址
    amount:发送erc20代币数量

 */
function transferErc20(erc20Address,toAddress,amount){
    const contract = new web3.eth.Contract(erc20_abi, erc20Address)
    const txObject = {
        to:       erc20Address,
        data: contract.methods.transfer(toAddress,amount).encodeABI()
    }
    contract_call(txObject)
}

/*
    授权给指定地址指定数量的消费额度
    erc20_address: erc20代币地址
    approve_contract_address:指定的其他消费代币的合约地址
    approve_amount:授权数量
 */
function approve(erc20Address, approveContractAddress, approveAmount,call_back=null){
    const contract = new web3.eth.Contract(erc20_abi, erc20Address)
    const txObject = {
        to:       erc20Address,
        data: contract.methods.approve(approveContractAddress,approveAmount).encodeABI()
    }
    contract_call(txObject,call_back)
}


/*
    发起dex交易,通过uniswapV3 dex进行交易
    :param input_address: 输入的erc20 代币地址
    :param out_address:  输出的erc20 代币地址
    :param input_amount: 输入数量
 */
function UniswapV3Swap(input_address, out_address, input_amount){
    var fee = 3000  // uniswap 池子手续费一般三个等级 分别为 500,3000,10000
    var input_contract = new web3.eth.Contract(erc20_abi, input_address)
    var uniswap_router3_contract = new web3.eth.Contract(uniswap_router3_abi, uniswap_router3_address)
    input_contract.methods.allowance(your_wallet_address,uniswap_router3_address).call()
        .then((allowance)=>{
            const swap_function =function (){
                parms = {
                    'tokenIn': input_address,
                    'tokenOut': out_address,
                    'fee': fee,
                    'recipient': your_wallet_address,
                    'amountIn': input_amount,
                    'amountOutMinimum': 0,
                    'sqrtPriceLimitX96': 0,
                }
                const txObject = {
                    to:       uniswap_router3_address,
                    data: uniswap_router3_contract.methods.exactInputSingle(parms).encodeABI(),
                    from:your_wallet_address
                }
                contract_call(txObject)
            }
            if(allowance == 0) {
                approve(input_address,uniswap_router3_address,input_amount,swap_function)
            }else if (allowance < input_amount){
                approve(input_address,uniswap_router3_address,0,function (txHash){
                    approve(input_address,uniswap_router3_address,input_amount,swap_function)
                })
            }else{
                swap_function()
            }
        });
}

//获取your_wallet_address 地址拥有的USDT余额
getErc20Balance(usdt_address,your_wallet_address)
//获取your_wallet_address 给0x50431c70f6B4B9ab5CA438Cb9a3f030C4Bad5707 授权量多少usdt消费额度
getErc20Allowance(usdt_address,your_wallet_address,"0x50431c70f6B4B9ab5CA438Cb9a3f030C4Bad5707")
//获取your_wallet_address 的ETH余额
getEthBalance(your_wallet_address)

//以下方法需要同步执行,也可以注释一下其他方法,只执行一个,因为异步一起执行会导致nonce计算错误
//给 0x50431c70f6B4B9ab5CA438Cb9a3f030C4Bad5707 转账一个ETH
transferEth("0x50431c70f6B4B9ab5CA438Cb9a3f030C4Bad5707","1")
//给 0x50431c70f6B4B9ab5CA438Cb9a3f030C4Bad5707 转账 10000 usdt
transferErc20(usdt_address,"0x50431c70f6B4B9ab5CA438Cb9a3f030C4Bad5707","10000")
//授权 给 uniswap_router3_address 10 usdt 的消费额度
approve(usdt_address,uniswap_router3_address,10)
//花 100000000 usdt 买入 BTC
UniswapV3Swap(usdt_address,wbtc_address,100000000)

到了这里,关于web3.js简介与入门的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SCF金融公链推出WEB3社交平台FinBox,赢得市场青睐

    随着区块链技术的飞速发展,以及加密货币市场的日益火热,世界正式宣告走向Web3.0时代。而过去几年,区块链和加密货币行业经历了爆炸式增长。DeFi(去中心化金融)和NFT(非同质化代币)市场的崛起引领了加密世界的变革,带动数字产业的发展。在这样的大环境下,许多

    2024年02月06日
    浏览(78)
  • Web3.0介绍与产业赛道(去中心化,金融与数字资产,应用与存储,区块链技术)

    1、web3.0时代——区块链技术 Web3.0是什么 Web3.0是指下一代互联网技术,它将在现有的Web2.0技术基础上, 进一步深化人与人、人与物、物与物之间的连接和交互 ,实现更高效、更安全、更去中心化、更开放的互联网生态。 Web3.0是由区块链技术和去中心化应用(DApp)所驱动的,

    2024年02月03日
    浏览(52)
  • 华为云智能化组装式交付方案 ——金融级PaaS业务洞察及Web3实践的卓越贡献

    伴随信息技术与金融业务加速的融合,企业应用服务平台(PaaS)已从幕后走向台前,成为推动行业数字化转型的关键力量。此背景下,华为云PaaS智能化组装式交付方案闪耀全场,在近日结束的华为全联接大会 2023上倍受关注。 图 1华为全联接大会 2023华为云展区显示屏 华为

    2024年02月07日
    浏览(55)
  • 【Web3】Web3Js高频Api

    目录 Web3Js方法 初始化Web3实例 Web3Api 创建账号Api 获取余额Api 单位转换工具函数 Web3Js方法 web3.eth:用于与以太坊区块链和智能合约之间的交互。 web3.utils:包含一些辅助方法。 web3.shh:用于协议进行通信的P2P和广播。 web3.bzz:用于与群网络交互的Bzz模块。 初始化Web3实例 npm

    2024年02月13日
    浏览(41)
  • Web3技术简介:重新定义互联网的未来

    在21世纪的数字时代,互联网已成为我们日常生活的不可或缺的一部分。然而,随着区块链和加密技术的快速发展,一个全新的互联网模型——Web3,正逐渐崭露头角。Web3不仅仅是技术的进步,它更是对传统互联网模型的挑战和革新,旨在构建一个更去中心化、安全、透明和用

    2024年04月27日
    浏览(40)
  • 【Web3】 Web3JS Pay Api

    Web3Network.eth.sendSignedTransaction(serializedTx) 参数: from - String|Number :发送帐户的地址。如果未指定,则使用web3.eth.defaultAccount属性。或web3.eth.accounts.wallet中本地的地址。 to - String :(可选)消息的目标地址,若未定义则为发送消息。 value - Number|String|BN|BigNumber :(可选)为wei中的交易

    2024年02月16日
    浏览(37)
  • web3.js 基础

    web3.js是一个库集合,允许您使用HTTP、IPC或WebSocket与本地或远程以太坊节点交互。 github readthedocs npm npm install web3 yarn yarn add web3 In the Browser 使用预构建的dist/web3.min.js,或者使用web3.js库进行构建: 然后在你的html文件中包含dist/web3.min.js。这将在window 对象上公开 Web3 。 jsDelivr CD

    2024年02月09日
    浏览(30)
  • web3.js获取导入

    我们访问 https://github.com/ 我们搜索 web3.js 然后我们直接点击第一个进去 进入之后 往下拉 你会看到 它支持node项目的两种引入方式 这里 大家可以直接下载我的资源 https://download.csdn.net/download/weixin_45966674/87878737 下载好解压出来就会有一个 web3.min.js 我们将下载下来的js文件放在

    2024年02月08日
    浏览(30)
  • 使用 React、Web3.js 和 Metamask 构建 Web3 dApp 身份验证

    我相信您和我一样对 Web3 充满热情。本文介绍了一种新的区块链开发登录方法:使用 MetaMask 扩展的一键式加密安全登录流程,所有数据都存储在我们自己的后端。它还可以保护我们的数据和加密货币的安全。 在这里,我们将构建一个允许用户使用 MetaMask 登录的身份验证解决

    2024年02月04日
    浏览(63)
  • web3.js 查看钱包金额

    ajax与web服务器交互,传递数据; 等同于 web3.js 向以太坊网络某一节点交互; 见下图来自link. 所以接下来的问题是: JSON RPC(JSON远程调用)作为程序和EVM client的web3 interface,是如何作用的?? 类似jQuery ajax库来读写web服务器上的数据??这又是什么? 注册infura,创建新proj

    2024年02月16日
    浏览(40)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包