Skip to content

Async Wallet

ether.AsyncWallet

AsyncWallet(private_key, network='Ethereum')

Bases: _BaseWallet

Asynchronous version of the Wallet class, providing methods to interact with an Ethereum wallet. This class allows for asynchronous operations, making it suitable for use in asynchronous applications.

This class supports functionalities such as balance retrieval, transaction construction, token approvals, and transfers. It leverages the web3.py library for Ethereum blockchain interactions.

PARAMETER DESCRIPTION
private_key

Account's key required for making (signing) transactions.

TYPE: str

network

The name of the built-inEthereum-based network or custom network configuration

Example

from ether import AsyncWallet, Network

network = Network(
  name='BOB',
  rpc='https://bob.drpc.org',
  token='ETH',
  explorer='https://explorer.gobob.xyz'
)

custom_wallet = AsyncWallet('0xPrivateKey', network)
from ether import AsyncWallet
my_wallet = AsyncWallet('0xPrivateKey', 'Arbitrum')

TYPE: Union[Network, str] DEFAULT: 'Ethereum'

Example
from ether import AsyncWallet

async def main() -> None:
    wallet = AsyncWallet('0xPrivateKey', 'Ethereum')

    # Token details
    token_address = '0xTokenAddressHere'
    token = wallet.get_token(token_address)

    # Recipient and amount
    recipient = '0xRecipientAddressHere'
    amount = 100 * 10 ** token.decimals  # Sending 100 USDT

    # Perform the token transfer
    transaction_hash = await wallet.transfer(token, recipient, amount)

    print(f"Token transfer sent! Hash: {transaction_hash.hex()}")
Source code in ether/async_wallet.py
68
69
70
71
72
73
def __init__(
        self,
        private_key: str,
        network: Union[Network, str] = 'Ethereum',
):
    super().__init__(private_key, network, True)

network property writable

network

Gets the current Network instance.

RETURNS DESCRIPTION
Network

The current network instance.

TYPE: Network

private_key property

private_key

Returns the account's key required for making (signing) transactions.

RETURNS DESCRIPTION
str

Account's key required for making (signing) transactions.

TYPE: str

public_key property

public_key

Returns the account's key used for sharing payment details.

RETURNS DESCRIPTION
ChecksumAddress

The account's key used for sharing payment details.

TYPE: ChecksumAddress

nonce property

nonce

Returns the account's overall number of transactions.

RETURNS DESCRIPTION
int

Account's overall number of transactions.

TYPE: int

native_token property

native_token

Gets the native token of the current network.

RETURNS DESCRIPTION
str

The native token of the current network.

TYPE: str

provider property

provider

Gets the AsyncWeb3 instance. It's required for instantiating contract instances

RETURNS DESCRIPTION
AsyncWeb3

The AsyncWeb3 instance.

TYPE: AsyncWeb3

Example
provider = wallet.provider

# Define the ABI (Application Binary Interface) of the smart contract and the contract address
stargate_abi = [...]
stargate_router = '0x8731d54E9D02c286767d56ac03e8037C07e01e98'  # Contract address (Stargate Router)

# Create a contract instance using the ABI and contract address
stargate = wallet.provider.eth.contract(address=stargate_router, abi=stargate_abi)

network_map classmethod

network_map()

Returns a copy of the network map, containing information about built-in networks.

RETURNS DESCRIPTION
dict[str, Network]

dict[str, Network]: The network map.

Source code in ether/_base_wallet.py
313
314
315
316
317
318
319
320
321
@classmethod
def network_map(cls) -> dict[str, Network]:
    """
    Returns a copy of the network map, containing information about built-in networks.

    Returns:
        dict[str, Network]: The network map.
    """
    return cls.__network_map.copy()

is_native_token

is_native_token(token)

Checks if the token is the native token of the network.

PARAMETER DESCRIPTION
token

Token symbol.

TYPE: str

RETURNS DESCRIPTION
bool

