Skip to content

API Reference

Implemented coins

BTC

BTC class supports lightning out of the box. For lightning methods to work, it must be enabled from the daemon (enabled by default and edited by BTC_LIGHTNING environment variable). If lightning is disabled, LightningDisabledError is raised when calling lightning methods.

BTC

BTC(
    rpc_url: str | None = None,
    rpc_user: str | None = None,
    rpc_pass: str | None = None,
    xpub: str | None = None,
    proxy: str | None = None,
    session: Optional[ClientSession] = None,
)

              flowchart TD
              bitcart.coins.btc.BTC[BTC]
              bitcart.coin.Coin[Coin]
              bitcart.event_delivery.EventDelivery[EventDelivery]

                              bitcart.coin.Coin --> bitcart.coins.btc.BTC
                
                bitcart.event_delivery.EventDelivery --> bitcart.coins.btc.BTC
                


              click bitcart.coins.btc.BTC href "" "bitcart.coins.btc.BTC"
              click bitcart.coin.Coin href "" "bitcart.coin.Coin"
              click bitcart.event_delivery.EventDelivery href "" "bitcart.event_delivery.EventDelivery"
            

Methods:

Attributes:

  • node_id (str) –

    Get node id

  • spec (dict) –

    Returns current daemon's spec

Source code in bitcart/coins/btc.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def __init__(
    self,
    rpc_url: str | None = None,
    rpc_user: str | None = None,
    rpc_pass: str | None = None,
    xpub: str | None = None,
    proxy: str | None = None,
    session: Optional["ClientSession"] = None,
):
    super().__init__()
    self.symbol = self.coin_name
    self.rpc_url = rpc_url or self.RPC_URL
    self.rpc_user = rpc_user or self.RPC_USER
    self.rpc_pass = rpc_pass or self.RPC_PASS
    self.xpub = xpub
    self.event_handlers: dict[str, Callable] = {}
    self.amount_field = getattr(self, "AMOUNT_FIELD", f"amount_{self.coin_name}")
    self.server = RPCProxy(self.rpc_url, self.rpc_user, self.rpc_pass, self.xpub, session=session, proxy=proxy)
node_id async property
node_id: str

Get node id

Electrum's lightning implementation itself is a lightning node, that way you can get a super light node, this method returns it's id

Examples:

>>> a.node_id
'030ff29580149a366bdddf148713fa808f0f4b934dccd5f7820f3d613e03c86e55'

Returns:

  • str ( str ) –

    id of your node

spec async property
spec: dict

Returns current daemon's spec

It contains documentation for all possible exceptions raised

Examples:

>>> c.spec
{'version': '0.0.1', 'electrum_map': {...}, 'exceptions': {...}}

Returns:

  • dict ( dict ) –

    spec

add_invoice async
add_invoice(
    amount: AmountType, description: str = "", expire: int | float = 15
) -> dict

Create a lightning invoice

Create a lightning invoice and return invoice data with bolt invoice id All parameters are the same as in add_request

Examples:

>>> a.add_invoice(0.5, "My invoice", 20)
{'time': 1562762334, 'amount': 50000000, 'exp': 1200, 'invoice': 'lnbc500m',...

Parameters:

  • self
    (BTC) –

    self

  • amount
    (AmountType) –

    amount to open invoice

  • description
    (str, default: '' ) –

    Description of invoice. Defaults to "".

  • expire
    (Union[int, float], default: 15 ) –

    The time invoice will expire in. In minutes. Defaults to 15.

Returns:

  • dict ( dict ) –

    Invoice data

Source code in bitcart/coins/btc.py
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
@lightning
async def add_invoice(
    self,
    amount: AmountType,
    description: str = "",
    expire: int | float = 15,
) -> dict:
    """Create a lightning invoice

    Create a lightning invoice and return invoice data with bolt invoice id
    All parameters are the same as in add_request

    Examples:
        >>> a.add_invoice(0.5, "My invoice", 20)
        {'time': 1562762334, 'amount': 50000000, 'exp': 1200, 'invoice': 'lnbc500m',...

    Args:
        self (BTC): self
        amount (AmountType): amount to open invoice
        description (str, optional): Description of invoice. Defaults to "".
        expire (Union[int, float], optional): The time invoice will expire in. In minutes. Defaults to 15.

    Returns:
        dict: Invoice data
    """
    return await self._add_request_base(
        self._add_request, amount, description, expire, extra_kwargs={"force": True, "lightning": True}
    )
add_request async
add_request(
    amount: AmountType | None = None, description: str = "", expire: int | float = 15
) -> dict

Add invoice

Create an invoice and request amount in BTC, it will expire by parameter provided. If expire is None, it will last forever.

Examples:

>>> c.add_request(0.5, "My invoice", 20)
{'time': 1562762334, 'amount': 50000000, 'exp': 1200, 'address': 'xxx',...

Parameters:

  • self
    (BTC) –

    self

  • amount
    (Optional[AmountType], default: None ) –

    amount to open invoice. Defaults to None.

  • description
    (str, default: '' ) –

    Description of invoice. Defaults to "".

  • expire
    (Union[int, float], default: 15 ) –

    The time invoice will expire in. In minutes. Defaults to 15.

Returns:

  • dict ( dict ) –

    Invoice data

Source code in bitcart/coins/btc.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
async def add_request(
    self,
    amount: AmountType | None = None,
    description: str = "",
    expire: int | float = 15,
) -> dict:
    """Add invoice

    Create an invoice and request amount in BTC, it will expire by parameter provided.
    If expire is None, it will last forever.

    Examples:
        >>> c.add_request(0.5, "My invoice", 20)
        {'time': 1562762334, 'amount': 50000000, 'exp': 1200, 'address': 'xxx',...

    Args:
        self (BTC): self
        amount (Optional[AmountType]): amount to open invoice. Defaults to None.
        description (str, optional): Description of invoice. Defaults to "".
        expire (Union[int, float], optional): The time invoice will expire in. In minutes. Defaults to 15.

    Returns:
        dict: Invoice data
    """
    return await self._add_request_base(self._add_request, amount, description, expire, extra_kwargs={"force": True})
balance async
balance() -> dict

Get balance of wallet

Examples:

>>> c.balance()
{"confirmed": 0.00005, "unconfirmed": 0, "unmatured": 0}

Returns:

  • dict ( dict ) –

    It should return dict of balance statuses

Source code in bitcart/coins/btc.py
127
128
129
130
131
132
133
134
135
136
137
138
async def balance(self) -> dict:
    """Get balance of wallet

    Examples:
        >>> c.balance()
        {"confirmed": 0.00005, "unconfirmed": 0, "unmatured": 0}

    Returns:
        dict: It should return dict of balance statuses
    """
    data = await self.server.getbalance()
    return {attr: convert_amount_type(data.get(attr, 0)) for attr in self.BALANCE_ATTRS}
close_channel async
close_channel(channel_id: str, force: bool = False) -> str

Close lightning channel

Close channel by channel_id got from open_channel, returns transaction id

Parameters:

  • self
    (BTC) –

    self

  • channel_id
    (str) –

    channel_id from open_channel

  • force
    (bool, default: False ) –

    Create new address beyond gap limit, if no more addresses are available.

Returns:

  • str ( str ) –

    tx_id of closed channel

Source code in bitcart/coins/btc.py
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
@lightning
async def close_channel(self, channel_id: str, force: bool = False) -> str:
    """Close lightning channel

    Close channel by channel_id got from open_channel, returns transaction id

    Args:
        self (BTC): self
        channel_id (str): channel_id from open_channel
        force (bool): Create new address beyond gap limit, if no more addresses are available.

    Returns:
        str: tx_id of closed channel
    """
    return await self.server.close_channel(channel_id, force)  # type: ignore
connect async
connect(connection_string: str) -> bool

Connect to lightning node

connection string must respect format pubkey@ipaddress

Parameters:

  • connection_string
    (str) –

    connection string

Returns:

  • bool ( bool ) –

    True on success, False otherwise

Source code in bitcart/coins/btc.py
548
549
550
551
552
553
554
555
556
557
558
559
560
@lightning
async def connect(self, connection_string: str) -> bool:
    """Connect to lightning node

    connection string must respect format pubkey@ipaddress

    Args:
        connection_string (str): connection string

    Returns:
        bool: True on success, False otherwise
    """
    return await self.server.add_peer(connection_string)  # type: ignore
get_address async
get_address(address: str) -> list

Get address history

This method should return list of transaction informations for specified address

Examples:

>>> c.get_address("31smpLFzLnza6k8tJbVpxXiatGjiEQDmzc")
[{'tx_hash': '7854bdf4c4e27276ecc1fb8d666d6799a248f5e81bdd58b16432d1ddd1d4c332', 'height': 581878, 'tx': ...

Parameters:

  • address
    (str) –

    address to get transactions for

Returns:

  • list ( list ) –

    List of transactions

Source code in bitcart/coins/btc.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
async def get_address(self, address: str) -> list:  # pragma: no cover
    """Get address history

    This method should return list of transaction informations for specified address

    Examples:
        >>> c.get_address("31smpLFzLnza6k8tJbVpxXiatGjiEQDmzc")
        [{'tx_hash': '7854bdf4c4e27276ecc1fb8d666d6799a248f5e81bdd58b16432d1ddd1d4c332', 'height': 581878, 'tx': ...

    Args:
        address (str): address to get transactions for

    Returns:
        list: List of transactions
    """
    out: list = await self.server.getaddresshistory(address)
    for i in out:
        i["tx"] = await self.get_tx(i["tx_hash"])
    return out
get_config async
get_config(key: str) -> Any

Get config key

Keys are stored in electrum's config file, check :meth:bitcart.coins.btc.BTC.set_config doc for details.

Examples:

>>> c.get_config("x")
5

Parameters:

  • self
    (BTC) –

    self

  • key
    (str) –

    key to get

Returns:

  • Any ( Any ) –

    value of the key or default value provided

Source code in bitcart/coins/btc.py
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
async def get_config(self, key: str) -> Any:
    """Get config key

    Keys are stored in electrum's config file, check :meth:`bitcart.coins.btc.BTC.set_config` doc for details.

    Examples:
        >>> c.get_config("x")
        5

    Args:
        self (BTC): self
        key (str): key to get

    Returns:
        Any: value of the key or default value provided
    """
    return await self.server.getconfig(key)
get_invoice async
get_invoice(rhash: str) -> dict

Get lightning invoice info

Get lightning invoice information by rhash got from add_invoice

Examples:

>>> c.get_invoice("e34d7fb4cda66e0760fc193496c302055d0fd960cfd982432355c8bfeecd5f33")
{'is_lightning': True, 'amount_BTC': Decimal('0.5'), 'timestamp': 1619273042, 'expiry': 900, ...

Parameters:

  • rhash
    (str) –

    invoice rhash

Returns:

  • dict ( dict ) –

    invoice data

Source code in bitcart/coins/btc.py
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
@lightning
async def get_invoice(self, rhash: str) -> dict:
    """Get lightning invoice info

    Get lightning invoice information by rhash got from add_invoice

    Examples:
        >>> c.get_invoice("e34d7fb4cda66e0760fc193496c302055d0fd960cfd982432355c8bfeecd5f33")
        {'is_lightning': True, 'amount_BTC': Decimal('0.5'), 'timestamp': 1619273042, 'expiry': 900, ...

    Args:
        rhash (str): invoice rhash

    Returns:
        dict: invoice data
    """
    data = await self.server.get_invoice(rhash)
    return await self._convert_amounts(data)
get_request async
get_request(address: str) -> dict

Get invoice info

Get invoice information by address got from add_request

Examples:

>>> c.get_request("1A6jnc6xQwmhsChNLcyKAQNWPcWsVYqCqJ")
{'time': 1562762334, 'amount': 50000000, 'exp': 1200, 'address': '1A6jnc6xQwmhsChNLcyKAQNWPcWsVYqCqJ',...

Parameters:

  • self
    (BTC) –

    self

  • address
    (str) –

    address of invoice

Returns:

  • dict ( dict ) –

    Invoice data

Source code in bitcart/coins/btc.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
async def get_request(self, address: str) -> dict:
    """Get invoice info

    Get invoice information by address got from add_request

    Examples:
        >>> c.get_request("1A6jnc6xQwmhsChNLcyKAQNWPcWsVYqCqJ")
        {'time': 1562762334, 'amount': 50000000, 'exp': 1200, 'address': '1A6jnc6xQwmhsChNLcyKAQNWPcWsVYqCqJ',...

    Args:
        self (BTC): self
        address (str): address of invoice

    Returns:
        dict: Invoice data
    """
    data = await self.server.get_request(address)
    return await self._convert_amounts(data)
get_tx async
get_tx(tx: str) -> dict

Get transaction information

Given tx hash of transaction, return full information as dictionary

Examples:

>>> c.get_tx("54604b116b28124e31d2d20bbd4561e6f8398dca4b892080bffc8c87c27762ba")
{'partial': False, 'version': 2, 'segwit_ser': True, 'inputs': [{'prevout_hash': 'xxxx',...

Parameters:

  • tx
    (str) –

    tx_hash

Returns:

  • dict ( dict ) –

    transaction info

Source code in bitcart/coins/btc.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
async def get_tx(self, tx: str) -> dict:  # pragma: no cover: see tests for explanation
    """Get transaction information

    Given tx hash of transaction, return full information as dictionary

    Examples:
        >>> c.get_tx("54604b116b28124e31d2d20bbd4561e6f8398dca4b892080bffc8c87c27762ba")
        {'partial': False, 'version': 2, 'segwit_ser': True, 'inputs': [{'prevout_hash': 'xxxx',...

    Args:
        tx (str): tx_hash

    Returns:
        dict: transaction info
    """
    return await self.server.get_transaction(tx)  # type: ignore
help async
help() -> list

Get help

Returns a list of all available RPC methods

Returns:

  • list ( list ) –

    RPC methods list

Source code in bitcart/coins/btc.py
80
81
82
83
84
85
86
87
88
async def help(self) -> list:
    """Get help

    Returns a list of all available RPC methods

    Returns:
        list: RPC methods list
    """
    return await self.server.help()  # type: ignore
history async
history() -> dict

Get transaction history of wallet

Examples:

>>> c.history()
{'summary': {'end_balance': '0.', 'end_date': None, 'from_height': None, 'incoming': '0.00185511',...

Parameters:

Returns:

  • dict ( dict ) –

    dictionary with some data, where key transactions is list of transactions

Source code in bitcart/coins/btc.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
async def history(self) -> dict:
    """Get transaction history of wallet

    Examples:
        >>> c.history()
        {'summary': {'end_balance': '0.', 'end_date': None, 'from_height': None, 'incoming': '0.00185511',...

    Args:
        self (BTC): self

    Returns:
        dict: dictionary with some data, where key transactions is list of transactions
    """
    return await self.server.onchain_history()  # type: ignore
list_channels async
list_channels() -> list

List all channels ever opened

Possible channel statuses: OPENING, OPEN, CLOSED, DISCONNECTED

Examples:

>>> a.server.list_channels()
[{'local_htlcs': {'adds': {}, 'locked_in': {}, 'settles': {}, 'fails': {}}, 'remote_htlcs': ...

Returns:

  • list ( list ) –

    list of channels

Source code in bitcart/coins/btc.py
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
@lightning
async def list_channels(self) -> list:
    """List all channels ever opened

    Possible channel statuses:
    OPENING, OPEN, CLOSED, DISCONNECTED

    Examples:
        >>> a.server.list_channels()
        [{'local_htlcs': {'adds': {}, 'locked_in': {}, 'settles': {}, 'fails': {}}, 'remote_htlcs': ...

    Returns:
        list: list of channels
    """
    return await self.server.list_channels()  # type: ignore
list_peers async
list_peers(gossip: bool = False) -> list

Get a list of lightning peers

Parameters:

  • gossip
    (bool, default: False ) –

    Whether to return peers of a gossip (one per node) or of a wallet. Defaults to False.

Returns:

  • list ( list ) –

    list of lightning peers

Source code in bitcart/coins/btc.py
562
563
564
565
566
567
568
569
570
571
572
@lightning
async def list_peers(self, gossip: bool = False) -> list:
    """Get a list of lightning peers

    Args:
        gossip (bool, optional): Whether to return peers of a gossip (one per node) or of a wallet. Defaults to False.

    Returns:
        list: list of lightning peers
    """
    return await self.server.list_peers(gossip=gossip)  # type: ignore
lnpay async
lnpay(invoice: str) -> bool

Pay lightning invoice

Returns True on success, False otherwise

Parameters:

  • invoice
    (str) –

    invoice to pay

Returns:

  • bool ( bool ) –

    success or not

Source code in bitcart/coins/btc.py
534
535
536
537
538
539
540
541
542
543
544
545
546
@lightning
async def lnpay(self, invoice: str) -> bool:
    """Pay lightning invoice

    Returns True on success, False otherwise

    Args:
        invoice (str): invoice to pay

    Returns:
        bool: success or not
    """
    return await self.server.lnpay(invoice)  # type: ignore
open_channel async
open_channel(node_id: str, amount: AmountType) -> str

Open lightning channel

Open channel with node, returns string of format txid:output_index

Parameters:

  • self
    (BTC) –

    self

  • node_id
    (str) –

    id of node to open channel with

  • amount
    (AmountType) –

    amount to open channel

Returns:

  • str ( str ) –

    string of format txid:output_index

Source code in bitcart/coins/btc.py
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
@lightning
async def open_channel(self, node_id: str, amount: AmountType) -> str:
    """Open lightning channel

    Open channel with node, returns string of format
    txid:output_index

    Args:
        self (BTC): self
        node_id (str): id of node to open channel with
        amount (AmountType): amount to open channel

    Returns:
        str: string of format txid:output_index
    """
    return await self.server.open_channel(node_id, amount)  # type: ignore
pay_to async
pay_to(
    address: str,
    amount: AmountType,
    fee: AmountType | Callable | None = None,
    feerate: AmountType | None = None,
    broadcast: bool = True,
) -> dict | str

Pay to address

This function creates a transaction, your wallet must have sufficent balance and address must exist.

Examples:

>>> btc.pay_to("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt", 0.001)
'608d9af34032868fd2849723a4de9ccd874a51544a7fba879a18c847e37e577b'
>>> btc.pay_to("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt",0.001, feerate=1)
'23d0aec06f6ea6100ba9c6ce8a1fa5d333a6c1d39a780b5fadc4b2836d71b66f'
>>> btc.pay_to("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt", 0.001, broadcast=False)
{'hex': '02000000026.....', 'complete': True, 'final': False, 'name': None, 'csv_delay': 0, 'cltv_expiry': 0}

Parameters:

  • self
    (BTC) –

    self

  • address
    (str) –

    address where to send BTC

  • amount
    (AmountType) –

    amount of bitcoins to send

  • fee
    (Optional[Union[AmountType, Callable]], default: None ) –

    Either a fixed fee, or a callable getting size and default fee as argument and returning fee. Defaults to None.

  • feerate
    (Optional[AmountType], default: None ) –

    A sat/byte feerate, can't be passed together with fee argument. Defaults to None.

  • broadcast
    (bool, default: True ) –

    Whether to broadcast transaction to network. Defaults to True.

Raises:

  • TypeError

    if you have provided both fee and feerate

Returns:

  • dict | str

    Union[dict, str]: tx hash of ready transaction or raw transaction, depending on broadcast argument.

Source code in bitcart/coins/btc.py
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
282
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
async def pay_to(
    self,
    address: str,
    amount: AmountType,
    fee: AmountType | Callable | None = None,
    feerate: AmountType | None = None,
    broadcast: bool = True,
) -> dict | str:
    """Pay to address

    This function creates a transaction, your wallet must have sufficent balance
    and address must exist.

    Examples:
        >>> btc.pay_to("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt", 0.001)
        '608d9af34032868fd2849723a4de9ccd874a51544a7fba879a18c847e37e577b'

        >>> btc.pay_to("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt",0.001, feerate=1)
        '23d0aec06f6ea6100ba9c6ce8a1fa5d333a6c1d39a780b5fadc4b2836d71b66f'

        >>> btc.pay_to("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt", 0.001, broadcast=False)
        {'hex': '02000000026.....', 'complete': True, 'final': False, 'name': None, 'csv_delay': 0, 'cltv_expiry': 0}

    Args:
        self (BTC): self
        address (str): address where to send BTC
        amount (AmountType): amount of bitcoins to send
        fee (Optional[Union[AmountType, Callable]], optional): Either a fixed fee, or a callable getting size and
            default fee as argument and returning fee. Defaults to None.
        feerate (Optional[AmountType], optional): A sat/byte feerate, can't be passed together with fee argument.
            Defaults to None.
        broadcast (bool, optional): Whether to broadcast transaction to network. Defaults to True.

    Raises:
        TypeError: if you have provided both fee and feerate

    Returns:
        Union[dict, str]: tx hash of ready transaction or raw transaction, depending on broadcast argument.
    """
    if fee and feerate:
        raise TypeError("Can't specify both fee and feerate at the same time")
    is_callable = callable(fee)
    fee_arg = fee if not is_callable else None
    tx_data = await self.server.payto(
        address, amount, fee=fee_arg, feerate=feerate, addtransaction=broadcast and not is_callable
    )
    if is_callable:
        tx_size = await self.server.get_tx_size(tx_data)
        default_fee = satoshis(await self.server.get_default_fee(tx_size))
        try:
            resulting_fee: str | None = str(bitcoins(fee(tx_size, default_fee)))  # type: ignore
        except Exception:
            resulting_fee = None
        if resulting_fee:
            tx_data = await self.server.payto(
                address, amount, fee=resulting_fee, feerate=feerate, addtransaction=broadcast
            )
        elif broadcast:  # use existing tx_data
            await self.server.addtransaction(tx_data)
    if broadcast:
        return await self.server.broadcast(tx_data)  # type: ignore
    return tx_data  # type: ignore
pay_to_many async
pay_to_many(
    outputs: Iterable[dict | tuple],
    fee: AmountType | Callable | None = None,
    feerate: AmountType | None = None,
    broadcast: bool = True,
) -> dict | str

Pay to multiple addresses(batch transaction)

This function creates a batch transaction, your wallet must have sufficent balance and addresses must exist. outputs parameter is either an iterable of (address, amount) tuples(or any iterables) or a dict with two keys: address and amount {"address": "someaddress", "amount": 0.5}

Examples:

>>> btc.pay_to_many([{"address":"mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt","amount":0.001},             {"address":"mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB","amount":0.0001}])
'60fa120d9f868a7bd03d6bbd1e225923cab0ba7a3a6b961861053c90365ed40a'
>>> btc.pay_to_many([("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt",0.001), ("mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB",0.0001)])
'd80f14e20af2ceaa43a8b7e15402d420246d39e235d87874f929977fb0b1cab8'
>>> btc.pay_to_many((("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt",0.001),             ("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt",0.001)), feerate=1)
'0a6611876e04a6f2742eac02d4fac4c242dda154d85f0d547bbac1a33dbbbe34'
>>> btc.pay_to_many([("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt",0.001),             ("mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB",0.0001)], broadcast=False)
{'hex': '0200000...', 'complete': True, 'final': False}

Parameters:

  • self
    (BTC) –

    self

  • outputs
    (Iterable[Union[dict, tuple]]) –

    An iterable with dictionary or iterable as the item

  • fee
    (Optional[Union[AmountType, Callable]], default: None ) –

    Either a fixed fee, or a callable getting size and default fee as argument and returning fee. Defaults to None.

  • feerate
    (Optional[AmountType], default: None ) –

    A sat/byte feerate, can't be passed together with fee argument. Defaults to None.

  • broadcast
    (bool, default: True ) –

    Whether to broadcast transaction to network. Defaults to True.

Raises:

  • TypeError

    if you have provided both fee and feerate

Returns:

  • dict | str

    Union[dict, str]: tx hash of ready transaction or raw transaction, depending on broadcast argument.

Source code in bitcart/coins/btc.py
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
380
381
382
383
384
385
async def pay_to_many(
    self,
    outputs: Iterable[dict | tuple],
    fee: AmountType | Callable | None = None,
    feerate: AmountType | None = None,
    broadcast: bool = True,
) -> dict | str:
    """Pay to multiple addresses(batch transaction)

    This function creates a batch transaction, your wallet must have sufficent balance
    and addresses must exist.
    outputs parameter is either an iterable of ``(address, amount)`` tuples(or any iterables) or a dict with two
    keys: address and amount ``{"address": "someaddress", "amount": 0.5}``

    Examples:
        >>> btc.pay_to_many([{"address":"mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt","amount":0.001}, \
        {"address":"mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB","amount":0.0001}])
        '60fa120d9f868a7bd03d6bbd1e225923cab0ba7a3a6b961861053c90365ed40a'

        >>> btc.pay_to_many([("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt",0.001), ("mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB",0.0001)])
        'd80f14e20af2ceaa43a8b7e15402d420246d39e235d87874f929977fb0b1cab8'

        >>> btc.pay_to_many((("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt",0.001), \
        ("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt",0.001)), feerate=1)
        '0a6611876e04a6f2742eac02d4fac4c242dda154d85f0d547bbac1a33dbbbe34'

        >>> btc.pay_to_many([("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt",0.001), \
        ("mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB",0.0001)], broadcast=False)
        {'hex': '0200000...', 'complete': True, 'final': False}

    Args:
        self (BTC): self
        outputs (Iterable[Union[dict, tuple]]): An iterable with dictionary or iterable as the item
        fee (Optional[Union[AmountType, Callable]], optional): Either a fixed fee, or a callable getting size and
            default fee as argument and returning fee. Defaults to None.
        feerate (Optional[AmountType], optional): A sat/byte feerate, can't be passed together with fee argument.
            Defaults to None.
        broadcast (bool, optional): Whether to broadcast transaction to network. Defaults to True.

    Raises:
        TypeError: if you have provided both fee and feerate

    Returns:
        Union[dict, str]: tx hash of ready transaction or raw transaction, depending on broadcast argument.
    """
    if fee and feerate:
        raise TypeError("Can't specify both fee and feerate at the same time")
    new_outputs = []
    dict_outputs = False
    for output in outputs:
        if isinstance(output, dict):
            dict_outputs = True
            new_outputs.append((output["address"], output["amount"]))
    outputs = new_outputs if dict_outputs else outputs
    is_callable = callable(fee)
    fee_arg = fee if not is_callable else None
    tx_data = await self.server.paytomany(
        outputs, fee=fee_arg, feerate=feerate, addtransaction=broadcast and not is_callable
    )
    if is_callable:
        tx_size = await self.server.get_tx_size(tx_data)
        default_fee = satoshis(await self.server.get_default_fee(tx_size))
        try:
            resulting_fee: str | None = str(bitcoins(fee(tx_size, default_fee)))  # type: ignore
        except Exception:
            resulting_fee = None
        if resulting_fee:
            tx_data = await self.server.paytomany(outputs, fee=resulting_fee, feerate=feerate, addtransaction=broadcast)
        elif broadcast:  # use existing tx_data
            await self.server.addtransaction(tx_data)
    if broadcast:
        return await self.server.broadcast(tx_data)  # type: ignore
    return tx_data  # type: ignore
set_config async
set_config(key: str, value: Any) -> bool

Set config key to specified value

It sets the config value in electrum's config store, usually $HOME/.electrum/config

You can set any keys and values using this function(as long as JSON serializable), and some are used to configure underlying electrum daemon.

Examples:

>>> c.set_config("x", 5)
True

Parameters:

  • self
    (BTC) –

    self

  • key
    (str) –

    key to set

  • value
    (Any) –

    value to set

Returns:

  • bool ( bool ) –

    True on success, False otherwise

Source code in bitcart/coins/btc.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
async def set_config(self, key: str, value: Any) -> bool:
    """Set config key to specified value

    It sets the config value in electrum's config store, usually
    $HOME/.electrum/config

    You can set any keys and values using this function(as long as JSON serializable),
    and some are used to configure underlying electrum daemon.

    Examples:
        >>> c.set_config("x", 5)
        True

    Args:
        self (BTC): self
        key (str): key to set
        value (Any): value to set

    Returns:
        bool: True on success, False otherwise
    """
    return await self.server.setconfig(key, value)  # type: ignore
validate_key async
validate_key(key: str, *args: Any, **kwargs: Any) -> bool

Validate whether provided key is valid to restore a wallet

If the key is x/y/z pub/prv or electrum seed at the network daemon is running at, then it would be valid(True), else False

Examples:

>>> c.validate_key("test")
False
>>> c.validate_key("your awesome electrum seed")
True
>>> c.validate_key("x/y/z pub/prv here")
True

Parameters:

  • self
    (BTC) –

    self

  • key
    (str) –

    key to check

Returns:

  • bool ( bool ) –

    Whether the key is valid or not

Source code in bitcart/coins/btc.py
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
async def validate_key(self, key: str, *args: Any, **kwargs: Any) -> bool:
    """Validate whether provided key is valid to restore a wallet

    If the key is x/y/z pub/prv or electrum seed at the network daemon is running
    at, then it would be valid(True), else False

    Examples:
        >>> c.validate_key("test")
        False

        >>> c.validate_key("your awesome electrum seed")
        True

        >>> c.validate_key("x/y/z pub/prv here")
        True

    Args:
        self (BTC): self
        key (str): key to check

    Returns:
        bool: Whether the key is valid or not
    """
    return await self.server.validatekey(key, *args, **kwargs)  # type: ignore

BCH

BCH supports Schnorr signatures, they are enabled out of the box

BCH

BCH(
    rpc_url: str | None = None,
    rpc_user: str | None = None,
    rpc_pass: str | None = None,
    xpub: str | None = None,
    proxy: str | None = None,
    session: Optional[ClientSession] = None,
)

              flowchart TD
              bitcart.coins.bch.BCH[BCH]
              bitcart.coins.btc.BTC[BTC]
              bitcart.coin.Coin[Coin]
              bitcart.event_delivery.EventDelivery[EventDelivery]

                              bitcart.coins.btc.BTC --> bitcart.coins.bch.BCH
                                bitcart.coin.Coin --> bitcart.coins.btc.BTC
                
                bitcart.event_delivery.EventDelivery --> bitcart.coins.btc.BTC
                



              click bitcart.coins.bch.BCH href "" "bitcart.coins.bch.BCH"
              click bitcart.coins.btc.BTC href "" "bitcart.coins.btc.BTC"
              click bitcart.coin.Coin href "" "bitcart.coin.Coin"
              click bitcart.event_delivery.EventDelivery href "" "bitcart.event_delivery.EventDelivery"
            
Source code in bitcart/coins/btc.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def __init__(
    self,
    rpc_url: str | None = None,
    rpc_user: str | None = None,
    rpc_pass: str | None = None,
    xpub: str | None = None,
    proxy: str | None = None,
    session: Optional["ClientSession"] = None,
):
    super().__init__()
    self.symbol = self.coin_name
    self.rpc_url = rpc_url or self.RPC_URL
    self.rpc_user = rpc_user or self.RPC_USER
    self.rpc_pass = rpc_pass or self.RPC_PASS
    self.xpub = xpub
    self.event_handlers: dict[str, Callable] = {}
    self.amount_field = getattr(self, "AMOUNT_FIELD", f"amount_{self.coin_name}")
    self.server = RPCProxy(self.rpc_url, self.rpc_user, self.rpc_pass, self.xpub, session=session, proxy=proxy)

XMR

XMR support is based on our custom daemon implementation which tries to follow electrum APIs as closely as possible

XMR

XMR(
    rpc_url: str | None = None,
    rpc_user: str | None = None,
    rpc_pass: str | None = None,
    xpub: str | None = None,
    proxy: str | None = None,
    session: Optional[ClientSession] = None,
)

              flowchart TD
              bitcart.coins.xmr.XMR[XMR]
              bitcart.coins.eth.ETH[ETH]
              bitcart.coins.btc.BTC[BTC]
              bitcart.coin.Coin[Coin]
              bitcart.event_delivery.EventDelivery[EventDelivery]

                              bitcart.coins.eth.ETH --> bitcart.coins.xmr.XMR
                                bitcart.coins.btc.BTC --> bitcart.coins.eth.ETH
                                bitcart.coin.Coin --> bitcart.coins.btc.BTC
                
                bitcart.event_delivery.EventDelivery --> bitcart.coins.btc.BTC
                




              click bitcart.coins.xmr.XMR href "" "bitcart.coins.xmr.XMR"
              click bitcart.coins.eth.ETH href "" "bitcart.coins.eth.ETH"
              click bitcart.coins.btc.BTC href "" "bitcart.coins.btc.BTC"
              click bitcart.coin.Coin href "" "bitcart.coin.Coin"
              click bitcart.event_delivery.EventDelivery href "" "bitcart.event_delivery.EventDelivery"
            
Source code in bitcart/coins/btc.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def __init__(
    self,
    rpc_url: str | None = None,
    rpc_user: str | None = None,
    rpc_pass: str | None = None,
    xpub: str | None = None,
    proxy: str | None = None,
    session: Optional["ClientSession"] = None,
):
    super().__init__()
    self.symbol = self.coin_name
    self.rpc_url = rpc_url or self.RPC_URL
    self.rpc_user = rpc_user or self.RPC_USER
    self.rpc_pass = rpc_pass or self.RPC_PASS
    self.xpub = xpub
    self.event_handlers: dict[str, Callable] = {}
    self.amount_field = getattr(self, "AMOUNT_FIELD", f"amount_{self.coin_name}")
    self.server = RPCProxy(self.rpc_url, self.rpc_user, self.rpc_pass, self.xpub, session=session, proxy=proxy)

ETH

ETH support is based on our custom daemon implementation which tries to follow electrum APIs as closely as possible

ETH

ETH(
    rpc_url: str | None = None,
    rpc_user: str | None = None,
    rpc_pass: str | None = None,
    xpub: str | None = None,
    proxy: str | None = None,
    session: Optional[ClientSession] = None,
)

              flowchart TD
              bitcart.coins.eth.ETH[ETH]
              bitcart.coins.btc.BTC[BTC]
              bitcart.coin.Coin[Coin]
              bitcart.event_delivery.EventDelivery[EventDelivery]

                              bitcart.coins.btc.BTC --> bitcart.coins.eth.ETH
                                bitcart.coin.Coin --> bitcart.coins.btc.BTC
                
                bitcart.event_delivery.EventDelivery --> bitcart.coins.btc.BTC
                



              click bitcart.coins.eth.ETH href "" "bitcart.coins.eth.ETH"
              click bitcart.coins.btc.BTC href "" "bitcart.coins.btc.BTC"
              click bitcart.coin.Coin href "" "bitcart.coin.Coin"
              click bitcart.event_delivery.EventDelivery href "" "bitcart.event_delivery.EventDelivery"
            
Source code in bitcart/coins/btc.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def __init__(
    self,
    rpc_url: str | None = None,
    rpc_user: str | None = None,
    rpc_pass: str | None = None,
    xpub: str | None = None,
    proxy: str | None = None,
    session: Optional["ClientSession"] = None,
):
    super().__init__()
    self.symbol = self.coin_name
    self.rpc_url = rpc_url or self.RPC_URL
    self.rpc_user = rpc_user or self.RPC_USER
    self.rpc_pass = rpc_pass or self.RPC_PASS
    self.xpub = xpub
    self.event_handlers: dict[str, Callable] = {}
    self.amount_field = getattr(self, "AMOUNT_FIELD", f"amount_{self.coin_name}")
    self.server = RPCProxy(self.rpc_url, self.rpc_user, self.rpc_pass, self.xpub, session=session, proxy=proxy)

BNB

BNB support is based on our custom daemon implementation which tries to follow electrum APIs as closely as possible

BNB

BNB(
    rpc_url: str | None = None,
    rpc_user: str | None = None,
    rpc_pass: str | None = None,
    xpub: str | None = None,
    proxy: str | None = None,
    session: Optional[ClientSession] = None,
)

              flowchart TD
              bitcart.coins.bnb.BNB[BNB]
              bitcart.coins.eth.ETH[ETH]
              bitcart.coins.btc.BTC[BTC]
              bitcart.coin.Coin[Coin]
              bitcart.event_delivery.EventDelivery[EventDelivery]

                              bitcart.coins.eth.ETH --> bitcart.coins.bnb.BNB
                                bitcart.coins.btc.BTC --> bitcart.coins.eth.ETH
                                bitcart.coin.Coin --> bitcart.coins.btc.BTC
                
                bitcart.event_delivery.EventDelivery --> bitcart.coins.btc.BTC
                




              click bitcart.coins.bnb.BNB href "" "bitcart.coins.bnb.BNB"
              click bitcart.coins.eth.ETH href "" "bitcart.coins.eth.ETH"
              click bitcart.coins.btc.BTC href "" "bitcart.coins.btc.BTC"
              click bitcart.coin.Coin href "" "bitcart.coin.Coin"
              click bitcart.event_delivery.EventDelivery href "" "bitcart.event_delivery.EventDelivery"
            
Source code in bitcart/coins/btc.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def __init__(
    self,
    rpc_url: str | None = None,
    rpc_user: str | None = None,
    rpc_pass: str | None = None,
    xpub: str | None = None,
    proxy: str | None = None,
    session: Optional["ClientSession"] = None,
):
    super().__init__()
    self.symbol = self.coin_name
    self.rpc_url = rpc_url or self.RPC_URL
    self.rpc_user = rpc_user or self.RPC_USER
    self.rpc_pass = rpc_pass or self.RPC_PASS
    self.xpub = xpub
    self.event_handlers: dict[str, Callable] = {}
    self.amount_field = getattr(self, "AMOUNT_FIELD", f"amount_{self.coin_name}")
    self.server = RPCProxy(self.rpc_url, self.rpc_user, self.rpc_pass, self.xpub, session=session, proxy=proxy)

Polygon (MATIC)

Polygon (MATIC) support is based on our custom daemon implementation which tries to follow electrum APIs as closely as possible

MATIC

MATIC(
    rpc_url: str | None = None,
    rpc_user: str | None = None,
    rpc_pass: str | None = None,
    xpub: str | None = None,
    proxy: str | None = None,
    session: Optional[ClientSession] = None,
)

              flowchart TD
              bitcart.coins.matic.MATIC[MATIC]
              bitcart.coins.eth.ETH[ETH]
              bitcart.coins.btc.BTC[BTC]
              bitcart.coin.Coin[Coin]
              bitcart.event_delivery.EventDelivery[EventDelivery]

                              bitcart.coins.eth.ETH --> bitcart.coins.matic.MATIC
                                bitcart.coins.btc.BTC --> bitcart.coins.eth.ETH
                                bitcart.coin.Coin --> bitcart.coins.btc.BTC
                
                bitcart.event_delivery.EventDelivery --> bitcart.coins.btc.BTC
                




              click bitcart.coins.matic.MATIC href "" "bitcart.coins.matic.MATIC"
              click bitcart.coins.eth.ETH href "" "bitcart.coins.eth.ETH"
              click bitcart.coins.btc.BTC href "" "bitcart.coins.btc.BTC"
              click bitcart.coin.Coin href "" "bitcart.coin.Coin"
              click bitcart.event_delivery.EventDelivery href "" "bitcart.event_delivery.EventDelivery"
            
Source code in bitcart/coins/btc.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def __init__(
    self,
    rpc_url: str | None = None,
    rpc_user: str | None = None,
    rpc_pass: str | None = None,
    xpub: str | None = None,
    proxy: str | None = None,
    session: Optional["ClientSession"] = None,
):
    super().__init__()
    self.symbol = self.coin_name
    self.rpc_url = rpc_url or self.RPC_URL
    self.rpc_user = rpc_user or self.RPC_USER
    self.rpc_pass = rpc_pass or self.RPC_PASS
    self.xpub = xpub
    self.event_handlers: dict[str, Callable] = {}
    self.amount_field = getattr(self, "AMOUNT_FIELD", f"amount_{self.coin_name}")
    self.server = RPCProxy(self.rpc_url, self.rpc_user, self.rpc_pass, self.xpub, session=session, proxy=proxy)

TRON (TRX)

TRON (TRX) support is based on our custom daemon implementation which tries to follow electrum APIs as closely as possible

TRX

TRX(
    rpc_url: str | None = None,
    rpc_user: str | None = None,
    rpc_pass: str | None = None,
    xpub: str | None = None,
    proxy: str | None = None,
    session: Optional[ClientSession] = None,
)

              flowchart TD
              bitcart.coins.trx.TRX[TRX]
              bitcart.coins.eth.ETH[ETH]
              bitcart.coins.btc.BTC[BTC]
              bitcart.coin.Coin[Coin]
              bitcart.event_delivery.EventDelivery[EventDelivery]

                              bitcart.coins.eth.ETH --> bitcart.coins.trx.TRX
                                bitcart.coins.btc.BTC --> bitcart.coins.eth.ETH
                                bitcart.coin.Coin --> bitcart.coins.btc.BTC
                
                bitcart.event_delivery.EventDelivery --> bitcart.coins.btc.BTC
                




              click bitcart.coins.trx.TRX href "" "bitcart.coins.trx.TRX"
              click bitcart.coins.eth.ETH href "" "bitcart.coins.eth.ETH"
              click bitcart.coins.btc.BTC href "" "bitcart.coins.btc.BTC"
              click bitcart.coin.Coin href "" "bitcart.coin.Coin"
              click bitcart.event_delivery.EventDelivery href "" "bitcart.event_delivery.EventDelivery"
            
Source code in bitcart/coins/btc.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def __init__(
    self,
    rpc_url: str | None = None,
    rpc_user: str | None = None,
    rpc_pass: str | None = None,
    xpub: str | None = None,
    proxy: str | None = None,
    session: Optional["ClientSession"] = None,
):
    super().__init__()
    self.symbol = self.coin_name
    self.rpc_url = rpc_url or self.RPC_URL
    self.rpc_user = rpc_user or self.RPC_USER
    self.rpc_pass = rpc_pass or self.RPC_PASS
    self.xpub = xpub
    self.event_handlers: dict[str, Callable] = {}
    self.amount_field = getattr(self, "AMOUNT_FIELD", f"amount_{self.coin_name}")
    self.server = RPCProxy(self.rpc_url, self.rpc_user, self.rpc_pass, self.xpub, session=session, proxy=proxy)

XRG

XRG supports Schnorr signatures, they are enabled out of the box

XRG

XRG(
    rpc_url: str | None = None,
    rpc_user: str | None = None,
    rpc_pass: str | None = None,
    xpub: str | None = None,
    proxy: str | None = None,
    session: Optional[ClientSession] = None,
)

              flowchart TD
              bitcart.coins.xrg.XRG[XRG]
              bitcart.coins.bch.BCH[BCH]
              bitcart.coins.btc.BTC[BTC]
              bitcart.coin.Coin[Coin]
              bitcart.event_delivery.EventDelivery[EventDelivery]

                              bitcart.coins.bch.BCH --> bitcart.coins.xrg.XRG
                                bitcart.coins.btc.BTC --> bitcart.coins.bch.BCH
                                bitcart.coin.Coin --> bitcart.coins.btc.BTC
                
                bitcart.event_delivery.EventDelivery --> bitcart.coins.btc.BTC
                




              click bitcart.coins.xrg.XRG href "" "bitcart.coins.xrg.XRG"
              click bitcart.coins.bch.BCH href "" "bitcart.coins.bch.BCH"
              click bitcart.coins.btc.BTC href "" "bitcart.coins.btc.BTC"
              click bitcart.coin.Coin href "" "bitcart.coin.Coin"
              click bitcart.event_delivery.EventDelivery href "" "bitcart.event_delivery.EventDelivery"
            
Source code in bitcart/coins/btc.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def __init__(
    self,
    rpc_url: str | None = None,
    rpc_user: str | None = None,
    rpc_pass: str | None = None,
    xpub: str | None = None,
    proxy: str | None = None,
    session: Optional["ClientSession"] = None,
):
    super().__init__()
    self.symbol = self.coin_name
    self.rpc_url = rpc_url or self.RPC_URL
    self.rpc_user = rpc_user or self.RPC_USER
    self.rpc_pass = rpc_pass or self.RPC_PASS
    self.xpub = xpub
    self.event_handlers: dict[str, Callable] = {}
    self.amount_field = getattr(self, "AMOUNT_FIELD", f"amount_{self.coin_name}")
    self.server = RPCProxy(self.rpc_url, self.rpc_user, self.rpc_pass, self.xpub, session=session, proxy=proxy)

LTC

LTC class supports lightning out of the box. For lightning methods to work, it must be enabled from the daemon (enabled by default and edited by LTC_LIGHTNING environment variable). If lightning is disabled, LightningDisabledError is raised when calling lightning methods.

LTC

LTC(
    rpc_url: str | None = None,
    rpc_user: str | None = None,
    rpc_pass: str | None = None,
    xpub: str | None = None,
    proxy: str | None = None,
    session: Optional[ClientSession] = None,
)

              flowchart TD
              bitcart.coins.ltc.LTC[LTC]
              bitcart.coins.btc.BTC[BTC]
              bitcart.coin.Coin[Coin]
              bitcart.event_delivery.EventDelivery[EventDelivery]

                              bitcart.coins.btc.BTC --> bitcart.coins.ltc.LTC
                                bitcart.coin.Coin --> bitcart.coins.btc.BTC
                
                bitcart.event_delivery.EventDelivery --> bitcart.coins.btc.BTC
                



              click bitcart.coins.ltc.LTC href "" "bitcart.coins.ltc.LTC"
              click bitcart.coins.btc.BTC href "" "bitcart.coins.btc.BTC"
              click bitcart.coin.Coin href "" "bitcart.coin.Coin"
              click bitcart.event_delivery.EventDelivery href "" "bitcart.event_delivery.EventDelivery"
            
Source code in bitcart/coins/btc.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def __init__(
    self,
    rpc_url: str | None = None,
    rpc_user: str | None = None,
    rpc_pass: str | None = None,
    xpub: str | None = None,
    proxy: str | None = None,
    session: Optional["ClientSession"] = None,
):
    super().__init__()
    self.symbol = self.coin_name
    self.rpc_url = rpc_url or self.RPC_URL
    self.rpc_user = rpc_user or self.RPC_USER
    self.rpc_pass = rpc_pass or self.RPC_PASS
    self.xpub = xpub
    self.event_handlers: dict[str, Callable] = {}
    self.amount_field = getattr(self, "AMOUNT_FIELD", f"amount_{self.coin_name}")
    self.server = RPCProxy(self.rpc_url, self.rpc_user, self.rpc_pass, self.xpub, session=session, proxy=proxy)

GRS

GRS class supports lightning out of the box. For lightning methods to work, it must be enabled from the daemon (enabled by default and edited by GRS_LIGHTNING environment variable). If lightning is disabled, LightningDisabledError is raised when calling lightning methods.

GRS

GRS(
    rpc_url: str | None = None,
    rpc_user: str | None = None,
    rpc_pass: str | None = None,
    xpub: str | None = None,
    proxy: str | None = None,
    session: Optional[ClientSession] = None,
)

              flowchart TD
              bitcart.coins.grs.GRS[GRS]
              bitcart.coins.btc.BTC[BTC]
              bitcart.coin.Coin[Coin]
              bitcart.event_delivery.EventDelivery[EventDelivery]

                              bitcart.coins.btc.BTC --> bitcart.coins.grs.GRS
                                bitcart.coin.Coin --> bitcart.coins.btc.BTC
                
                bitcart.event_delivery.EventDelivery --> bitcart.coins.btc.BTC
                



              click bitcart.coins.grs.GRS href "" "bitcart.coins.grs.GRS"
              click bitcart.coins.btc.BTC href "" "bitcart.coins.btc.BTC"
              click bitcart.coin.Coin href "" "bitcart.coin.Coin"
              click bitcart.event_delivery.EventDelivery href "" "bitcart.event_delivery.EventDelivery"
            
Source code in bitcart/coins/btc.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def __init__(
    self,
    rpc_url: str | None = None,
    rpc_user: str | None = None,
    rpc_pass: str | None = None,
    xpub: str | None = None,
    proxy: str | None = None,
    session: Optional["ClientSession"] = None,
):
    super().__init__()
    self.symbol = self.coin_name
    self.rpc_url = rpc_url or self.RPC_URL
    self.rpc_user = rpc_user or self.RPC_USER
    self.rpc_pass = rpc_pass or self.RPC_PASS
    self.xpub = xpub
    self.event_handlers: dict[str, Callable] = {}
    self.amount_field = getattr(self, "AMOUNT_FIELD", f"amount_{self.coin_name}")
    self.server = RPCProxy(self.rpc_url, self.rpc_user, self.rpc_pass, self.xpub, session=session, proxy=proxy)

Utilities

utils

Functions:

  • bitcoins

    Convert amount from satoshis to bitcoins

  • call_universal

    Call a function: async or sync one. All passed arguments are passed to the function too

  • convert_amount_type

    Convert amount from str to Decimal

  • json_encode

    json.dumps supporting Decimals

  • satoshis

    Convert amount from bitcoins to satoshis

bitcoins
bitcoins(amount: int) -> Decimal

Convert amount from satoshis to bitcoins

Parameters:

  • amount
    (int) –

    amount in satoshis

Returns:

  • Decimal ( Decimal ) –

    amount in bitcoins

Source code in bitcart/utils.py
39
40
41
42
43
44
45
46
47
48
def bitcoins(amount: int) -> Decimal:
    """Convert amount from satoshis to bitcoins

    Args:
        amount (int): amount in satoshis

    Returns:
        Decimal: amount in bitcoins
    """
    return Decimal(amount) / Decimal(CONVERT_RATE)
call_universal async
call_universal(func: Callable, *args: Any, **kwargs: Any) -> Any

Call a function: async or sync one. All passed arguments are passed to the function too

Parameters:

  • func
    (Callable) –

    a function to call: either sync or async one

Returns:

  • Any ( Any ) –

    function execution result

Source code in bitcart/utils.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
async def call_universal(func: Callable, *args: Any, **kwargs: Any) -> Any:
    """Call a function: async or sync one. All passed arguments are passed to the function too

    Args:
        func (Callable): a function to call: either sync or async one

    Returns:
        Any: function execution result
    """
    try:
        result = func(*args, **kwargs)
        if inspect.isawaitable(result):
            result = await result
        return result
    except Exception:
        logger.error(f"Error occured:\n{traceback.format_exc()}")
convert_amount_type
convert_amount_type(amount: str | Decimal) -> Decimal

Convert amount from str to Decimal

Parameters:

  • amount
    (Union[str, Decimal]) –

    amount

Returns:

  • Decimal

    Decimal

Source code in bitcart/utils.py
13
14
15
16
17
18
19
20
21
22
23
24
def convert_amount_type(amount: str | Decimal) -> Decimal:
    """Convert amount from str to Decimal

    Args:
        amount (Union[str, Decimal]): amount

    Returns:
        Decimal
    """
    if amount == "None":
        return Decimal("Nan")
    return Decimal(amount)
json_encode
json_encode(obj: Any) -> Any

json.dumps supporting Decimals

Parameters:

  • obj
    (Any) –

    any object

Returns:

  • Any ( Any ) –

    return value of json.dumps

Source code in bitcart/utils.py
58
59
60
61
62
63
64
65
66
67
def json_encode(obj: Any) -> Any:
    """json.dumps supporting Decimals

    Args:
        obj (Any): any object

    Returns:
        Any: return value of json.dumps
    """
    return json.dumps(obj, cls=CustomJSONEncoder)
satoshis
satoshis(amount: str | Decimal) -> int

Convert amount from bitcoins to satoshis

Parameters:

  • amount
    (Union[str, Decimal]) –

    bitcoin amount

Returns:

  • int ( int ) –

    same amount in satoshis

Source code in bitcart/utils.py
27
28
29
30
31
32
33
34
35
36
def satoshis(amount: str | Decimal) -> int:
    """Convert amount from bitcoins to satoshis

    Args:
        amount (Union[str, Decimal]): bitcoin amount

    Returns:
        int: same amount in satoshis
    """
    return int(convert_amount_type(amount) * CONVERT_RATE)