首页 > 编程语言 >php web3转账交易查询常用操作教程

php web3转账交易查询常用操作教程

时间:2024-01-02 19:33:03浏览次数:34  
标签:教程 transaction err contract web3 amount address php erc20

php也可以调用web3相关接口进行转账交易,唯一需要注册的就是 infura ,获得一个密钥,然后就可以调用了,首先:

composer require web3p/[email protected]
composer require blockchainethdev/ethereum-tx

下面示例在php 7.3.33版本运行正常测试通过,其他版本请自行测试是否能用。

下面是一些简单的示例:

<?php
require('vendor/autoload.php');
use Web3\Web3;
use Web3\Contract;
use Web3\Providers\HttpProvider;
use Web3\RequestManagers\HttpRequestManager;
use Blockchainethdev\EthereumTx\Transaction;
define('your_private_key','96991d589fe5fbb2decd399c01d8912d05e1b82ab037472ec46a5f61840dfb91');
define('your_wallet_address','0x9411B02906FE57C8E7f8597F888AA358aDC7a410');
/*
 * Ethereum Mainnet : 1
 * BNB Smart Chain Mainnet : 56
 * Arbitrum One : 42161
 * Polygon Mainnet : 137
 * OP Mainnet : 10
 *
 */
define('chainId',1);
//在https://infura.io注册获得免费的rpc地址
$Web3 = new Web3(new HttpProvider(new HttpRequestManager("https://mainnet.infura.io/v3/{密钥}")));
define('usdt_address','0xdAC17F958D2ee523a2206206994597C13D831ec7');
define('wbtc_address','0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599');
define('uniswap_router3_address','0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45');
define('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"}]');
define('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"}]');
$Eth = $Web3->getEth();
function get_eth_balance($owner_address){
    /*
    获取指定账户的eth余额
    owner_address: 指定账户地址

    :return:账户余额
    */
    global $Eth;
    $Eth->getBalance($owner_address, function ($err, $balance) {
        if ($err !== null) {
        }
        echo 'Balance: ' . $balance->toString() . PHP_EOL;
    });
}
function get_erc20_balance($erc20_address, $owner_address){
    /*
    获取指定账户的erc20代币余额
    erc20_address:erc20合约地址
    owner_address: 指定账户地址

    :return:账户erc20代币余额
    */
    global $Web3;
    $contract = new Contract($Web3->getProvider(), erc20_abi);
    $contract->at($erc20_address)->call("balanceOf", $owner_address, function ($err, $balance) {
        if ($err !== null) {
        }
        echo 'Balance: ' . $balance[0]->toString() . PHP_EOL;
    });
}
function transfer_eth($to_address, $amount){
    /*
    发送指定数量的eth给指定地址
    to_address:接收方地址
    amount:发送eth数量
    */
    global $Eth;
    $Eth->getTransactionCount(your_wallet_address, function ($err, $transactionCount)use($to_address,$Eth,$amount) {
        if ($err !== null) {
            return print_r($err);
        }
        $Eth->gasPrice(function ($err, $gasPrice)use($transactionCount,$to_address,$Eth,$amount) {
            if ($err !== null) {
                return print_r($err);
            }
            $nonce = $transactionCount->toString();
            $transaction = new Transaction([
                'nonce' => intval($nonce),
                'from' => your_wallet_address,
                'to' => $to_address,
                'gas' => 21000,
                'gasPrice' => intval($gasPrice->toString()),
                'value' => $amount,
                'chainId' => chainId, // optional
            ]);
            $sign_data = $transaction->sign(your_private_key);
            $Eth->sendRawTransaction("0x".$sign_data, function ($err, $transaction) {
                print_r([$err,$transaction]);
                if ($err !== null) {
                    print_r($err);
                }
                echo 'tx id: ' . $transaction . PHP_EOL;
            });
        });

    });
}
function contract_call($from_address,$contract_address,$callData){
    global $Eth;
    $transaction_dict =[
        'from' => $from_address,
        'to' => $contract_address,
        'data' => $callData
    ];
    $Eth->getTransactionCount(your_wallet_address, function ($err, $transactionCount)use($contract_address,$callData,$Eth,$transaction_dict) {
        if ($err !== null) {
            //print_r($err);
        }
        $nonce = $transactionCount->toString();
        $transaction_dict['nonce'] = intval($nonce);
        $Eth->gasPrice(function ($err, $gasPrice)use($nonce,$contract_address,$callData,$Eth,$transaction_dict) {
            $Eth->estimateGas($transaction_dict, function ($err, $gas)use($gasPrice,$Eth,$transaction_dict) {
                if ($err !== null) {
                    //print_r($err);
                    exit(1);
                }
                $transaction_dict['gasPrice'] =intval($gasPrice->toString());
                $transaction_dict["gas"] = intval($gas->toString());
                $transaction_dict["chainId"] = chainId;
                $transaction = new Transaction($transaction_dict);
                $sign_data = $transaction->sign(your_private_key);
                $Eth->sendRawTransaction("0x".$sign_data, function ($err, $transaction) {
                    if ($err !== null) {
                        //print_r($err);
                        exit(1);
                    }
                    echo 'tx id: ' . $transaction . PHP_EOL;
                });
            });
        });
    });
}
function transfer_erc20($erc20_address, $to_address, $amount){
    /*
    发送erc20代币给指定地址指定数量
    erc20_address:erc20代币合约地址
    to_address:接收方地址
    amount:发送erc20代币数量
     */
    global $Web3;
    $contract = new Contract($Web3->getProvider(), erc20_abi);
    $callData = $contract->getData("transfer",$to_address , $amount);
    contract_call(your_wallet_address,$erc20_address,"0x".$callData);
}
function approve($erc20_address, $approve_contract_address, $approve_amount){
    /*
    授权给指定地址指定数量的消费额度
    erc20_address: erc20代币地址
    approve_contract_address:指定的其他消费代币的合约地址
    approve_amount:授权数量
     */
    global $Web3;
    $contract = new Contract($Web3->getProvider(), erc20_abi);
    $callData = $contract->getData("approve",$approve_contract_address , $approve_amount);
    contract_call(your_wallet_address,$erc20_address,"0x".$callData);
}