True if the token is native, False otherwise.

TYPE: bool

Source code in ether/_base_wallet.py
323
324
325
326
327
328
329
330
331
332
333
334
335
336
def is_native_token(self, token: str) -> bool:
    """
    Checks if the token is the native token of the network.

    Args:
        token: Token symbol.

    Returns:
        bool: True if the token is native, False otherwise.
    """
    network = self.network

    native_token = network.token
    return token.upper() == native_token or token.lower() == native_token

get_explorer_url

get_explorer_url(tx_hash)

Returns the explorer URL for the given transaction hash.

PARAMETER DESCRIPTION
tx_hash

Transaction hash.

TYPE: HexBytes | str

RETURNS DESCRIPTION
str

Explorer URL for the transaction.

TYPE: str

Source code in ether/_base_wallet.py
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
def get_explorer_url(self, tx_hash: HexBytes | str) -> str:
    """
    Returns the explorer URL for the given transaction hash.

    Args:
        tx_hash: Transaction hash.

    Returns:
        str: Explorer URL for the transaction.
    """
    if isinstance(tx_hash, bytes):
        tx_hash = tx_hash.hex()
    elif not isinstance(tx_hash, str):
        raise TypeError(f"Invalid transaction hash type. Hash must be a `bytes` object or `str`. "
                        f"Actual type:  {type(tx_hash)}")

    explorer_url = f'{self.network.explorer}/tx/{tx_hash}'
    return explorer_url

create classmethod

create(network='Ethereum')

Creates a new ethereum account and associated AsyncWallet instance.

PARAMETER DESCRIPTION
network

The name of the built-in Ethereum-based network or custom network configuration

TYPE: Union[Network, str] DEFAULT: 'Ethereum'

RETURNS DESCRIPTION
Self

Instance of AsyncWallet.

TYPE: AsyncWallet

Source code in ether/async_wallet.py
109
110
111
112
113
114
115
116
117
118
119
120
@classmethod
def create(cls, network: Union[Network, str] = 'Ethereum') -> "AsyncWallet":
    """
    Creates a new ethereum account and associated AsyncWallet instance.

    Args:
        network: The name of the built-in Ethereum-based network or custom network configuration

    Returns:
        Self: Instance of AsyncWallet.
    """
    return cls.create(network)

get_balance async

get_balance(from_wei=False)

Retrieves the balance of the wallet.

PARAMETER DESCRIPTION
from_wei

Whether to return the balance in ethereum units instead of Wei.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Union[float, Wei]

float | Wei: The balance in Wei or ethereum.

Example
async def main():
    balance = await wallet.get_balance(from_wei=True)
    print(f"Wallet Balance: {balance} ETH")
Source code in ether/async_wallet.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
async def get_balance(self, from_wei: bool = False) -> Union[float,  Wei]:
    """
    Retrieves the balance of the wallet.

    Args:
        from_wei: Whether to return the balance in ethereum units instead of Wei.

    Returns:
        float | Wei: The balance in Wei or ethereum.

    Example:
        ```python
        async def main():
            balance = await wallet.get_balance(from_wei=True)
            print(f"Wallet Balance: {balance} ETH")
        ```
    """
    provider = self.provider
    balance = await provider.eth.get_balance(self.public_key)

    return balance if not from_wei else provider.from_wei(balance, 'ether')

estimate_gas async

estimate_gas(tx_params, from_wei=False)

Estimates the gas for the given transaction params

PARAMETER DESCRIPTION
tx_params

The transaction parameters.

TYPE: TxParams

from_wei

Whether to return the gas value in Ether units.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Wei

The estimated gas cost.

TYPE: Wei

Example
async def main():
    tx_params = await wallet.build_tx_params(...)
    gas_estimated = wallet.estimate_gas(tx_params)
    print(f"Estimated Gas: {gas_estimated}")
