eth

package
v0.6.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 7, 2023 License: BlueOak-1.0.0 Imports: 59 Imported by: 1

Documentation

Overview

Package eth implements methods to work with ethereum swap contracts and transactions. The LGPL is a more restrictive license that may be more of a burden for closed source software.

Index

Constants

View Source
const (
	// BipID is the BIP-0044 asset ID.
	BipID = 60
)

Variables

View Source
var (
	WalletOpts = []*asset.ConfigOption{
		{
			Key:         "gasfeelimit",
			DisplayName: "Gas Fee Limit",
			Description: "This is the highest network fee rate you are willing to " +
				"pay on swap transactions. If gasfeelimit is lower than a market's " +
				"maxfeerate, you will not be able to trade on that market with this " +
				"wallet.  Units: gwei / gas",
			DefaultValue: defaultGasFeeLimit,
		},
	}
	RPCOpts = []*asset.ConfigOption{
		{
			Key:         providersKey,
			DisplayName: "Provider",
			Description: "Specify one or more providers. For infrastructure " +
				"providers, prefer using wss address. Only url-based authentication " +
				"is supported. For a local node, use the filepath to an IPC file.",
			Repeatable: providerDelimiter,
			RepeatN:    2,
			Required:   true,
		},
	}
	// WalletInfo defines some general information about a Ethereum wallet.
	WalletInfo = &asset.WalletInfo{
		Name:    "Ethereum",
		Version: 0,

		SupportedVersions: []uint32{0},
		UnitInfo:          dexeth.UnitInfo,
		AvailableWallets: []*asset.WalletDefinition{

			{
				Type:        walletTypeRPC,
				Tab:         "External",
				Description: "Infrastructure providers (e.g. Infura) or local nodes",
				ConfigOpts:  append(RPCOpts, WalletOpts...),
				Seeded:      true,
				NoAuth:      true,
				GuideLink:   "https://github.com/decred/dcrdex/blob/master/docs/wiki/Ethereum.md",
			},
		},
	}
)

Functions

func CreateWallet

func CreateWallet(cfg *asset.CreateWalletParams) error

CreateWallet creates a new internal ETH wallet and stores the private key derived from the wallet seed.

func GetGasEstimates

func GetGasEstimates(ctx context.Context, cl ethFetcher, c contractor, maxSwaps int, g *dexeth.Gases,
	toAddress common.Address, waitForMined func(), waitForReceipt func(ethFetcher, *types.Transaction) (*types.Receipt, error)) error

getGasEstimate is used to get a gas table for an asset's contract(s). The provided gases, g, should be generous estimates of what the gas might be. Errors are thrown if the provided estimates are too small by more than a factor of 2. The account should already have a trading balance of at least maxSwaps gwei (token or eth), and sufficient eth balance to cover the requisite tx fees.

Types

type Balance

type Balance struct {
	Current, PendingIn, PendingOut *big.Int
}

Balance is the current balance, including information about the pending balance.

type Driver

type Driver struct{}

Driver implements asset.Driver.

func (*Driver) Create

func (d *Driver) Create(params *asset.CreateWalletParams) error

func (*Driver) DecodeCoinID

func (d *Driver) DecodeCoinID(coinID []byte) (string, error)

DecodeCoinID creates a human-readable representation of a coin ID for Ethereum. These are supported coin ID formats:

  1. A transaction hash. 32 bytes
  2. An encoded ETH funding coin id which includes the account address and amount. 20 + 8 = 28 bytes
  3. An encoded token funding coin id which includes the account address, a token value, and fees. 20 + 8 + 8 = 36 bytes
  4. A byte encoded string of the account address. 40 or 42 (with 0x) bytes
  5. A byte encoded string which represents specific case where Taker found Maker redemption on his own (while Maker failed to notify him about it first). 26 (`TakerFoundMakerRedemption:` prefix) + 42 (Maker address with 0x) bytes

func (*Driver) Exists

func (d *Driver) Exists(walletType, dataDir string, settings map[string]string, net dex.Network) (bool, error)

Exists checks the existence of the wallet.

func (*Driver) Info

func (d *Driver) Info() *asset.WalletInfo