function swap1InchSwap($from_token_address, $to_token_address, $amount){
    /*
    通过聚合器1inch获取最优交易方案
    from_token_address 花费的token
    to_token_address 获得的token
    amount 花费数量
    :return:
     */
    # slippage 交易滑点 5%
    $slippage = 5;
    # one_inch_key 去 https://portal.1inch.dev/ 注册免费获取
    $one_inch_key = 'Bearer Obx4dtKrfE7SXf9SSJOgd4nA3ANniV6b';
    $chainId = chainId;
    $base_url_1inch = "https://api.1inch.dev/swap/v5.2/$chainId/swap?";
    $swap_params = [
        "src"=> $from_token_address,
        "dst"=> $to_token_address,
        "amount"=> $amount,
        "from"=> your_wallet_address,
        "slippage"=> $slippage,
        "disableEstimate"=>True,
        "allowPartialFill"=>False
    ];
    $headers = [
        'http' => [
            'method' => 'GET',
            'header' => implode("\r\n", [
                'Content-type: application/json', // Replace with your desired content type
                'Authorization: '.$one_inch_key, // Replace with any authorization header if needed
                // Add any other headers as needed
            ]),
        ],
    ];
    $context = stream_context_create($headers);
    $p = [];
    foreach ($swap_params as $key => $value){
        $p[]="$key=$value";
    }
    $base_url_1inch.=implode("&", $p);
    $json = file_get_contents($base_url_1inch, false, $context);
    if($json){
        $json = json_decode($json,true);
        $tx = $json["tx"];
        contract_call(your_wallet_address,$tx['to'],$tx['data']);
    }
}

function bridge_orbiter($from_network, $to_network, $from_coin,$to_coin, $amount){
    /*
         通过orbiter平台进行跨链操作
        from_network 跨出链
        to_network 跨入链
        from_coin 跨出币种
        to_coin 跨入币种
        amount 跨链数量
        :return:
     */
    $network_id_map = [
        "Ethereum"=> 1,
        "Arbitrum"=> 2,
        "zkSyncLite"=> 3,
        "Starknet"=> 4,
        "Polygon"=> 6,
        "Optimism"=> 7,
        "ImmutableX"=> 8,
        "Loopring"=> 9,
        "Metis"=> 10,
        "dydx"=> 11,
        "ZKSpace"=> 12,
        "Boba"=> 13,
        "zkSyncEra"=> 14,
        "BNBChain"=> 15,
        "ArbitrumNova"=> 16,
        "PolygonzkEVM"=> 17,
        "Base"=> 21,
        "Linea"=> 23,
        "Mantle"=>24,
        "opBNB"=> 25,
        "Zora"=> 30,
        "ScrollAlpha"=> 31,
        "Taiko"=> 32,
        "ScrollSepolia"=> 33,
        "Combo"=> 34,
        "Kroma"=> 35,
        "Manta"=> 36
    ];
    #orbiter_config 配置见  https://blog.51cto.com/u_7992628/8315297
    $orbiter_config = '';
    $orbiter_config = json_decode($orbiter_config,true);
    $from_net_id = $network_id_map[$from_network];
    $to_net_id = $network_id_map[$to_network];

    $config = $orbiter_config["$from_net_id-$to_net_id"];
    $config = $config["$from_coin-$to_coin"];
    $send_decimals = 10 ** 13;
    $amount = intval(floor($amount / $send_decimals) * $send_decimals);
    $amount += ($network_id_map[$to_network]+9000);
    transfer_eth($config["sender"], $amount);
}
//# 获取账户ETH余额
get_eth_balance(your_wallet_address);
//# 获取账户usdt余额
get_erc20_balance(usdt_address,your_wallet_address);
//# 发送1个ETH给 0x95341E8d48ebCF212e0Eb8a314244Ba0cdFC85B5
transfer_eth("0x95341E8d48ebCF212e0Eb8a314244Ba0cdFC85B5",1*pow(10,18));
//# 发送1usdt 给 0x50431c70f6B4B9ab5CA438Cb9a3f030C4Bad5707
transfer_erc20(usdt_address,"0x50431c70f6B4B9ab5CA438Cb9a3f030C4Bad5707",1*pow(10,6));
//# 给 0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45 授权 10btc的消费额度
approve(wbtc_address,"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",10*pow(10,8));
//#通过1Inch 卖出 1btc ,获得 usdt
swap1InchSwap(wbtc_address,usdt_address,1*pow(10,8));
//# 从eth主网跨链到ARBITRUM网络 1个eth
bridge_orbiter("Ethereum","Arbitrum","ETH","ETH",1*pow(10,18));