Source code in ether/async_wallet.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
async def estimate_gas(self, tx_params: TxParams, from_wei: bool = False) -> Wei:
    """
    Estimates the gas for the given transaction params

    Args:
        tx_params: The transaction parameters.
        from_wei: Whether to return the gas value in Ether units.

    Returns:
        Wei: The estimated gas cost.

    Example:
        ```python
        async def main():
            tx_params = await wallet.build_tx_params(...)
            gas_estimated = wallet.estimate_gas(tx_params)
            print(f"Estimated Gas: {gas_estimated}")
        ```
    """
    provider = self.provider
    gas = Wei(int(await provider.eth.estimate_gas(tx_params)))
    return gas if not from_wei else provider.from_wei(gas, 'ether')

build_and_transact async

build_and_transact(closure, value=0, gas=None, max_fee=None, max_priority_fee=None, validate_status=False)

Builds and sends a transaction. It's based on getting closure as an argument. Closure is a transaction's function, called with arguments. Notice that it has to be not built

PARAMETER DESCRIPTION
closure

Contract function.

TYPE: AsyncContractFunction

value

Transaction value. Defaults to 0.

TYPE: TokenAmount DEFAULT: 0

gas

Gas limit. Defaults to None.

TYPE: Optional[int] DEFAULT: None

max_fee

The maximum fee per gas. Defaults to None.

TYPE: Optional[Wei] DEFAULT: None

max_priority_fee

The maximum priority fee per gas. Defaults to None.

TYPE: Optional[Wei] DEFAULT: None

validate_status

Whether to throw the error if the transaction status is bad. Defaults to False.

TYPE: bool DEFAULT: False

Example
from ether import AsyncWallet

async def main():
    # Initialize the wallet object with your private key and network (e.g., Arbitrum)
    wallet = AsyncWallet('0xPrivateKey', 'Arbitrum')

    # Access the provider associated with the wallet
    provider = wallet.provider

    # Define the ABI (Application Binary Interface) of the smart contract and the contract address
    stargate_abi = [...]
    stargate_router = '0x8731d54E9D02c286767d56ac03e8037C07e01e98'  # Contract address (Stargate Router)

    # Create a contract instance using the ABI and contract address
    stargate = wallet.provider.eth.contract(address=stargate_router, abi=stargate_abi)

    usdt = '0xUsdtAddress'
    eth_amount = provider.to_wei(0.001, 'ether')  # 0.001 Ether to Wei

    # Prepare the contract function call to swap ETH for USDT using the smart contract's function
    closure = stargate.functions.swapETH(eth_amount, usdt)

    # Build the transaction and send it
    await wallet.build_and_transact(closure, eth_amount)
RETURNS DESCRIPTION
HexBytes

Transaction hash.

TYPE: HexBytes

Source code in ether/async_wallet.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
async def build_and_transact(
        self,
        closure: AsyncContractFunction,
        value: TokenAmount = 0,
        gas: Optional[int] = None,
        max_fee: Optional[Wei] = None,
        max_priority_fee: Optional[Wei] = None,
        validate_status: bool = False
) -> HexBytes:
    """
    Builds and sends a transaction. It's based on getting closure as an argument. Closure is a transaction's function,
    called with arguments. Notice that it has to be not built

    Args:
        closure: Contract function.
        value: Transaction value. Defaults to 0.
        gas: Gas limit. Defaults to None.
        max_fee: The maximum fee per gas. Defaults to None.
        max_priority_fee: The maximum priority fee per gas. Defaults to None.
        validate_status: Whether to throw the error if the transaction status is bad. Defaults to False.

    Example:
        ```python
        from ether import AsyncWallet

        async def main():
            # Initialize the wallet object with your private key and network (e.g., Arbitrum)
            wallet = AsyncWallet('0xPrivateKey', 'Arbitrum')

            # Access the provider associated with the wallet
            provider = wallet.provider

            # Define the ABI (Application Binary Interface) of the smart contract and the contract address
            stargate_abi = [...]
            stargate_router = '0x8731d54E9D02c286767d56ac03e8037C07e01e98'  # Contract address (Stargate Router)

            # Create a contract instance using the ABI and contract address
            stargate = wallet.provider.eth.contract(address=stargate_router, abi=stargate_abi)

            usdt = '0xUsdtAddress'
            eth_amount = provider.to_wei(0.001, 'ether')  # 0.001 Ether to Wei

            # Prepare the contract function call to swap ETH for USDT using the smart contract's function
            closure = stargate.functions.swapETH(eth_amount, usdt)

            # Build the transaction and send it
            await wallet.build_and_transact(closure, eth_amount)
        ```

    Returns:
        HexBytes: Transaction hash.
    """
    gas_ = Wei(300_000) if not gas else gas
    tx_params = await self.build_tx_params(value=value, gas=gas_, max_fee=max_fee, max_priority_fee=max_priority_fee)
    tx_params = await closure.build_transaction(tx_params)

    if not gas:
        gas = await self.estimate_gas(tx_params)
        tx_params['gas'] = gas

    return await self.transact(tx_params, validate_status=validate_status)