Info returns basic information about the wallet and asset.

func (*Driver) Open

func (d *Driver) Open(cfg *asset.WalletConfig, logger dex.Logger, network dex.Network) (asset.Wallet, error)

Open opens the ETH exchange wallet. Start the wallet with its Run method.

type ETHWallet

type ETHWallet struct {
	// contains filtered or unexported fields
}

ETHWallet implements some Ethereum-specific methods.

func NewWallet

func NewWallet(assetCFG *asset.WalletConfig, logger dex.Logger, net dex.Network) (w *ETHWallet, err error)

NewWallet is the exported constructor by which the DEX will import the exchange wallet.

func (ETHWallet) AuditContract

func (w ETHWallet) AuditContract(coinID, contract, serializedTx dex.Bytes, rebroadcast bool) (*asset.AuditInfo, error)

AuditContract retrieves information about a swap contract on the blockchain. This would be used to verify the counter-party's contract during a swap. coinID is expected to be the transaction id, and must be the same as the hash of serializedTx. contract is expected to be (contractVersion|secretHash) where the secretHash uniquely keys the swap.

func (ETHWallet) Balance

func (w ETHWallet) Balance() (*asset.Balance, error)

Balance returns the available and locked funds (token or eth).

func (*ETHWallet) ConfirmRedemption

func (w *ETHWallet) ConfirmRedemption(coinID dex.Bytes, redemption *asset.Redemption) (*asset.ConfirmRedemptionStatus, error)

ConfirmRedemption checks the status of a redemption. If it is determined that a transaction will not be mined, this function will submit a new transaction to replace the old one. The caller is notified of this by having a different coinID in the returned asset.ConfirmRedemptionStatus as was used to call the function.

func (*ETHWallet) Connect

func (w *ETHWallet) Connect(ctx context.Context) (_ *sync.WaitGroup, err error)

Connect connects to the node RPC server. Satisfies dex.Connector.

func (ETHWallet) ContractLockTimeExpired

func (w ETHWallet) ContractLockTimeExpired(ctx context.Context, contract dex.Bytes) (bool, time.Time, error)

ContractLockTimeExpired returns true if the specified contract's locktime has expired, making it possible to issue a Refund.

func (ETHWallet) DynamicRedemptionFeesPaid

func (eth ETHWallet) DynamicRedemptionFeesPaid(ctx context.Context, coinID, contractData dex.Bytes) (fee uint64, secretHashes [][]byte, err error)

DynamicRedemptionFeesPaid returns fees for redemption transactions. Part of the asset.DynamicSwapOrRedemptionFeeChecker interface.

func (ETHWallet) DynamicSwapFeesPaid

func (eth ETHWallet) DynamicSwapFeesPaid(ctx context.Context, coinID, contractData dex.Bytes) (fee uint64, secretHashes [][]byte, err error)

DynamicSwapFeesPaid returns fees for initiation transactions. Part of the asset.DynamicSwapOrRedemptionFeeChecker interface.

func (*ETHWallet) EstimateRegistrationTxFee

func (w *ETHWallet) EstimateRegistrationTxFee(feeRate uint64) uint64

EstimateRegistrationTxFee returns an estimate for the tx fee needed to pay the registration fee using the provided feeRate.

func (*ETHWallet) EstimateSendTxFee

func (w *ETHWallet) EstimateSendTxFee(addr string, value, _ uint64, subtract bool) (uint64, bool, error)

EstimateSendTxFee returns a tx fee estimate for a send tx. The provided fee rate is ignored since all sends will use an internally derived fee rate. If an address is provided, it will ensure wallet has enough to cover total spend.

func (ETHWallet) FindRedemption

func (w ETHWallet) FindRedemption(ctx context.Context, _, contract dex.Bytes) (redemptionCoin, secret dex.Bytes, err error)

FindRedemption checks the contract for a redemption. If the swap is initiated but un-redeemed and un-refunded, FindRedemption will block until a redemption is seen.

func (*ETHWallet) FundOrder

func (w *ETHWallet) FundOrder(ord *asset.Order) (asset.Coins, []dex.Bytes, error)

