| import requests | |
| from web3 import Web3 | |
| from typing import Dict, Any | |
| class TokenApprovalHelper: | |
| def __init__(self, web3: Web3, private_key: str): | |
| self.web3 = web3 | |
| self.private_key = private_key | |
| def approve_token(self, erc20_contract_address: str, exchange_proxy_address: str, sell_amount: str, eth_address: str) -> Dict[str, Any]: | |
| """ | |
| Approves the 0x Exchange Proxy contract to spend the specified amount of the ERC-20 token. | |
| Args: | |
| erc20_contract_address (str): The address of the ERC-20 token contract. | |
| exchange_proxy_address (str): The address of the 0x Exchange Proxy contract. | |
| sell_amount (str): The amount of the token to approve. | |
| eth_address (str): Your Ethereum address. | |
| Returns: | |
| dict: The transaction receipt of the approval transaction. | |
| Example: | |
| >>> approve_token('0xTokenAddress', '0xProxyAddress', '1000000000000000000', '0xYourAddress') | |
| """ | |
| erc20_abi = [ | |
| { | |
| "constant": False, | |
| "inputs": [ | |
| { | |
| "name": "_spender", | |
| "type": "address" | |
| }, | |
| { | |
| "name": "_value", | |
| "type": "uint256" | |
| } | |
| ], | |
| "name": "approve", | |
| "outputs": [ | |
| { | |
| "name": "", | |
| "type": "bool" | |
| } | |
| ], | |
| "type": "function" | |
| } | |
| ] | |
| erc20_contract = self.web3.eth.contract(address=erc20_contract_address, abi=erc20_abi) | |
| approve_tx = erc20_contract.functions.approve( | |
| exchange_proxy_address, | |
| int(sell_amount) | |
| ).buildTransaction({ | |
| 'from': eth_address, | |
| 'nonce': self.web3.eth.getTransactionCount(eth_address), | |
| 'gas': 100000, | |
| 'gasPrice': self.web3.toWei('20', 'gwei') | |
| }) | |
| signed_approve_tx = self.web3.eth.account.signTransaction(approve_tx, private_key=self.private_key) | |
| tx_hash = self.web3.eth.sendRawTransaction(signed_approve_tx.rawTransaction) | |
| return self.web3.eth.waitForTransactionReceipt(tx_hash) | |