approve async

approve(token, contract_address, token_amount, gas=None, max_fee=None, max_priority_fee=None, validate_status=False)

Approves a specified amount of tokens for a contract.

PARAMETER DESCRIPTION
token

Token object.

TYPE: Token

contract_address

Contract address.

TYPE: AnyAddress

token_amount

Amount of tokens to approve.

TYPE: TokenAmount

gas

Gas limit. Defaults to None. If not provided, the default is 300,000.

TYPE: Optional[int] DEFAULT: None

max_fee

The maximum fee per gas. If not provided, the base fee from the latest block will be used.

TYPE: Optional[Wei] DEFAULT: None

max_priority_fee

The maximum priority fee per gas. If not provided, it will default to 5% of the max_fee.

TYPE: Optional[Wei] DEFAULT: None

validate_status

Whether to throw the error if the transaction status is bad. Defaults to False.

TYPE: bool DEFAULT: False

Example
async def main():
    # Contract address (e.g., a DeFi protocol)
    contract_address = '0xContractAddressHere'
    amount_to_approve = 1000 * 10 ** token.decimals

    # Approve the contract to spend tokens
    approval_tx_hash = await wallet.approve(token, contract_address, amount_to_approve)

    print(f"Approval transaction sent! Hash: {approval_tx_hash.hex()}")
RAISES DESCRIPTION
ValueError

If the provided contract address is not valid.

RETURNS DESCRIPTION
HexBytes

Transaction hash.

TYPE: HexBytes

Source code in ether/async_wallet.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
async def approve(
        self,
        token: Token,
        contract_address: AnyAddress,
        token_amount: TokenAmount,
        gas: Optional[int] = None,
        max_fee: Optional[Wei] = None,
        max_priority_fee: Optional[Wei] = None,
        validate_status: bool = False
) -> HexBytes:
    """
    Approves a specified amount of tokens for a contract.

    Args:
        token: Token object.
        contract_address: Contract address.
        token_amount: Amount of tokens to approve.
        gas: Gas limit. Defaults to None. If not provided, the default is 300,000.
        max_fee: The maximum fee per gas. If not provided, the base fee from the latest block will be used.
        max_priority_fee: The maximum priority fee per gas. If not provided, it will default to 5% of the `max_fee`.
        validate_status: Whether to throw the error if the transaction status is bad. Defaults to False.

    Example:
        ```python
        async def main():
            # Contract address (e.g., a DeFi protocol)
            contract_address = '0xContractAddressHere'
            amount_to_approve = 1000 * 10 ** token.decimals

            # Approve the contract to spend tokens
            approval_tx_hash = await wallet.approve(token, contract_address, amount_to_approve)

            print(f"Approval transaction sent! Hash: {approval_tx_hash.hex()}")
        ```

    Raises:
        ValueError: If the provided contract address is not valid.

    Returns:
        HexBytes: Transaction hash.
    """
    if not is_checksum_address(contract_address):
        raise ValueError('Invalid contract address is provided')

    token = self._load_token_contract(token.address)
    contract_address = self.provider.to_checksum_address(contract_address)
    return await self.build_and_transact(
        token.functions.approve(contract_address, token_amount),
        gas=gas,
        max_fee=max_fee,
        max_priority_fee=max_priority_fee,
        validate_status=validate_status
    )