FundOrder locks value for use in an order.

func (*ETHWallet) FundingCoins

func (w *ETHWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error)

FundingCoins gets funding coins for the coin IDs. The coins are locked. This method might be called to reinitialize an order from data stored externally.

func (*ETHWallet) Info

func (w *ETHWallet) Info() *asset.WalletInfo

Info returns basic information about the wallet and asset.

func (*ETHWallet) Lock

func (eth *ETHWallet) Lock() error

Lock locks the exchange wallet.

func (ETHWallet) LockTimeExpired

func (w ETHWallet) LockTimeExpired(ctx context.Context, lockTime time.Time) (bool, error)

LockTimeExpired returns true if the specified locktime has expired, making it possible to redeem the locked coins.

func (*ETHWallet) MaxOrder

func (w *ETHWallet) MaxOrder(ord *asset.MaxOrderForm) (*asset.SwapEstimate, error)

MaxOrder generates information about the maximum order size and associated fees that the wallet can support for the given DEX configuration. The fees are an estimate based on current network conditions, and will be <= the fees associated with nfo.MaxFeeRate. For quote assets, the caller will have to calculate lotSize based on a rate conversion from the base asset's lot size.

func (*ETHWallet) OpenTokenWallet

func (w *ETHWallet) OpenTokenWallet(tokenCfg *asset.TokenConfig) (asset.Wallet, error)

OpenTokenWallet creates a new TokenWallet.

func (ETHWallet) PreRedeem

func (w ETHWallet) PreRedeem(req *asset.PreRedeemForm) (*asset.PreRedeem, error)

PreRedeem generates an estimate of the range of redemption fees that could be assessed.

func (*ETHWallet) PreSwap

func (w *ETHWallet) PreSwap(req *asset.PreSwapForm) (*asset.PreSwap, error)

PreSwap gets order estimates based on the available funds and the wallet configuration.

func (*ETHWallet) ReReserveRedemption

func (w *ETHWallet) ReReserveRedemption(req uint64) error

ReReserveRedemption checks out an amount for redemptions. Use ReReserveRedemption after initializing a new asset.Wallet. Part of the AccountLocker interface.

func (*ETHWallet) ReReserveRefund

func (w *ETHWallet) ReReserveRefund(req uint64) error

ReReserveRefund checks out an amount for doing refunds. Use ReReserveRefund after initializing a new assetWallet. Part of the AccountLocker interface.

func (*ETHWallet) Reconfigure

func (w *ETHWallet) Reconfigure(ctx context.Context, cfg *asset.WalletConfig, currentAddress string) (restart bool, err error)

Reconfigure attempts to reconfigure the wallet.

func (*ETHWallet) Redeem

func (w *ETHWallet) Redeem(form *asset.RedeemForm) ([]dex.Bytes, asset.Coin, uint64, error)

Redeem sends the redemption transaction, which may contain more than one redemption. All redemptions must be for the same contract version because the current API requires a single transaction reported (asset.Coin output), but conceptually a batch of redeems could be processed for any number of different contract addresses with multiple transactions. (buck: what would the difference from calling Redeem repeatedly?)

func (ETHWallet) Refund

func (w ETHWallet) Refund(_, contract dex.Bytes, feeRate uint64) (dex.Bytes, error)

Refund refunds a contract. This can only be used after the time lock has expired.

func (*ETHWallet) ReserveNRedemptions

func (w *ETHWallet) ReserveNRedemptions(n uint64, ver uint32, maxFeeRate uint64) (uint64, error)

ReserveNRedemptions locks funds for redemption. It is an error if there is insufficient spendable balance. Part of the AccountLocker interface.

func (*ETHWallet) ReserveNRefunds

func (w *ETHWallet) ReserveNRefunds(n uint64, ver uint32, maxFeeRate uint64) (uint64, error)

ReserveNRefunds locks funds for doing refunds. It is an error if there is insufficient spendable balance. Part of the AccountLocker interface.

func (ETHWallet) RestorationInfo

func (w ETHWallet) RestorationInfo(seed []byte) ([]*asset.WalletRestoration, error)

RestorationInfo returns information about how to restore the wallet in various external wallets.

