File size: 2,309 Bytes
cbb819c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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)