build_tx_params async

build_tx_params(value, recipient=None, raw_data=None, gas=Wei(100000), max_fee=None, max_priority_fee=None, tx_type=None)

Builds the transaction parameters for a blockchain transaction.

This method constructs the parameters required to send a transaction on the Ethereum blockchain, including the transaction value, recipient, gas limit, and fee details. It can also include raw data or a custom transaction type. It's used in conjunction with the transact method to make transaction.

PARAMETER DESCRIPTION
value

The number of tokens to be sent in the transaction.

TYPE: TokenAmount

recipient

The recipient's address for the transaction.

TYPE: Optional[AnyAddress] DEFAULT: None

raw_data

The raw data to be included in the transaction.

TYPE: Optional[Union[bytes, HexStr]] DEFAULT: None

gas

The gas limit for the transaction. Default is 300,000.

TYPE: Wei DEFAULT: Wei(100000)

max_fee

The maximum fee per gas unit. If not provided, the base fee from the latest block will be used.

TYPE: Optional[Wei] DEFAULT: None

max_priority_fee

The maximum priority fee per gas unit. If not provided, it will default to 5% of the max_fee.

TYPE: Optional[Wei] DEFAULT: None

tx_type

The type of the transaction.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION
TxParams

A dictionary containing the constructed transaction parameters.

TYPE: TxParams

Example
from ether import AsyncWallet
from hexbytes import HexBytes

async def main():
    wallet = AsyncWallet('0xPrivateKey', 'Ethereum')

    value = 1 * 10 ** 18 # 1 token to send
    recipient = "0xRecipientAddress"
    raw_data = HexBytes("0xRawData")

    tx_params = await wallet.build_tx_params(
        value=value,
        recipient=recipient,
        raw_data=raw_data,
        gas=Wei(500_000),
        max_fee=Wei(1000),
        max_priority_fee=Wei(50),
        tx_type="0x2"
    )

    print(tx_params)

This will output the constructed transaction parameters, like:

{
    'from': '0xYourPublicKey',
    'chainId': 1,
    'nonce': 5,
    'value': 1e18,
    'gas': Wei(500_000),
    'maxFeePerGas': Wei(1000),
    'maxPriorityFeePerGas': Wei(50),
    'to': '0xRecipientAddress',
    'data': HexBytes("0xRawData"),
    'type': '0x2'
}

