ethers发送交易-nodejs

原生资产,转账、获取余额

var customHttpProvider = new ethers.providers.JsonRpcProvider('https://bsc-dataseed.binance.org/');
  var privateKey = "私钥";
  var wallet = new ethers.Wallet(privateKey, customHttpProvider);
  const balance = await wallet.getBalance()
  console.log(balance)
  
  let tx = await wallet.sendTransaction({
    
    
        gasLimit: gasLimit,
        gasPrice: gasPrice,
        to: newAddress,
        value: value
    });

发送token

function send_token(
  contract_address,
  send_token_amount,
  to_address,
  send_account,
  private_key
) {
    
    
  let wallet = new ethers.Wallet(private_key)
  let walletSigner = wallet.connect(window.ethersProvider)

  window.ethersProvider.getGasPrice().then((currentGasPrice) => {
    
    
    let gas_price = ethers.utils.hexlify(parseInt(currentGasPrice))
    console.log(`gas_price: ${
      
      gas_price}`)

    if (contract_address) {
    
    
      // general token send
      let contract = new ethers.Contract(
        contract_address,
        send_abi,
        walletSigner
      )

      // How many tokens?
      let numberOfTokens = ethers.utils.parseUnits(send_token_amount, 18)
      console.log(`numberOfTokens: ${
      
      numberOfTokens}`)

      // Send tokens
      contract.transfer(to_address, numberOfTokens).then((transferResult) => {
    
    
        console.dir(transferResult)
        alert("sent token")
      })
    } // ether send
    else {
    
    
      const tx = {
    
    
        from: send_account,
        to: to_address,
        value: ethers.utils.parseEther(send_token_amount),
        nonce: window.ethersProvider.getTransactionCount(
          send_account,
          "latest"
        ),
        gasLimit: ethers.utils.hexlify(gas_limit), // 100000
        gasPrice: gas_price,
      }
      console.dir(tx)
      try {
    
    
        walletSigner.sendTransaction(tx).then((transaction) => {
    
    
          console.dir(transaction)
          alert("Send finished!")
        })
      } catch (error) {
    
    
        alert("failed to send!!")
      }
    }
  })
}

发送合约交易

const customHttpProvider = new ethers.providers.JsonRpcProvider('https://bsc-dataseed.binance.org/');

 const walletSigner = new ethers.Wallet(私钥, customHttpProvider);
  const gasPrice = await customHttpProvider.getGasPrice()
  let contract = new ethers.Contract(
    address,
    abi,
    walletSigner
  )
  
    const tx = await contract[方法](
	参数...
    {
    
    
      gasPrice,
      gasLimit: 300000,
      value: ethers.utils.parseEther(String(buyValue))
    })
	// 交易信息
	const transData = await tx.wait()
	

猜你喜欢

转载自blog.csdn.net/weixin_43840202/article/details/123368717