func (*ETHWallet) ReturnCoins

func (w *ETHWallet) ReturnCoins(coins asset.Coins) error

ReturnCoins unlocks coins. This would be necessary in the case of a canceled order.

func (*ETHWallet) Send

func (w *ETHWallet) Send(addr string, value, _ uint64) (asset.Coin, error)

Send sends the exact value to the specified address. The provided fee rate is ignored since all sends will use an internally derived fee rate.

func (ETHWallet) SingleLotRedeemFees

func (w ETHWallet) SingleLotRedeemFees(form *asset.PreRedeemForm) (fees uint64, err error)

SingleLotRedeemFees is a fallback for PreRedeem that uses estimation when funds aren't available. The returned fees are the RealisticWorstCase. The Lots field of the PreSwapForm is ignored and assumed to be a single lot.

func (ETHWallet) SingleLotSwapFees

func (w ETHWallet) SingleLotSwapFees(form *asset.PreSwapForm) (fees uint64, err error)

SingleLotSwapFees is a fallback for PreSwap that uses estimation when funds aren't available. The returned fees are the RealisticWorstCase. The Lots field of the PreSwapForm is ignored and assumed to be a single lot.

func (*ETHWallet) Swap

func (w *ETHWallet) Swap(swaps *asset.Swaps) ([]asset.Receipt, asset.Coin, uint64, error)

Swap sends the swaps in a single transaction. The fees used returned are the max fees that will possibly be used, since in ethereum with EIP-1559 we cannot know exactly how much fees will be used.

func (ETHWallet) SwapConfirmations

func (w ETHWallet) SwapConfirmations(ctx context.Context, coinID dex.Bytes, contract dex.Bytes, _ time.Time) (confs uint32, spent bool, err error)

SwapConfirmations gets the number of confirmations and the spend status for the specified swap.

func (*ETHWallet) UnlockRedemptionReserves

func (w *ETHWallet) UnlockRedemptionReserves(reserves uint64)

UnlockRedemptionReserves unlocks the specified amount from redemption reserves. Part of the AccountLocker interface.

func (*ETHWallet) UnlockRefundReserves

func (w *ETHWallet) UnlockRefundReserves(reserves uint64)

UnlockRefundReserves unlocks the specified amount from refund reserves. Part of the AccountLocker interface.

func (*ETHWallet) ValidateAddress

func (w *ETHWallet) ValidateAddress(address string) bool

ValidateAddress checks whether the provided address is a valid hex-encoded Ethereum address.

type TokenWallet

type TokenWallet struct {
	// contains filtered or unexported fields
}

TokenWallet implements some token-specific methods.

func (TokenWallet) AuditContract

func (w TokenWallet) AuditContract(coinID, contract, serializedTx dex.Bytes, rebroadcast bool) (*asset.AuditInfo, error)

AuditContract retrieves information about a swap contract on the blockchain. This would be used to verify the counter-party's contract during a swap. coinID is expected to be the transaction id, and must be the same as the hash of serializedTx. contract is expected to be (contractVersion|secretHash) where the secretHash uniquely keys the swap.

func (TokenWallet) Balance

func (w TokenWallet) Balance() (*asset.Balance, error)

Balance returns the available and locked funds (token or eth).

func (*TokenWallet) ConfirmRedemption

func (w *TokenWallet) ConfirmRedemption(coinID dex.Bytes, redemption *asset.Redemption) (*asset.ConfirmRedemptionStatus, error)

ConfirmRedemption checks the status of a redemption. If it is determined that a transaction will not be mined, this function will submit a new transaction to replace the old one. The caller is notified of this by having a different coinID in the returned asset.ConfirmRedemptionStatus as was used to call the function.

func (*TokenWallet) Connect

func (w *TokenWallet) Connect(ctx context.Context) (*sync.WaitGroup, error)

Connect waits for context cancellation and closes the WaitGroup. Satisfies dex.Connector.

func (TokenWallet) ContractLockTimeExpired

func (w TokenWallet) ContractLockTimeExpired(ctx context.Context, contract dex.Bytes) (bool, time.Time, error)