Source code in ether/async_wallet.py
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
async def build_tx_params(
        self,
        value: TokenAmount,
        recipient: Optional[AnyAddress] = None,
        raw_data: Optional[Union[bytes, HexStr]] = None,
        gas: Wei = Wei(100_000),
        max_fee: Optional[Wei] = None,
        max_priority_fee: Optional[Wei] = None,
        tx_type: Optional[str] = None,
) -> TxParams:
    """
    Builds the transaction parameters for a blockchain transaction.

    This method constructs the parameters required to send a transaction on the Ethereum blockchain,
    including the transaction value, recipient, gas limit, and fee details. It can also include
    raw data or a custom transaction type. It's used in conjunction with the [`transact`][ether.AsyncWallet.transact]
    method to make transaction. 

    Args:
        value: The number of tokens to be sent in the transaction.
        recipient: The recipient's address for the transaction.
        raw_data: The raw data to be included in the transaction.
        gas: The gas limit for the transaction. Default is 300,000.
        max_fee: The maximum fee per gas unit. If not provided,
            the base fee from the latest block will be used.
        max_priority_fee: The maximum priority fee per gas unit.
            If not provided, it will default to 5% of the `max_fee`.
        tx_type: The type of the transaction.

    Returns:
        TxParams: A dictionary containing the constructed transaction parameters.

    Example:
        ```python
        from ether import AsyncWallet
        from hexbytes import HexBytes

        async def main():
            wallet = AsyncWallet('0xPrivateKey', 'Ethereum')

            value = 1 * 10 ** 18 # 1 token to send
            recipient = "0xRecipientAddress"
            raw_data = HexBytes("0xRawData")

            tx_params = await wallet.build_tx_params(
                value=value,
                recipient=recipient,
                raw_data=raw_data,
                gas=Wei(500_000),
                max_fee=Wei(1000),
                max_priority_fee=Wei(50),
                tx_type="0x2"
            )

            print(tx_params)
        ```

        This will output the constructed transaction parameters, like:
        ```python
        {
            'from': '0xYourPublicKey',
            'chainId': 1,
            'nonce': 5,
            'value': 1e18,
            'gas': Wei(500_000),
            'maxFeePerGas': Wei(1000),
            'maxPriorityFeePerGas': Wei(50),
            'to': '0xRecipientAddress',
            'data': HexBytes("0xRawData"),
            'type': '0x2'
        }
        ```
    """
    if not max_fee:
        latest_block = await self.provider.eth.get_block('latest')
        max_fee = latest_block['baseFeePerGas'] + 1000

    tx_params = {
        'from': self.public_key,
        'chainId': self.network.chain_id,
        'nonce': self.nonce,
        'value': value,
        'gas': gas,
        'maxFeePerGas': max_fee,
        'maxPriorityFeePerGas': max_priority_fee or int(max_fee * 0.05)
    }

    if recipient:
        tx_params['to'] = self.provider.to_checksum_address(recipient)

    if raw_data:
        tx_params['data'] = raw_data

    if tx_type:
        tx_params['type'] = tx_type

    return tx_params

transact async

transact(tx_params, validate_status=False)

Sends a transaction. It's used in conjunction with the build_tx_params method to build transaction params.

PARAMETER DESCRIPTION
tx_params

Transaction parameters.

TYPE: TxParams

validate_status

Whether to throw the error if the transaction status is bad. Defaults to False.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
ValueError

If the transaction is failed and validate_status is True

Example
from ether import Wallet

async def main():
    # Create a wallet instance
    wallet = Wallet('0xPrivateKey', 'Ethereum')

    # Define recipient and amount
    recipient = '0xRecipientAddressHere'
    amount_in_wei = 10 ** 18 # 1 Ether (in Wei)

    # Build transaction params and send the transaction
    params = await wallet.build_tx_params(amount_in_wei, recipient)
    tx_hash = await wallet.transact(params)

    print(f"Transaction sent! Hash: {tx_hash.hex()}")
RETURNS DESCRIPTION
HexBytes

Transaction hash.

TYPE: HexBytes

Source code in ether/async_wallet.py
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
async def transact(self, tx_params: TxParams, validate_status: bool = False) -> HexBytes:
    """
    Sends a transaction. It's used in conjunction with the [`build_tx_params`][ether.AsyncWallet.build_tx_params] method to
    build transaction params.

    Args:
        tx_params: Transaction parameters.
        validate_status: Whether to throw the error if the transaction status is bad. Defaults to False.

    Raises:
        ValueError: If the transaction is failed and validate_status is True

    Example:
        ```python
        from ether import Wallet

        async def main():
            # Create a wallet instance
            wallet = Wallet('0xPrivateKey', 'Ethereum')

            # Define recipient and amount
            recipient = '0xRecipientAddressHere'
            amount_in_wei = 10 ** 18 # 1 Ether (in Wei)

            # Build transaction params and send the transaction
            params = await wallet.build_tx_params(amount_in_wei, recipient)
            tx_hash = await wallet.transact(params)

            print(f"Transaction sent! Hash: {tx_hash.hex()}")
        ```

    Returns:
        HexBytes: Transaction hash.
    """
    provider = self.provider
    signed_transaction = provider.eth.account.sign_transaction(tx_params, self.private_key)
    tx_hash = await provider.eth.send_raw_transaction(signed_transaction.rawTransaction)
    self._nonce += 1

    if validate_status:
        receipt = await provider.eth.wait_for_transaction_receipt(tx_hash)
        if receipt.status != 1:
            raise ValueError(f"Transaction failed with status {receipt.status}. Receipt: {receipt}")

    return tx_hash

