Etherscan

由於 TRANSFER_FROM_FAILED 交換令牌失敗

  • April 20, 2022

我正在嘗試在 rinkeby 測試網路上測試程式碼,並且我正在嘗試使用 WETH 代幣購買 DAI 代幣。我的賬戶上有水(0.5),我的賬戶上也有 ETH(0.1)。總結一下。我收到一條錯誤消息,提示 TRANSFER_FROM_FAILED。在網上看了很多問題和答案後,這是我得到的程式碼。我嘗試過但沒有出現在程式碼中的東西是:

  1. 使用 swapExactETHForTokensSupportingFeeOnTransferTokens 而不是 swapExactTokensForTokens,沒有用
  2. 批准對地址以及路由器(程式碼僅顯示批准路由器地址)

知道為什麼這個交換失敗了嗎?這是失敗交易的範例和程式碼: https ://rinkeby.etherscan.io/tx/0x402fabb51​​e0bfc1eedf7fcecffa3cc8c134dd8fe80544ccee619fe7dc05a06af

# Enums
class Tokens(Enum):
   WBNB = 1
   BUSD = 2

pancakeSwapRouterContractAddress = '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D' # router has swap method
pancakeSwapFactoryContractAddress = '0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f'
pancakeSwapFactoryABIFile = open('pancakeSwapFactoryABI.json')
pancakeSwapRouterABIFile = open('pancakeSwapRouterABI.json')
IERC20ABIFile = open('ERC20ABI.json')
pancakeSwapFactoryABI = json.loads(pancakeSwapFactoryABIFile.read())
pancakeSwapRouterABI = json.loads(pancakeSwapRouterABIFile.read())
IERC20Abi = json.loads(IERC20ABIFile.read())

# add your blockchain connection information
InfuraUrl = 'https://rinkeby.infura.io/v3/<my-infura-api-key>'
web3 = Web3(Web3.HTTPProvider(InfuraUrl))
web3.middleware_onion.inject(geth_poa_middleware, layer=0)

# set personal account information
privateKeyFilePath = "../key/privateKey.txt" 
privateKeyFile = open(privateKeyFilePath)
privateKey = privateKeyFile.read() # private key will hold my account private key.

# Global Parameters
toeknNameToCheckSumAddressMapping = {
   Tokens.WBNB: "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",
   Tokens.BUSD: "0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56"
   }
routerContract = web3.eth.contract(address=pancakeSwapRouterContractAddress, abi=pancakeSwapRouterABI)
factoryContract = web3.eth.contract(address=pancakeSwapFactoryContractAddress, abi=pancakeSwapFactoryABI)
ethContract = web3.eth.contract(address='0xc778417E063141139Fce010982780140Aa0cD5Ab', abi=IERC20Abi)
transactionCounts = 0
whenToFlushTransaction = 3
minValOfTransaction = 1000
currentDateFile = datetime.utcnow().date
slippage = 0.15

if __name__ == "__main__":
   try:
       newTokenAddress = Web3.toChecksumAddress('0xc7AD46e0b8a400Bb3C915120d284AafbA8fc4735') #dai address
       mainTokenAddress = Web3.toChecksumAddress('0xc778417E063141139Fce010982780140Aa0cD5Ab') # weth address
       myAccount = '0x8C64EAA77707cAc8018f34991d3F51E4F810Eb7D'
       AmountInEth = 0.05

       pairAddress = factoryContract.functions.getPair(newTokenAddress, mainTokenAddress).call()

       #get the nonce.  Prevents one from sending the transaction twice
       nonce = web3.eth.getTransactionCount(myAccount)
       deadline = int(time.time()) + 600 # 10 min ahead deadline
       path = [mainTokenAddress, newTokenAddress]
       amountIn = web3.toWei(AmountInEth, 'Ether')
       print(amountIn)
       amounts = routerContract.functions.getAmountsOut(amountIn, path).call()
       isApproved = ethContract.functions.approve(pancakeSwapRouterContractAddress, amountIn).call({'from': myAccount})
       print(f'approved returned: {isApproved}')
       amountOut = int(amounts[1] - (amounts[1] * slippage))
       transaction = routerContract.functions.swapExactTokensForTokens(amountIn, amountOut, path, myAccount, deadline).buildTransaction({
                   'from': myAccount,
                   'gas': 250000,
                   'gasPrice': web3.toWei("5", 'gwei'),
                   'nonce': nonce,
               })
       signedTransaction = web3.eth.account.sign_transaction(transaction, privateKey)
       tx_token = web3.eth.send_raw_transaction(signedTransaction.rawTransaction)
       print(f'tx token = {tx_token.hex()}')
   except Exception as ex:
       print(f"an exception of type {type(ex).__name__} occurred. Arguments:\n{ex.args}")

嘗試批准您使用的路由器時.call(..)

isApproved = ethContract.functions.approve(
   pancakeSwapRouterContractAddress, 
   amountIn).call({'from': myAccount})

呼叫在記憶體中執行,任何更改在返回後立即丟棄,因此路由器不被批准從 myAccount 傳輸令牌。

要使其正常工作,您必須使用或.transact(..)呼叫..buildTransaction(..)``swapExactTokensForTokens

引用自:https://ethereum.stackexchange.com/questions/126477