ContractLockTimeExpired returns true if the specified contract's locktime has expired, making it possible to issue a Refund.

func (TokenWallet) DynamicRedemptionFeesPaid

func (eth TokenWallet) DynamicRedemptionFeesPaid(ctx context.Context, coinID, contractData dex.Bytes) (fee uint64, secretHashes [][]byte, err error)

DynamicRedemptionFeesPaid returns fees for redemption transactions. Part of the asset.DynamicSwapOrRedemptionFeeChecker interface.

func (TokenWallet) DynamicSwapFeesPaid

func (eth TokenWallet) DynamicSwapFeesPaid(ctx context.Context, coinID, contractData dex.Bytes) (fee uint64, secretHashes [][]byte, err error)

DynamicSwapFeesPaid returns fees for initiation transactions. Part of the asset.DynamicSwapOrRedemptionFeeChecker interface.

func (*TokenWallet) EstimateRegistrationTxFee

func (w *TokenWallet) EstimateRegistrationTxFee(feeRate uint64) uint64

EstimateRegistrationTxFee returns an estimate for the tx fee needed to pay the registration fee using the provided feeRate.

func (*TokenWallet) EstimateSendTxFee

func (w *TokenWallet) EstimateSendTxFee(addr string, value, _ uint64, subtract bool) (fee uint64, isValidAddress bool, err error)

EstimateSendTxFee returns a tx fee estimate for a send tx. The provided fee rate is ignored since all sends will use an internally derived fee rate. If an address is provided, it will ensure wallet has enough to cover total spend.

func (TokenWallet) FindRedemption

func (w TokenWallet) FindRedemption(ctx context.Context, _, contract dex.Bytes) (redemptionCoin, secret dex.Bytes, err error)

FindRedemption checks the contract for a redemption. If the swap is initiated but un-redeemed and un-refunded, FindRedemption will block until a redemption is seen.

func (*TokenWallet) FundOrder

func (w *TokenWallet) FundOrder(ord *asset.Order) (asset.Coins, []dex.Bytes, error)

FundOrder locks value for use in an order.

func (*TokenWallet) FundingCoins

func (w *TokenWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error)

FundingCoins gets funding coins for the coin IDs. The coins are locked. This method might be called to reinitialize an order from data stored externally.

func (*TokenWallet) Info

func (w *TokenWallet) Info() *asset.WalletInfo

Info returns basic information about the wallet and asset.

func (*TokenWallet) Lock

func (eth *TokenWallet) Lock() error

Lock does nothing for tokens. See above TODO.

func (TokenWallet) LockTimeExpired

func (w TokenWallet) LockTimeExpired(ctx context.Context, lockTime time.Time) (bool, error)

LockTimeExpired returns true if the specified locktime has expired, making it possible to redeem the locked coins.

func (*TokenWallet) MaxOrder

func (w *TokenWallet) MaxOrder(ord *asset.MaxOrderForm) (*asset.SwapEstimate, error)

MaxOrder generates information about the maximum order size and associated fees that the wallet can support for the given DEX configuration.

func (TokenWallet) PreRedeem

func (w TokenWallet) PreRedeem(req *asset.PreRedeemForm) (*asset.PreRedeem, error)

PreRedeem generates an estimate of the range of redemption fees that could be assessed.

func (*TokenWallet) PreSwap

func (w *TokenWallet) PreSwap(req *asset.PreSwapForm) (*asset.PreSwap, error)

PreSwap gets order estimates based on the available funds and the wallet configuration.

func (*TokenWallet) ReReserveRedemption

func (w *TokenWallet) ReReserveRedemption(req uint64) error

ReReserveRedemption checks out an amount for redemptions. Use ReReserveRedemption after initializing a new asset.Wallet. Part of the AccountLocker interface.

func (*TokenWallet) ReReserveRefund

func (w *TokenWallet) ReReserveRefund(req uint64) error

ReReserveRefund checks out an amount for doing refunds. Use ReReserveRefund after initializing a new assetWallet. Part of the AccountLocker interface.

func (*TokenWallet) Reconfigure

func (w *TokenWallet) Reconfigure(context.Context, *asset.WalletConfig, string) (bool, error)