transfer async

transfer(token, recipient, token_amount, gas=None, max_fee=None, max_priority_fee=None, validate_status=False)

Transfers ERC-20 tokens to a recipient. Don't use it to transfer native tokens (like ETH in Ethereum, Arbitrum), instead use the build_tx_params and transact methods.

PARAMETER DESCRIPTION
token

Token object.

TYPE: Token

recipient

Recipient address.

TYPE: AnyAddress

token_amount

Amount of tokens to transfer.

TYPE: TokenAmount

gas

Gas limit. Defaults to None. If not provided, the default is 300,000.

TYPE: Optional[Wei] DEFAULT: None

max_fee

The maximum fee per gas. If not provided, the base fee from the latest block will be used.

TYPE: Optional[Wei] DEFAULT: None

max_priority_fee

The maximum priority fee per gas. If not provided, it will default to 5% of the max_fee.

TYPE: Optional[Wei] DEFAULT: None

validate_status

Whether to throw the error if the transaction status is bad. Defaults to False.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
ValueError

If the recipient address is invalid.

Example
from ether import AsyncWallet

async def main():
    wallet = AsyncWallet('0xPrivateKey', 'Ethereum')

    # Token details
    token_address = '0xTokenAddressHere'
    token = await wallet.get_token(token_address)

    # Recipient and amount
    recipient = '0xRecipientAddressHere'
    amount = 100 * 10 ** token.decimals  # Sending 100 USDT

    # Perform the token transfer
    transaction_hash = await wallet.transfer(token, recipient, amount)

    print(f"Token transfer sent! Hash: {transaction_hash.hex()}")

Returns: HexBytes: Transaction hash.

Source code in ether/async_wallet.py
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
async def transfer(
        self,
        token: Token,
        recipient: AnyAddress,
        token_amount: TokenAmount,
        gas: Optional[Wei] = None,
        max_fee: Optional[Wei] = None,
        max_priority_fee: Optional[Wei] = None,
        validate_status: bool = False
) -> HexBytes:
    """
    Transfers ERC-20 tokens to a recipient. Don't use it to transfer native tokens (like ETH in Ethereum, Arbitrum),
    instead use the [`build_tx_params`][ether.AsyncWallet.build_tx_params] and [`transact`][ether.AsyncWallet.transact] methods.

    Args:
        token: Token object.
        recipient: Recipient address.
        token_amount: Amount of tokens to transfer.
        gas: Gas limit. Defaults to None. If not provided, the default is 300,000.
        max_fee: The maximum fee per gas. If not provided, the base fee from the latest block will be used.
        max_priority_fee: The maximum priority fee per gas. If not provided, it will default to 5% of the `max_fee`.
        validate_status: Whether to throw the error if the transaction status is bad. Defaults to False.

    Raises:
        ValueError: If the recipient address is invalid.

    Example:
        ```python
        from ether import AsyncWallet

        async def main():
            wallet = AsyncWallet('0xPrivateKey', 'Ethereum')

            # Token details
            token_address = '0xTokenAddressHere'
            token = await wallet.get_token(token_address)

            # Recipient and amount
            recipient = '0xRecipientAddressHere'
            amount = 100 * 10 ** token.decimals  # Sending 100 USDT

            # Perform the token transfer
            transaction_hash = await wallet.transfer(token, recipient, amount)

            print(f"Token transfer sent! Hash: {transaction_hash.hex()}")
        ```
    Returns:
        HexBytes: Transaction hash.
    """
    if not is_checksum_address(recipient):
        raise ValueError('Invalid recipient address is provided')

    token_contract = self._load_token_contract(token.address)
    recipient = self.provider.to_checksum_address(recipient)
    closure = token_contract.functions.transfer(recipient, token_amount)
    return await self.build_and_transact(closure, Wei(0), gas, max_fee, max_priority_fee, validate_status)

get_balance_of async

get_balance_of(token, convert=False)

Retrieves the balance of a specified token. Don't use it to get balance of native tokens (like ETH in Ethereum, Arbitrum), instead use the get_balance methods.

PARAMETER DESCRIPTION
token

The token instance.

TYPE: Token

convert

Whether to convert the balance using the token's decimals. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
float

The balance of the token.

TYPE: float

Example
async def main():
    # Get the token balance
    balance = await wallet.get_balance_of(token, convert=True)
    print(f"Token Balance: {balance} {token.symbol}")
Source code in ether/async_wallet.py
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
async def get_balance_of(self, token: Token, convert: bool = False) -> float:
    """
    Retrieves the balance of a specified token. Don't use it to get balance of native tokens (like ETH in Ethereum, Arbitrum),
    instead use the [`get_balance`][ether.AsyncWallet.get_balance] methods.

    Args:
        token: The token instance.
        convert: Whether to convert the balance using the token's decimals. Defaults to False.

    Returns:
        float: The balance of the token.

    Example:
        ```python
        async def main():
            # Get the token balance
            balance = await wallet.get_balance_of(token, convert=True)
            print(f"Token Balance: {balance} {token.symbol}")
        ```
    """
    token_contract = self._load_token_contract(token.address)
    balance = await token_contract.functions.balanceOf(self.public_key).call()

    if convert:
        balance /= 10 ** token.decimals

    return balance

get_token async

get_token(address, abi=None)

Retrieves the token information from the specified address and puts it to the Token instance

PARAMETER DESCRIPTION
address

The token contract address.

TYPE: AnyAddress

abi

Contract ABI. Defaults to USDT ABI.

TYPE: Optional[ABI] DEFAULT: None

RETURNS DESCRIPTION
Token

The token instance.

TYPE: Token

Example
from ether import AsyncWallet

async def main():
    wallet = AsyncWallet('0xPrivateKey', 'Ethereum')

    # Token details
    token_address = '0xTokenAddressHere'
    token = await wallet.get_token(token_address)

    print(f"Token {token.symbol} is loaded!")
RAISES DESCRIPTION
ValueError

If the token address is invalid.

Source code in ether/async_wallet.py
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
async def get_token(self, address: AnyAddress, abi: Optional[ABI] = None) -> Token:
    """
    Retrieves the token information from the specified address and puts it to the Token instance

    Args:
        address: The token contract address.
        abi: Contract ABI. Defaults to USDT ABI.

    Returns:
        Token: The token instance.

    Example:
        ```python
        from ether import AsyncWallet

        async def main():
            wallet = AsyncWallet('0xPrivateKey', 'Ethereum')

            # Token details
            token_address = '0xTokenAddressHere'
            token = await wallet.get_token(token_address)

            print(f"Token {token.symbol} is loaded!")
        ```

    Raises:
        ValueError: If the token address is invalid.
    """
    if not is_checksum_address(address):
        raise ValueError('Invalid token address is provided')

    address = self._provider.to_checksum_address(address)
    token_contract = self._load_token_contract(address, abi)
    symbol = await token_contract.functions.symbol().call()
    decimals = await token_contract.functions.decimals().call()

    return Token(address=address, symbol=symbol, decimals=decimals)