Skip to content

Commit

Permalink
checkpoint. redid server. tests passing. no v1 tests on server yet.
Browse files Browse the repository at this point in the history
  • Loading branch information
buck54321 committed Oct 27, 2023
1 parent fe3fb28 commit cd4866c
Show file tree
Hide file tree
Showing 17 changed files with 904 additions and 587 deletions.
11 changes: 4 additions & 7 deletions client/asset/eth/contractor.go
Original file line number Diff line number Diff line change
Expand Up @@ -585,8 +585,7 @@ func (c *tokenContractorV0) tokenAddress() common.Address {

type contractorV1 struct {
contractV1
abi *abi.ABI
// net dex.Network
abi *abi.ABI
contractAddr common.Address
acctAddr common.Address
cb bind.ContractBackend
Expand All @@ -598,15 +597,13 @@ type contractorV1 struct {
var _ contractor = (*contractorV1)(nil)

func newV1Contractor(net dex.Network, contractAddr, acctAddr common.Address, cb bind.ContractBackend) (contractor, error) {

c, err := swapv1.NewETHSwap(contractAddr, cb)
if err != nil {
return nil, err
}
return &contractorV1{
contractV1: c,
abi: dexeth.ABIs[1],
// net: net,
contractV1: c,
abi: dexeth.ABIs[1],
contractAddr: contractAddr,
acctAddr: acctAddr,
cb: cb,
Expand Down Expand Up @@ -698,7 +695,7 @@ func (c *contractorV1) redeem(txOpts *bind.TransactOpts, redeems []*asset.Redemp

// Not checking version from DecodeLocator because it was already
// audited and incorrect version locator would err below anyway.
_, locator, err := dexeth.DecodeLocator(r.Spends.Contract)
_, locator, err := dexeth.DecodeContractData(r.Spends.Contract)
if err != nil {
return nil, fmt.Errorf("error parsing locator redeem: %w", err)
}
Expand Down
69 changes: 25 additions & 44 deletions client/asset/eth/eth.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,6 @@ const (
// TODO: Find a way to ask the host about their config set max fee and
// gas values.
maxTxFeeGwei = 1_000_000_000

contractVersionERC20 = ^uint32(0)
contractVersionUnknown = contractVersionERC20 - 1
)

var (
Expand Down Expand Up @@ -549,14 +546,7 @@ func privKeyFromSeed(seed []byte) (pk []byte, zero func(), err error) {
// contractVersion converts a server version to a contract version. It applies
// to both tokens and eth right now, but that may not always be the case.
func contractVersion(serverVer uint32) uint32 {
switch serverVer {
case 0:
return 0
case 1:
return 1
default:
return contractVersionUnknown
}
return dexeth.ProtocolVersion(serverVer).ContractVersion()
}

func CreateEVMWallet(chainID int64, createWalletParams *asset.CreateWalletParams, compat *CompatibilityData, skipConnect bool) error {
Expand Down Expand Up @@ -1326,9 +1316,10 @@ func (w *baseWallet) MaxFundingFees(_ uint32, _ uint64, _ map[string]string) uin

// SingleLotSwapRefundFees returns the fees for a swap transaction for a single lot.
func (w *assetWallet) SingleLotSwapRefundFees(serverVer uint32, feeSuggestion uint64, _ bool) (swapFees uint64, refundFees uint64, err error) {
g := w.gases(contractVersion(serverVer))
contractVer := contractVersion(serverVer)
g := w.gases(contractVer)
if g == nil {
return 0, 0, fmt.Errorf("no gases known for %d version %d", w.assetID, serverVer)
return 0, 0, fmt.Errorf("no gases known for %d, contract version %d", w.assetID, contractVer)
}
return g.Swap * feeSuggestion, g.Refund * feeSuggestion, nil
}
Expand Down Expand Up @@ -2155,7 +2146,7 @@ func (w *assetWallet) Redeem(form *asset.RedeemForm, feeWallet *assetWallet, non
// from redemption.Spends.Contract. Even for scriptable UTXO assets, the
// redeem script in this Contract field is redundant with the SecretHash
// field as ExtractSwapDetails can be applied to extract the hash.
ver, locator, err := dexeth.DecodeLocator(redemption.Spends.Contract)
ver, locator, err := dexeth.DecodeContractData(redemption.Spends.Contract)
if err != nil {
return fail(fmt.Errorf("Redeem: invalid versioned swap contract data: %w", err))
}
Expand Down Expand Up @@ -2310,7 +2301,7 @@ func recoverPubkey(msgHash, sig []byte) ([]byte, error) {
// tokenBalance checks the token balance of the account handled by the wallet.
func (w *assetWallet) tokenBalance() (bal *big.Int, err error) {
// We don't care about the version.
return bal, w.withTokenContractor(w.assetID, contractVersionERC20, func(c tokenContractor) error {
return bal, w.withTokenContractor(w.assetID, dexeth.ContractVersionERC20, func(c tokenContractor) error {
bal, err = c.balance(w.ctx)
return err
})
Expand All @@ -2319,7 +2310,7 @@ func (w *assetWallet) tokenBalance() (bal *big.Int, err error) {
// tokenAllowance checks the amount of tokens that the swap contract is approved
// to spend on behalf of the account handled by the wallet.
func (w *assetWallet) tokenAllowance() (allowance *big.Int, err error) {
return allowance, w.withTokenContractor(w.assetID, contractVersionERC20, func(c tokenContractor) error {
return allowance, w.withTokenContractor(w.assetID, dexeth.ContractVersionERC20, func(c tokenContractor) error {
allowance, err = c.allowance(w.ctx)
return err
})
Expand Down Expand Up @@ -2685,7 +2676,7 @@ func (w *assetWallet) AuditContract(coinID, contract, serializedTx dex.Bytes, re
return nil, fmt.Errorf("AuditContract: coin id != txHash - coin id: %x, txHash: %s", coinID, tx.Hash())
}

version, locator, err := dexeth.DecodeLocator(contract)
version, locator, err := dexeth.DecodeContractData(contract)
if err != nil {
return nil, fmt.Errorf("AuditContract: failed to decode contract data: %w", err)
}
Expand Down Expand Up @@ -2727,19 +2718,8 @@ func (w *assetWallet) AuditContract(coinID, contract, serializedTx dex.Bytes, re
if !ok {
return nil, errors.New("AuditContract: tx does not initiate secret hash")
}
// Check vector equivalence. Secret hash equivalence is implied by the
// vectors presence in the map returned from ParseInitiateData.
if vec.Value != txVec.Value {
return nil, errors.New("tx data value doesn't match reported locator data")
}
if vec.To != txVec.To {
return nil, errors.New("tx to address doesn't match reported locator data")
}
if vec.From != txVec.From {
return nil, errors.New("tx from address doesn't match reported locator data")
}
if vec.LockTime != txVec.LockTime {
return nil, errors.New("tx lock time doesn't match reported locator data")
if !dexeth.CompareVectors(vec, txVec) {
return nil, fmt.Errorf("tx vector doesn't match expectation. %+v != %+v", txVec, vec)
}
val = vec.Value
participant = vec.To.String()
Expand Down Expand Up @@ -2788,7 +2768,7 @@ func (w *assetWallet) LockTimeExpired(ctx context.Context, lockTime time.Time) (
// ContractLockTimeExpired returns true if the specified contract's locktime has
// expired, making it possible to issue a Refund.
func (w *assetWallet) ContractLockTimeExpired(ctx context.Context, contract dex.Bytes) (bool, time.Time, error) {
contractVer, locator, err := dexeth.DecodeLocator(contract)
contractVer, locator, err := dexeth.DecodeContractData(contract)
if err != nil {
return false, time.Time{}, err
}
Expand Down Expand Up @@ -2855,7 +2835,7 @@ func (w *assetWallet) FindRedemption(ctx context.Context, _, contract dex.Bytes)
// contract, so we are basically doing the next best thing here.
const coinIDTmpl = coinIDTakerFoundMakerRedemption + "%s"

contractVer, locator, err := dexeth.DecodeLocator(contract)
contractVer, locator, err := dexeth.DecodeContractData(contract)
if err != nil {
return nil, nil, err
}
Expand Down Expand Up @@ -2934,7 +2914,7 @@ func (w *assetWallet) findSecret(locator []byte, contractVer uint32) ([]byte, st
// Refund refunds a contract. This can only be used after the time lock has
// expired.
func (w *assetWallet) Refund(_, contract dex.Bytes, feeRate uint64) (dex.Bytes, error) {
contractVer, locator, err := dexeth.DecodeLocator(contract)
contractVer, locator, err := dexeth.DecodeContractData(contract)
if err != nil {
return nil, fmt.Errorf("Refund: failed to decode contract: %w", err)
}
Expand Down Expand Up @@ -3032,7 +3012,7 @@ 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 (w *TokenWallet) EstimateRegistrationTxFee(feeRate uint64) uint64 {
g := w.gases(contractVersionERC20)
g := w.gases(dexeth.ContractVersionERC20)
if g == nil {
w.log.Errorf("no gas table")
return math.MaxUint64
Expand Down Expand Up @@ -3107,7 +3087,7 @@ func (w *TokenWallet) canSend(value uint64, verifyBalance, isPreEstimate bool) (
return 0, nil, fmt.Errorf("error getting max fee rate: %w", err)
}

g := w.gases(contractVersionERC20)
g := w.gases(dexeth.ContractVersionERC20)
if g == nil {
return 0, nil, fmt.Errorf("gas table not found")
}
Expand Down Expand Up @@ -3199,7 +3179,7 @@ func (w *ETHWallet) RestorationInfo(seed []byte) ([]*asset.WalletRestoration, er
// SwapConfirmations gets the number of confirmations and the spend status
// for the specified swap.
func (w *assetWallet) SwapConfirmations(ctx context.Context, coinID dex.Bytes, contract dex.Bytes, _ time.Time) (confs uint32, spent bool, err error) {
contractVer, secretHash, err := dexeth.DecodeLocator(contract)
contractVer, secretHash, err := dexeth.DecodeContractData(contract)
if err != nil {
return 0, false, err
}
Expand Down Expand Up @@ -3384,7 +3364,7 @@ func (eth *assetWallet) DynamicRedemptionFeesPaid(ctx context.Context, coinID, c
// secret hashes.
func (eth *baseWallet) swapOrRedemptionFeesPaid(ctx context.Context, coinID, contractData dex.Bytes,
isInit bool) (fee uint64, secretHashes [][]byte, err error) {
contractVer, locator, err := dexeth.DecodeLocator(contractData)
contractVer, locator, err := dexeth.DecodeContractData(contractData)
if err != nil {
return 0, nil, err
}
Expand Down Expand Up @@ -4001,7 +3981,7 @@ func (w *assetWallet) checkUnconfirmedRedemption(locator []byte, contractVer uin
// entire redemption batch, a new transaction containing only the swap we are
// searching for will be created.
func (w *assetWallet) confirmRedemptionWithoutMonitoredTx(txHash common.Hash, redemption *asset.Redemption, feeWallet *assetWallet) (*asset.ConfirmRedemptionStatus, error) {
contractVer, locator, err := dexeth.DecodeLocator(redemption.Spends.Contract)
contractVer, locator, err := dexeth.DecodeContractData(redemption.Spends.Contract)
if err != nil {
return nil, fmt.Errorf("failed to decode contract data: %w", err)
}
Expand Down Expand Up @@ -4094,7 +4074,7 @@ func (w *assetWallet) confirmRedemption(coinID dex.Bytes, redemption *asset.Rede
txHash = monitoredTxHash
}

contractVer, locator, err := dexeth.DecodeLocator(redemption.Spends.Contract)
contractVer, locator, err := dexeth.DecodeContractData(redemption.Spends.Contract)
if err != nil {
return nil, fmt.Errorf("failed to decode contract data: %w", err)
}
Expand Down Expand Up @@ -4495,7 +4475,7 @@ func (w *ETHWallet) sendToAddr(addr common.Address, amt uint64, maxFeeRate *big.
func (w *TokenWallet) sendToAddr(addr common.Address, amt uint64, maxFeeRate *big.Int) (tx *types.Transaction, err error) {
w.baseWallet.nonceSendMtx.Lock()
defer w.baseWallet.nonceSendMtx.Unlock()
g := w.gases(contractVersionERC20)
g := w.gases(dexeth.ContractVersionERC20)
if g == nil {
return nil, fmt.Errorf("no gas table")
}
Expand All @@ -4504,7 +4484,7 @@ func (w *TokenWallet) sendToAddr(addr common.Address, amt uint64, maxFeeRate *bi
if err != nil {
return nil, err
}
return tx, w.withTokenContractor(w.assetID, contractVersionERC20, func(c tokenContractor) error {
return tx, w.withTokenContractor(w.assetID, dexeth.ContractVersionERC20, func(c tokenContractor) error {
tx, err = c.transfer(txOpts, addr, w.evmify(amt))
if err != nil {
c.voidUnusedNonce()
Expand Down Expand Up @@ -4627,7 +4607,7 @@ func (w *assetWallet) loadContractors() error {

// withContractor runs the provided function with the versioned contractor.
func (w *assetWallet) withContractor(contractVer uint32, f func(contractor) error) error {
if contractVer == contractVersionERC20 {
if contractVer == dexeth.ContractVersionERC20 {
// For ERC02 methods, use the most recent contractor version.
var bestVer uint32
var bestContractor contractor
Expand Down Expand Up @@ -4660,16 +4640,17 @@ func (w *assetWallet) withTokenContractor(assetID, ver uint32, f func(tokenContr
// estimateApproveGas estimates the gas required for a transaction approving a
// spender for an ERC20 contract.
func (w *assetWallet) estimateApproveGas(newGas *big.Int) (gas uint64, err error) {
return gas, w.withTokenContractor(w.assetID, contractVersionERC20, func(c tokenContractor) error {
return gas, w.withTokenContractor(w.assetID, dexeth.ContractVersionERC20, func(c tokenContractor) error {
gas, err = c.estimateApproveGas(w.ctx, newGas)
return err
})
}

// estimateTransferGas estimates the gas needed for a token transfer call to an
// ERC20 contract.
// TODO: Delete this and contractor methods. Unused.
func (w *assetWallet) estimateTransferGas(val uint64) (gas uint64, err error) {
return gas, w.withTokenContractor(w.assetID, contractVersionERC20, func(c tokenContractor) error {
return gas, w.withTokenContractor(w.assetID, dexeth.ContractVersionERC20, func(c tokenContractor) error {
gas, err = c.estimateTransferGas(w.ctx, w.evmify(val))
return err
})
Expand Down
41 changes: 8 additions & 33 deletions client/asset/eth/eth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2471,7 +2471,7 @@ func testSwap(t *testing.T, assetID uint32) {
testName, receipt.Coin().Value(), contract.Value)
}
contractData := receipt.Contract()
contractVer, locator, err := dexeth.DecodeLocator(contractData)
contractVer, locator, err := dexeth.DecodeContractData(contractData)
if err != nil {
t.Fatalf("failed to decode contract data: %v", err)
}
Expand Down Expand Up @@ -3047,7 +3047,7 @@ func testRedeem(t *testing.T, assetID uint32) {
// Check that value of output coin is as axpected
var totalSwapValue uint64
for _, redemption := range test.form.Redemptions {
_, locator, err := dexeth.DecodeLocator(redemption.Spends.Contract)
_, locator, err := dexeth.DecodeContractData(redemption.Spends.Contract)
if err != nil {
t.Fatalf("DecodeLocator: %v", err)
}
Expand Down Expand Up @@ -3302,15 +3302,6 @@ func TestMaxOrder(t *testing.T) {
}
}

func overMaxWei() *big.Int {
maxInt := ^uint64(0)
maxWei := new(big.Int).SetUint64(maxInt)
gweiFactorBig := big.NewInt(dexeth.GweiFactor)
maxWei.Mul(maxWei, gweiFactorBig)
overMaxWei := new(big.Int).Set(maxWei)
return overMaxWei.Add(overMaxWei, gweiFactorBig)
}

func packInitiateDataV0(initiations []*dexeth.Initiation) ([]byte, error) {
abiInitiations := make([]swapv0.ETHSwapInitiation, 0, len(initiations))
for _, init := range initiations {
Expand Down Expand Up @@ -3500,7 +3491,7 @@ func testAuditContract(t *testing.T, assetID uint32) {
t.Fatalf(`"%v": expected contract %x != actual %x`, test.name, test.contract, auditInfo.Contract)
}

_, expectedSecretHash, err := dexeth.DecodeLocator(test.contract)
_, expectedSecretHash, err := dexeth.DecodeContractData(test.contract)
if err != nil {
t.Fatalf(`"%v": failed to decode versioned bytes: %v`, test.name, err)
}
Expand Down Expand Up @@ -4087,24 +4078,14 @@ func testRefundReserves(t *testing.T, assetID uint32) {
node.swapMap = map[[32]byte]*dexeth.SwapState{secretHash: {}}

feeWallet := eth
gasesV0 := dexeth.VersionedGases[0]
gasesV1 := &dexeth.Gases{Refund: 1e6}
gasesV0 := eth.versionedGases[0]
gasesV1 := eth.versionedGases[1]
assetV0 := *tETHV0
assetV1 := *tETHV0
if assetID == BipID {
eth.versionedGases[1] = gasesV1
} else {
if assetID != BipID {
feeWallet = node.tokenParent
assetV0 = *tTokenV0
assetV1 = *tTokenV0
tokenContracts := dexeth.Tokens[simnetTokenID].NetTokens[dex.Simnet].SwapContracts
gasesV0 = &tokenGasesV0
tc := *tokenContracts[0]
tc.Gas = *gasesV1
tokenContracts[1] = &tc
defer delete(tokenContracts, 1)
eth.versionedGases[0] = gasesV0
eth.versionedGases[1] = gasesV1
node.tokenContractor.bal = dexeth.GweiToWei(1e9)
}

Expand Down Expand Up @@ -4185,9 +4166,9 @@ func testRedemptionReserves(t *testing.T, assetID uint32) {
var secretHash [32]byte
node.tContractor.swapMap[secretHash] = &dexeth.SwapState{}

gasesV1 := &dexeth.Gases{Redeem: 1e6, RedeemAdd: 85e5}
gasesV0 := eth.versionedGases[0]
gasesV1 := eth.versionedGases[1]
eth.versionedGases[1] = gasesV1
gasesV0 := dexeth.VersionedGases[0]
assetV0 := *tETHV0
assetV1 := *tETHV0
feeWallet := eth
Expand All @@ -4196,12 +4177,6 @@ func testRedemptionReserves(t *testing.T, assetID uint32) {
feeWallet = node.tokenParent
assetV0 = *tTokenV0
assetV1 = *tTokenV0
tokenContracts := dexeth.Tokens[simnetTokenID].NetTokens[dex.Simnet].SwapContracts
gasesV0 = &tokenGasesV0
tc := *tokenContracts[0]
tc.Gas = *gasesV1
tokenContracts[1] = &tc
defer delete(tokenContracts, 1)
}

assetV0.MaxFeeRate = 45
Expand Down
6 changes: 3 additions & 3 deletions client/asset/eth/nodeclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@ import (
)

const (
contractVersionNewest = ^uint32(0)
approveGas = 4e5
approveGas = 4e5
)

var (
Expand Down Expand Up @@ -410,9 +409,10 @@ func newTxOpts(ctx context.Context, from common.Address, val, maxGas uint64, max
}

func gases(contractVer uint32, versionedGases map[uint32]*dexeth.Gases) *dexeth.Gases {
if contractVer != contractVersionNewest {
if contractVer != dexeth.ContractVersionERC20 {
return versionedGases[contractVer]
}

var bestVer uint32
var bestGases *dexeth.Gases
for ver, gases := range versionedGases {
Expand Down
Loading

0 comments on commit cd4866c

Please sign in to comment.