标签:教程,transaction,err,contract,web3,amount,address,php,erc20
From: https://blog.51cto.com/u_7992628/9072371

相关文章

  • 无涯教程-Java 正则 - X*匹配函数
    贪婪匹配[X*]与出现的X匹配零次或多次。X*-示例以下示例显示了贪婪匹配的用法。packagecom.learnfk;importjava.util.regex.Matcher;importjava.util.regex.Pattern;publicclassGreedyQuantifierDemo{privatestaticfinalStringREGEX="T*";private......
  • 无涯教程-Java 正则 - X?匹配函数
    贪婪匹配[X?]匹配一次存在的X或根本不存在的X。X?-示例以下示例显示了贪婪匹配的用法。packagecom.learnfk;importjava.util.regex.Matcher;importjava.util.regex.Pattern;publicclassGreedyQuantifierDemo{privatestaticfinalStringREGEX="T?";p......
  • ig自动回复最全教程来了!多个方式教你设置
    自动回复是一种常见的功能,在收到消息或请求时,系统可以自动发送用户预设的回复消息。当用户无法及时回复时,这个功能就能发挥最大的用处。自动回复基本上已经应用于各种社媒渠道,无论是个人和商务领域,都可以提供更好的沟通和客户服务体验。Instagram(简称ig)作为海外最受欢迎的社媒之一,......
  • 无涯教程-Java 正则 - \Z匹配函数
    边界匹配器[\Z]匹配输入的末尾,但匹配最终终止符(如果有)。Z-示例以下示例显示了边界匹配器的用法。packagecom.learnfk;importjava.util.regex.Matcher;importjava.util.regex.Pattern;publicclassBoundaryMatcherDemo{privatestaticfinalStringREGEX......
  • 无涯教程-Java 正则 - \A匹配函数
    边界匹配器[\A]匹配输入的开头。A-示例以下示例显示了边界匹配器的用法。packagecom.learnfk;importjava.util.regex.Matcher;importjava.util.regex.Pattern;publicclassBoundaryMatcherDemo{privatestaticfinalStringREGEX="\\A";privatestat......
  • 无涯教程-Java 正则 - \B匹配函数
    边界匹配器[\B]匹配非单词边界。B-示例以下示例显示了边界匹配器的用法。packagecom.learnfk;importjava.util.regex.Matcher;importjava.util.regex.Pattern;publicclassBoundaryMatcherDemo{privatestaticfinalStringREGEX="\\B";privatestat......
  • xxl-job实现分片广播任务详细教程
    xxl-job是一个分布式任务调度平台,支持定时任务和分片任务。其中,分片任务可以将一个大任务拆分成多个小任务,分布式地执行,提高任务的执行效率和可靠性。分片任务中,有一种特殊的任务类型叫做分片广播任务,可以将一个任务广播到所有的执行器节点上执行,本质上是一种并行执行的方式。xxl-......
  • 无涯教程-Java 正则 - ^匹配函数
    边界匹配器[^]匹配行的开头。^-示例下面的示例显示边界匹配器的用法。packagecom.learnfk;importjava.util.regex.Matcher;importjava.util.regex.Pattern;publicclassBoundaryMatcherDemo{privatestaticfinalStringREGEX="^";privatestaticfi......
  • 无涯教程-Java 正则 - \P{InGreek}匹配函数
    字符类\P{InGreek}匹配除希腊符号以外的任何字符。P{InGreek}-示例下面的示例显示Unicode字符类匹配的用法。packagecom.learnfk;importjava.util.regex.Matcher;importjava.util.regex.Pattern;publicclassUnicodeCharacterClassDemo{privatestaticfina......
  • Rational rose 安装教程(图文)
    RationalRose是Rational公司出品的一种面向对象的统一建模语言的可视化建模工具。用于可视化建模和公司级水平软件应用的组件构造。就像一个戏剧导演设计一个剧本一样,一个软件设计师使用RationalRose,以演员(数字)、使用拖放式符号的程序表中的有用的案例元素(椭圆)、目标(矩形)和消息/......