Reconfigure attempts to reconfigure the wallet. The token wallet has no configurations.

func (*TokenWallet) Redeem

func (w *TokenWallet) Redeem(form *asset.RedeemForm) ([]dex.Bytes, asset.Coin, uint64, error)

Redeem sends the redemption transaction, which may contain more than one redemption.

func (TokenWallet) Refund

func (w TokenWallet) Refund(_, contract dex.Bytes, feeRate uint64) (dex.Bytes, error)

Refund refunds a contract. This can only be used after the time lock has expired.

func (*TokenWallet) ReserveNRedemptions

func (w *TokenWallet) ReserveNRedemptions(n uint64, ver uint32, maxFeeRate uint64) (uint64, error)

ReserveNRedemptions locks funds for redemption. It is an error if there is insufficient spendable balance. If an approval is necessary to increase the allowance to facilitate redemption, the approval is performed here. Part of the AccountLocker interface.

func (*TokenWallet) ReserveNRefunds

func (w *TokenWallet) ReserveNRefunds(n uint64, ver uint32, maxFeeRate uint64) (uint64, error)

ReserveNRefunds locks funds for doing refunds. It is an error if there is insufficient spendable balance. Part of the AccountLocker interface.

func (TokenWallet) RestorationInfo

func (w TokenWallet) RestorationInfo(seed []byte) ([]*asset.WalletRestoration, error)

RestorationInfo returns information about how to restore the wallet in various external wallets.

func (*TokenWallet) ReturnCoins

func (w *TokenWallet) ReturnCoins(coins asset.Coins) error

ReturnCoins unlocks coins. This would be necessary in the case of a canceled order.

func (*TokenWallet) Send

func (w *TokenWallet) Send(addr string, value, _ uint64) (asset.Coin, error)

Send sends the exact value to the specified address. Fees are taken from the parent wallet. The provided fee rate is ignored since all sends will use an internally derived fee rate.

func (TokenWallet) SingleLotRedeemFees

func (w TokenWallet) SingleLotRedeemFees(form *asset.PreRedeemForm) (fees uint64, err error)

SingleLotRedeemFees is a fallback for PreRedeem that uses estimation when funds aren't available. The returned fees are the RealisticWorstCase. The Lots field of the PreSwapForm is ignored and assumed to be a single lot.

func (TokenWallet) SingleLotSwapFees

func (w TokenWallet) SingleLotSwapFees(form *asset.PreSwapForm) (fees uint64, err error)

SingleLotSwapFees is a fallback for PreSwap that uses estimation when funds aren't available. The returned fees are the RealisticWorstCase. The Lots field of the PreSwapForm is ignored and assumed to be a single lot.

func (*TokenWallet) Swap

func (w *TokenWallet) Swap(swaps *asset.Swaps) ([]asset.Receipt, asset.Coin, uint64, error)

Swap sends the swaps in a single transaction. The fees used returned are the max fees that will possibly be used, since in ethereum with EIP-1559 we cannot know exactly how much fees will be used.

func (TokenWallet) SwapConfirmations

func (w TokenWallet) SwapConfirmations(ctx context.Context, coinID dex.Bytes, contract dex.Bytes, _ time.Time) (confs uint32, spent bool, err error)

SwapConfirmations gets the number of confirmations and the spend status for the specified swap.

func (*TokenWallet) UnlockRedemptionReserves

func (w *TokenWallet) UnlockRedemptionReserves(reserves uint64)

UnlockRedemptionReserves unlocks the specified amount from redemption reserves. Part of the AccountLocker interface.

func (*TokenWallet) UnlockRefundReserves

func (w *TokenWallet) UnlockRefundReserves(reserves uint64)

UnlockRefundReserves unlocks the specified amount from refund reserves. Part of the AccountLocker interface.

func (*TokenWallet) ValidateAddress

func (w *TokenWallet) ValidateAddress(address string) bool

ValidateAddress checks whether the provided address is a valid hex-encoded Ethereum address.

type WalletConfig

type WalletConfig struct {
	GasFeeLimit uint64 `ini:"gasfeelimit"`
}

WalletConfig are wallet-level configuration settings.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL