Ethereum THORChain swaps

Only native ETH supported for now.  Work on ERC20 token swaps is underway.

Sample create-sign-send workflow for a BTC->ETH swap (assumes offline
autosigning is set up):

    $ mmgen-swaptxcreate --autosign BTC 0.12345 ETH

    remove device - insert - wait for signing - remove - insert

    $ mmgen-txsend --autosign

Create step for ETH->BTC swap:

    $ mmgen-swaptxcreate --autosign ETH 5.4321 BTC

For more information, see:

    $ mmgen-swaptxcreate --help

Testing:

    $ test/cmdtest.py ethswap
This commit is contained in:
The MMGen Project 2025-03-23 09:26:45 +03:00
commit f0563031de
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
27 changed files with 376 additions and 35 deletions

View file

@ -64,8 +64,11 @@
By default, the change and destination addresses are chosen automatically by
finding the lowest-indexed unused addresses of the preferred address types in
the send and receive tracking wallets. Types ‘B’, ‘S’ and ‘C’ (see ADDRESS
TYPES below) are searched in that order for unused addresses.
the send and receive tracking wallets. For Bitcoin and forks, types ‘B’,
‘S’ and ‘C’ (see ADDRESS TYPES below) are searched in that order for unused
addresses. Note that sending to an unused address may be undesirable for
Ethereum, where address (i.e. account) reuse is the norm. In that case, the
user should specify a destination address on the command line.
If the wallet contains eligible unused addresses with multiple Seed IDs, the
user will be presented with a list of the lowest-indexed addresses of
@ -74,7 +77,8 @@
Change and destination addresses may also be specified manually with the
CHG_ADDR and ADDR arguments. These may be given as full MMGen IDs or in the
form ADDRTYPE_CODE or SEED_ID:ADDRTYPE_CODE (see EXAMPLES below and the
‘mmgen-txcreate’ help screen for details).
‘mmgen-txcreate’ help screen for details). For Ethereum, the CHG_ADDR
argument is not supported.
While discouraged, sending change or swapping to non-wallet addresses is also
supported, in which case the signing script (‘mmgen-txsign’ or ‘mmgen-
@ -196,5 +200,5 @@
$ mmgen-tool --coin=bch --bch-rpc-host=gemini twview minconf=0
MMGEN v15.1.dev18 March 2025 MMGEN-SWAPTXCREATE(1)
MMGEN v15.1.dev23 March 2025 MMGEN-SWAPTXCREATE(1)
```

View file

@ -85,8 +85,11 @@
By default, the change and destination addresses are chosen automatically by
finding the lowest-indexed unused addresses of the preferred address types in
the send and receive tracking wallets. Types ‘B’, ‘S’ and ‘C’ (see ADDRESS
TYPES below) are searched in that order for unused addresses.
the send and receive tracking wallets. For Bitcoin and forks, types ‘B’,
‘S’ and ‘C’ (see ADDRESS TYPES below) are searched in that order for unused
addresses. Note that sending to an unused address may be undesirable for
Ethereum, where address (i.e. account) reuse is the norm. In that case, the
user should specify a destination address on the command line.
If the wallet contains eligible unused addresses with multiple Seed IDs, the
user will be presented with a list of the lowest-indexed addresses of
@ -95,7 +98,8 @@
Change and destination addresses may also be specified manually with the
CHG_ADDR and ADDR arguments. These may be given as full MMGen IDs or in the
form ADDRTYPE_CODE or SEED_ID:ADDRTYPE_CODE (see EXAMPLES below and the
‘mmgen-txcreate’ help screen for details).
‘mmgen-txcreate’ help screen for details). For Ethereum, the CHG_ADDR
argument is not supported.
While discouraged, sending change or swapping to non-wallet addresses is also
supported, in which case the signing script (‘mmgen-txsign’ or ‘mmgen-
@ -260,5 +264,5 @@
$ mmgen-tool --coin=bch --bch-rpc-host=gemini twview minconf=0
MMGEN v15.1.dev18 March 2025 MMGEN-SWAPTXDO(1)
MMGEN v15.1.dev23 March 2025 MMGEN-SWAPTXDO(1)
```

View file

@ -1 +1 @@
15.1.dev22
15.1.dev23

View file

@ -41,8 +41,11 @@ inputs will be swapped.
By default, the change and destination addresses are chosen automatically by
finding the lowest-indexed unused addresses of the preferred address types in
the send and receive tracking wallets. Types ‘B’, ‘S’ and ‘C’ (see ADDRESS
TYPES below) are searched in that order for unused addresses.
the send and receive tracking wallets. For Bitcoin and forks, types ‘B’,
‘S’ and ‘C’ (see ADDRESS TYPES below) are searched in that order for unused
addresses. Note that sending to an unused address may be undesirable for
Ethereum, where address (i.e. account) reuse is the norm. In that case, the
user should specify a destination address on the command line.
If the wallet contains eligible unused addresses with multiple Seed IDs, the
user will be presented with a list of the lowest-indexed addresses of
@ -51,7 +54,8 @@ preferred type for each Seed ID and prompted to choose from among them.
Change and destination addresses may also be specified manually with the
CHG_ADDR and ADDR arguments. These may be given as full MMGen IDs or in the
form ADDRTYPE_CODE or SEED_ID:ADDRTYPE_CODE (see EXAMPLES below and the
‘mmgen-txcreate’ help screen for details).
‘mmgen-txcreate’ help screen for details). For Ethereum, the CHG_ADDR
argument is not supported.
While discouraged, sending change or swapping to non-wallet addresses is also
supported, in which case the signing script (‘mmgen-txsign’ or ‘mmgen-

View file

@ -53,6 +53,7 @@ class mainnet(CoinProtocol.Secp256k1): # chainparams.cpp
start_subsidy = 50
max_int = 0xffffffff
max_op_return_data_len = 80
address_reuse_ok = False
coin_cfg_opts = (
'daemon_id',

View file

@ -37,6 +37,8 @@ class mainnet(CoinProtocol.DummyWIF, CoinProtocol.Secp256k1):
base_coin = 'ETH'
avg_bdi = 15
decimal_prec = 36
address_reuse_ok = True
is_evm = True
# https://www.chainid.dev
chain_ids = {

View file

@ -65,8 +65,7 @@ class EthereumTwAddresses(TwAddresses, EthereumTwView, EthereumTwRPC):
async def get_rpc_data(self):
amt0 = self.proto.coin_amt('0')
self.total = amt0
self.total = self.proto.coin_amt('0')
self.minconf = None
addrs = {}
@ -75,7 +74,8 @@ class EthereumTwAddresses(TwAddresses, EthereumTwView, EthereumTwRPC):
addrs[e.label.mmid] = {
'addr': e.coinaddr,
'amt': bal,
'recvd': amt0,
'recvd': bal, # since it’s nearly impossible to empty an Ethereum account,
# we consider a used account to be any account with a balance
'confs': 0,
'lbl': e.label}
self.total += bal

View file

@ -18,6 +18,11 @@ from .base import Base, TokenBase
class Completed(Base, TxBase.Completed):
fn_fee_unit = 'Mwei'
def get_tx_usr_data(self):
o = self.txobj
if o['to'] and o['data']:
return bytes.fromhex(o['data'])
@property
def send_amt(self):
return self.outputs[0].amt if self.outputs else self.proto.coin_amt('0')

View file

@ -49,7 +49,10 @@ class TxInfo(TxInfo):
t = to_addr.hl(0) if to_addr else blue('None'),
a = t['amt'].hl(),
n = t['nonce'].hl(),
d = '{}... ({} bytes)'.format(td[:40], len(td)//2) if len(td) else blue('None'),
d = (
blue('None') if not td
else pink(bytes.fromhex(td).decode()) if tx.is_swap
else '{}... ({} bytes)'.format(td[:40], len(td)//2)),
c = tx.proto.dcoin if len(tx.outputs) else '',
g = yellow(tx.pretty_fmt_fee(t['gasPrice'].to_unit('Gwei'))),
G = yellow(tx.pretty_fmt_fee(t['startGas'].to_unit('Kwei'))),
@ -65,7 +68,7 @@ class TxInfo(TxInfo):
)
def format_verbose_footer(self):
if self.tx.txobj['data']:
if self.tx.txobj['data'] and not self.tx.is_swap:
from ..contract import parse_abi
return '\nParsed contract data: ' + pp_fmt(parse_abi(self.tx.txobj['data']))
else:

View file

@ -28,6 +28,8 @@ class New(Base, TxBase.New):
no_chg_msg = 'Warning: Transaction leaves account with zero balance'
usr_fee_prompt = 'Enter transaction fee or gas price: '
msg_insufficient_funds = 'Account balance insufficient to fund this transaction ({} {} needed)'
byte_cost = 68 # https://ethereum.stackexchange.com/questions/39401/
# how-do-you-calculate-gas-limit-for-transaction-with-data-in-ethereum
def __init__(self, *args, **kwargs):
@ -66,7 +68,7 @@ class New(Base, TxBase.New):
async def create_serialized(self, *, locktime=None):
assert len(self.inputs) == 1, 'Transaction has more than one input!'
o_num = len(self.outputs)
o_ok = 0 if self.usr_contract_data else 1
o_ok = 0 if self.usr_contract_data and not self.is_swap else 1
assert o_num == o_ok, f'Transaction has {o_num} output{suf(o_num)} (should have {o_ok})'
await self.make_txobj()
odict = {k:v if v is None else str(v) for k, v in self.txobj.items() if k != 'token_to'}
@ -78,10 +80,26 @@ class New(Base, TxBase.New):
'update_txid() must be called only when self.serialized is not hex data')
self.txid = MMGenTxID(make_chksum_6(self.serialized).upper())
def set_gas_with_data(self, data):
self.gas = self.proto.coin_amt(self.dfl_gas + self.byte_cost * len(data), from_unit='wei')
# one-shot method
def adj_gas_with_extra_data_len(self, extra_data_len):
if not hasattr(self, '_gas_adjusted'):
self.gas += self.proto.coin_amt(self.byte_cost * extra_data_len, from_unit='wei')
self._gas_adjusted = True
async def process_cmdline_args(self, cmd_args, ad_f, ad_w):
lc = len(cmd_args)
if lc == 2 and self.is_swap:
data_arg = cmd_args.pop()
lc = 1
assert data_arg.startswith('data:'), f'{data_arg}: invalid data arg (must start with "data:")'
self.usr_contract_data = data_arg.removeprefix('data:').encode()
self.set_gas_with_data(self.usr_contract_data)
if lc == 0 and self.usr_contract_data and 'Token' not in self.name:
return
@ -91,9 +109,10 @@ class New(Base, TxBase.New):
a = self.parse_cmdline_arg(self.proto, cmd_args[0], ad_f, ad_w)
self.add_output(
coinaddr = a.addr,
coinaddr = None if a.is_vault else a.addr,
amt = self.proto.coin_amt(a.amt or '0'),
is_chg = not a.amt)
is_chg = not a.amt,
is_vault = a.is_vault)
self.add_mmaddrs_to_outputs(ad_f, ad_w)

38
mmgen/proto/eth/tx/new_swap.py Executable file
View file

@ -0,0 +1,38 @@
#!/usr/bin/env python3
#
# MMGen Wallet, a terminal-based cryptocurrency wallet
# Copyright (C)2013-2025 The MMGen Project <mmgen@tuta.io>
# Licensed under the GNU General Public License, Version 3:
# https://www.gnu.org/licenses
# Public project repositories:
# https://github.com/mmgen/mmgen-wallet
# https://gitlab.com/mmgen/mmgen-wallet
"""
proto.eth.tx.new_swap: Ethereum new swap transaction class
"""
from ....tx.new_swap import NewSwap as TxNewSwap
from ....tx.new_swap import get_swap_proto_mod
from .new import New
class NewSwap(New, TxNewSwap):
desc = 'Ethereum swap transaction'
def update_data_output(self, trade_limit):
sp = get_swap_proto_mod(self.swap_proto)
parsed_memo = sp.data.parse(self.usr_contract_data.decode())
memo = sp.data(
self.recv_proto,
self.recv_proto.coin_addr(parsed_memo.address),
trade_limit = trade_limit)
self.usr_contract_data = str(memo).encode()
self.set_gas_with_data(self.usr_contract_data)
@property
def vault_idx(self):
return 0
@property
def vault_output(self):
return self.outputs[0]

View file

@ -60,7 +60,7 @@ class Status(TxBase.Status):
from ....color import cyan
msg('{}\n{}'.format(cyan('TRANSACTION RECEIPT'), pp_fmt(ret.rx)))
if ret:
if tx.txobj['data']:
if tx.txobj['data'] and not tx.is_swap:
cd = capfirst(tx.contract_desc)
if ret.exec_status == 0:
msg(f'{cd} failed to execute!')

View file

@ -60,7 +60,8 @@ class Unsigned(Completed, TxBase.Unsigned):
if o['data']: # contract-creating transaction
if o['to']:
raise ValueError('contract-creating transaction cannot have to-address')
if not self.is_swap:
raise ValueError('contract-creating transaction cannot have to-address')
else:
self.txobj['token_addr'] = TokenAddr(self.proto, etx.creates.hex())

View file

@ -55,6 +55,7 @@ class CoinProtocol(MMGenObject):
base_coin = None
is_fork_of = None
chain_names = None
is_evm = False
networks = ('mainnet', 'testnet', 'regtest')
decimal_prec = 28
_set_ok = ('tokensym',)

View file

@ -23,11 +23,13 @@ class params:
'BTC': 'Bitcoin',
'LTC': 'Litecoin',
'BCH': 'Bitcoin Cash',
'ETH': 'Ethereum',
},
'receive': {
'BTC': 'Bitcoin',
'LTC': 'Litecoin',
'BCH': 'Bitcoin Cash',
'ETH': 'Ethereum',
}
}

View file

@ -12,7 +12,7 @@
swap.proto.thorchain.memo: THORChain swap protocol memo class
"""
from ....util import die
from ....util import die, is_hex_str
from ....amt import UniAmt
from . import name as proto_name
@ -42,6 +42,8 @@ class Memo:
'THOR.RUNE': 'r',
}
evm_chains = ('ETH', 'AVAX', 'BSC', 'BASE')
function_abbrevs = {
'SWAP': '=',
}
@ -95,6 +97,11 @@ class Memo:
address = get_item('address')
if chain in cls.evm_chains:
assert address.startswith('0x'), f'{address}: address does not start with ‘0x’'
assert len(address) == 42, f'{address}: address has incorrect length ({len(address)} != 42)'
address = address.removeprefix('0x')
desc = 'trade_limit/stream_interval/stream_quantity'
lsq = get_item(desc)
@ -135,6 +142,11 @@ class Memo:
self.addr = addr.views[addr.view_pref]
assert not ':' in self.addr # colon is record separator, so address mustn’t contain one
if self.chain in self.evm_chains:
assert len(self.addr) == 40, f'{self.addr}: address has incorrect length ({len(self.addr)} != 40)'
assert is_hex_str(self.addr), f'{self.addr}: address is not a hexadecimal string'
self.addr = '0x' + self.addr
def __str__(self):
from . import ExpInt4
try:

View file

@ -98,6 +98,8 @@ class Thornode:
{lblcolor('Trade limit:')} {tl_rounded.hl()} {out_coin} """ + mcolor(
f'({abs(1 - ratio) * 100:0.2f}% {direction} expected amount)')
tx_size_adj = len(e.enc) - 1
if tx.proto.is_evm:
tx.adj_gas_with_extra_data_len(len(e.enc) - 1) # one-shot method, no-op if repeated
else:
trade_limit_disp = ''
tx_size_adj = 0
@ -105,7 +107,7 @@ class Thornode:
def get_estimated_fee():
return tx.feespec2abs(
fee_arg = d['recommended_gas_rate'] + gas_unit_data[gas_unit].code,
tx_size = tx.estimate_size() + tx_size_adj)
tx_size = None if tx.proto.is_evm else tx.estimate_size() + tx_size_adj)
_amount_in_label = 'Amount in:'
if deduct_est_fee:
@ -145,7 +147,8 @@ class Thornode:
@property
def inbound_address(self):
return self.data['inbound_address']
addr = self.data['inbound_address']
return addr.removeprefix('0x') if self.tx.proto.is_evm else addr
@property
def rel_fee_hint(self):

View file

@ -74,7 +74,9 @@ class TxInfo:
if tx.is_swap:
from ..swap.proto.thorchain.memo import Memo, proto_name
data = tx.data_output.data
data = (
(tx.usr_contract_data or bytes.fromhex(tx.txobj['data'])) if tx.proto.is_evm
else tx.data_output.data)
if Memo.is_partial_memo(data):
p = Memo.parse(data.decode('ascii'))
yield ' {} {}\n'.format(magenta('DEX Protocol:'), blue(proto_name))

View file

@ -306,6 +306,8 @@ class New(Base):
die(1, 'Exiting at user request')
async def warn_addr_used(self, proto, chg, desc):
if proto.address_reuse_ok:
return
from ..tw.addresses import TwAddresses
if (await TwAddresses(self.cfg, proto, get_data=True)).is_used(chg.addr):
from ..ui import keypress_confirm

View file

@ -97,7 +97,7 @@ class NewSwap(New):
arg = get_arg()
# arg 3: chg_spec (change address spec)
if args.send_amt:
if args.send_amt and not self.proto.is_evm:
if not arg in sp.params.coins['receive']: # is change arg
args.chg_spec = arg
arg = get_arg()
@ -119,7 +119,7 @@ class NewSwap(New):
chg_output = (
await self.get_swap_output(self.proto, args.chg_spec, addrfiles, 'change address')
if args.send_amt else None)
if args.send_amt and not self.proto.is_evm else None)
if chg_output:
self.check_addr_is_wallet_addr(
@ -145,6 +145,7 @@ class NewSwap(New):
self.swap_recv_addr_mmid = recv_output.mmid
return (
[f'vault,{args.send_amt}', f'data:{memo}'] if args.send_amt and self.proto.is_evm else
[f'vault,{args.send_amt}', chg_output.mmid, f'data:{memo}'] if args.send_amt else
['vault', f'data:{memo}'])

Some files were not shown because too many files have changed in this diff Show more