Skip to content

Commit 8624e81

Browse files
committed
cleanup and early review followup
1 parent 53b08ac commit 8624e81

12 files changed

Lines changed: 99 additions & 190 deletions

File tree

client/asset/eth/contractor.go

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,6 @@ func (c *contractorV0) swap(ctx context.Context, secretHash [32]byte) (*dexeth.S
195195
if err != nil {
196196
return nil, err
197197
}
198-
199198
return &dexeth.SwapState{
200199
BlockHeight: state.InitBlockNumber.Uint64(),
201200
LockTime: time.Unix(state.RefundBlockTimestamp.Int64(), 0),
@@ -207,7 +206,6 @@ func (c *contractorV0) swap(ctx context.Context, secretHash [32]byte) (*dexeth.S
207206
}, nil
208207
}
209208

210-
// swap retrieves the swap info from the read-only swap method.
211209
func (c *contractorV0) status(ctx context.Context, contract *dex.SwapContractDetails) (step dexeth.SwapStep, secret [32]byte, blockNumber uint32, err error) {
212210
var secretHash [32]byte
213211
copy(secretHash[:], contract.SecretHash)
@@ -218,32 +216,41 @@ func (c *contractorV0) status(ctx context.Context, contract *dex.SwapContractDet
218216
return swap.State, swap.Secret, uint32(swap.BlockHeight), nil
219217
}
220218

219+
func (c *contractorV0) refundImpl(txOpts *bind.TransactOpts, secretHash [32]byte) (*types.Transaction, error) {
220+
return c.contractV0.Refund(txOpts, secretHash)
221+
}
222+
221223
// refund issues the refund command to the swap contract. Use isRefundable first
222224
// to ensure the refund will be accepted.
223225
func (c *contractorV0) refund(txOpts *bind.TransactOpts, contract *dex.SwapContractDetails) (*types.Transaction, error) {
224226
var secretHash [32]byte
225227
copy(secretHash[:], contract.SecretHash)
226-
return c.contractV0.Refund(txOpts, secretHash)
228+
return c.refundImpl(txOpts, secretHash)
229+
}
230+
231+
func (c *contractorV0) isRedeemableImpl(secretHash, secret [32]byte) (bool, error) {
232+
return c.contractV0.IsRedeemable(&bind.CallOpts{From: c.acctAddr}, secretHash, secret)
227233
}
228234

229235
// isRedeemable exposes the isRedeemable method of the swap contract.
230236
func (c *contractorV0) isRedeemable(secret [32]byte, contract *dex.SwapContractDetails) (bool, error) {
231237
var secretHash [32]byte
232238
copy(secretHash[:], contract.SecretHash)
233-
return c.contractV0.IsRedeemable(&bind.CallOpts{From: c.acctAddr}, secretHash, secret)
239+
return c.isRedeemableImpl(secretHash, secret)
240+
}
241+
242+
func (c *contractorV0) isRefundableImpl(secretHash [32]byte) (bool, error) {
243+
return c.contractV0.IsRefundable(&bind.CallOpts{From: c.acctAddr}, secretHash)
234244
}
235245

236246
// isRefundable exposes the isRefundable method of the swap contract.
237247
func (c *contractorV0) isRefundable(contract *dex.SwapContractDetails) (bool, error) {
238248
var secretHash [32]byte
239249
copy(secretHash[:], contract.SecretHash)
240-
return c.contractV0.IsRefundable(&bind.CallOpts{From: c.acctAddr}, secretHash)
250+
return c.isRefundableImpl(secretHash)
241251
}
242252

243-
// estimateRedeemGas estimates the gas used to redeem. The secret hashes
244-
// supplied must reference existing swaps, so this method can't be used until
245-
// the swap is initiated.
246-
func (c *contractorV0) estimateRedeemGas(ctx context.Context, secrets [][32]byte, _ []*dex.SwapContractDetails) (uint64, error) {
253+
func (c *contractorV0) estimateRedeemGasImpl(ctx context.Context, secrets [][32]byte) (uint64, error) {
247254
redemps := make([]swapv0.ETHSwapRedemption, 0, len(secrets))
248255
for _, secret := range secrets {
249256
redemps = append(redemps, swapv0.ETHSwapRedemption{
@@ -254,13 +261,24 @@ func (c *contractorV0) estimateRedeemGas(ctx context.Context, secrets [][32]byte
254261
return c.estimateGas(ctx, nil, "redeem", redemps)
255262
}
256263

264+
// estimateRedeemGas estimates the gas used to redeem. The secret hashes
265+
// supplied must reference existing swaps, so this method can't be used until
266+
// the swap is initiated.
267+
func (c *contractorV0) estimateRedeemGas(ctx context.Context, secrets [][32]byte, _ []*dex.SwapContractDetails) (uint64, error) {
268+
return c.estimateRedeemGasImpl(ctx, secrets)
269+
}
270+
271+
func (c *contractorV0) estimateRefundGasImpl(ctx context.Context, secretHash [32]byte) (uint64, error) {
272+
return c.estimateGas(ctx, nil, "refund", secretHash)
273+
}
274+
257275
// estimateRefundGas estimates the gas used to refund. The secret hashes
258276
// supplied must reference existing swaps that are refundable, so this method
259277
// can't be used until the swap is initiated and the lock time has expired.
260278
func (c *contractorV0) estimateRefundGas(ctx context.Context, deets *dex.SwapContractDetails) (uint64, error) {
261279
var secretHash [32]byte
262280
copy(secretHash[:], deets.SecretHash)
263-
return c.estimateGas(ctx, nil, "refund", secretHash)
281+
return c.estimateRefundGasImpl(ctx, secretHash)
264282
}
265283

266284
// estimateInitGas estimates the gas used to initiate n generic swaps. The

client/asset/eth/eth.go

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1482,7 +1482,7 @@ func (w *ETHWallet) Swap(swaps *asset.Swaps) ([]asset.Receipt, asset.Coin, uint6
14821482
return fail("unfunded swap: %d < %d", reservedVal, swapVal+fees)
14831483
}
14841484

1485-
tx, err := w.initiate(w.ctx, w.assetID, w.contractsToDetails(swaps.Contracts), swaps.FeeRate, gasLimit, cfg.Version)
1485+
tx, err := w.initiate(w.ctx, w.assetID, w.contractsToInitDetails(swaps.Contracts), swaps.FeeRate, gasLimit, cfg.Version)
14861486
if err != nil {
14871487
return fail("Swap: initiate error: %w", err)
14881488
}
@@ -1512,7 +1512,7 @@ func (w *ETHWallet) Swap(swaps *asset.Swaps) ([]asset.Receipt, asset.Coin, uint6
15121512
return receipts, change, fees, nil
15131513
}
15141514

1515-
func (w *baseWallet) contractsToDetails(contracts []*asset.Contract) []*dex.SwapContractDetails {
1515+
func (w *baseWallet) contractsToInitDetails(contracts []*asset.Contract) []*dex.SwapContractDetails {
15161516
details := make([]*dex.SwapContractDetails, len(contracts))
15171517
for i, c := range contracts {
15181518
details[i] = &dex.SwapContractDetails{
@@ -1572,7 +1572,7 @@ func (w *TokenWallet) Swap(swaps *asset.Swaps) ([]asset.Receipt, asset.Coin, uin
15721572
return fail("unfunded token swap fees: %d < %d", reservedParent, fees)
15731573
}
15741574

1575-
tx, err := w.initiate(w.ctx, w.assetID, w.contractsToDetails(swaps.Contracts), swaps.FeeRate, gasLimit, cfg.Version)
1575+
tx, err := w.initiate(w.ctx, w.assetID, w.contractsToInitDetails(swaps.Contracts), swaps.FeeRate, gasLimit, cfg.Version)
15761576
if err != nil {
15771577
return fail("Swap: initiate error: %w", err)
15781578
}
@@ -2037,8 +2037,7 @@ func (w *assetWallet) AuditContract(coinID, contract, serializedTx dex.Bytes, re
20372037
}
20382038

20392039
var val uint64
2040-
var participant string
2041-
var initiator string
2040+
var participant, initiator string
20422041
var lockTime time.Time
20432042
switch version {
20442043
case 0:

client/asset/eth/eth_test.go

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2485,27 +2485,6 @@ func testAuditContract(t *testing.T, assetID uint32) {
24852485
}
24862486

24872487
for _, test := range tests {
2488-
// txData, err := packInitiateDataV0(test.initiations)
2489-
// if err != nil {
2490-
// t.Fatalf("unexpected error: %v", err)
2491-
// }
2492-
// if test.badTxData {
2493-
// txData = []byte{0}
2494-
// }
2495-
2496-
// tx := tTx(2, 300, uint64(len(test.initiations)), &node.addr, txData)
2497-
// chainParams := node.chainConfig()
2498-
// signer := types.LatestSignerForChainID(chainParams.ChainID)
2499-
// tx, _ = types.SignTx(tx, signer, privKey)
2500-
2501-
// txBinary, err := tx.MarshalBinary()
2502-
// if err != nil {
2503-
// t.Fatalf(`"%v": failed to marshal binary: %v`, test.name, err)
2504-
// }
2505-
// if test.badTxBinary {
2506-
// txBinary = []byte{0}
2507-
// }
2508-
25092488
txData, err := packInitiateDataV0(test.initiations)
25102489
if err != nil {
25112490
t.Fatalf("unexpected error: %v", err)

client/asset/eth/nodeclient_harness_test.go

Lines changed: 29 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -293,9 +293,9 @@ func runSimnet(m *testing.M) (int, error) {
293293
participantAddr = participantAcct.Address
294294

295295
if v1 {
296-
prepareV1Contractors()
296+
prepareV1SimnetContractors()
297297
} else {
298-
prepareV0Contractors()
298+
prepareV0SimnetContractors()
299299
}
300300

301301
if err := ethClient.unlock(pw); err != nil {
@@ -482,15 +482,15 @@ func runTestnet(m *testing.M) (int, error) {
482482
return code, nil
483483
}
484484

485-
func prepareV0Contractors() (err error) {
486-
return prepareContractors(newV0Contractor, newV0TokenContractor)
485+
func prepareV0SimnetContractors() (err error) {
486+
return prepareSimnetContractors(newV0Contractor, newV0TokenContractor)
487487
}
488488

489-
func prepareV1Contractors() (err error) {
490-
return prepareContractors(newV1Contractor, newV1TokenContractor)
489+
func prepareV1SimnetContractors() (err error) {
490+
return prepareSimnetContractors(newV1Contractor, newV1TokenContractor)
491491
}
492492

493-
func prepareContractors(c contractorConstructor, tc tokenContractorConstructor) (err error) {
493+
func prepareSimnetContractors(c contractorConstructor, tc tokenContractorConstructor) (err error) {
494494
if simnetContractor, err = c(dex.Simnet, simnetAddr, ethClient.contractBackend()); err != nil {
495495
return fmt.Errorf("new contractor error: %w", err)
496496
}
@@ -1210,21 +1210,9 @@ func testInitiate(t *testing.T, assetID uint32) {
12101210

12111211
diff := new(big.Int).Sub(wantBal, bal)
12121212
if diff.CmpAbs(new(big.Int)) != 0 {
1213-
1214-
fmt.Println("Original balance:", fmtBig(originalBal), ", New balance:", fmtBig(bal),
1215-
", Balance change:", fmtBig(new(big.Int).Sub(bal, originalBal)),
1216-
", Tx fees:", fmtBig(txFee), ", Swap val:", fmtBig(dexeth.GweiToWei(totalVal)))
1217-
1218-
cmd := exec.CommandContext(ctx, "./mine-alpha", "5")
1219-
cmd.Dir = harnessCtlDir
1220-
if err := cmd.Run(); err != nil {
1221-
t.Fatalf("error mining block after funding wallets")
1222-
}
1223-
1224-
bal, _ := balance()
1225-
1226-
fmt.Println("Original balance:", fmtBig(originalBal), ", New balance:", fmtBig(bal),
1227-
", Balance change:", fmtBig(new(big.Int).Sub(bal, originalBal)))
1213+
fmt.Println("Original balance:", fmtWei(originalBal), ", New balance:", fmtWei(bal),
1214+
", Balance change:", fmtWei(new(big.Int).Sub(bal, originalBal)),
1215+
", Tx fees:", fmtWei(txFee), ", Swap val:", fmtWei(dexeth.GweiToWei(totalVal)))
12281216
t.Fatalf("%s: unexpected balance change: want %d got %d gwei, diff = %.9f gwei",
12291217
test.name, dexeth.WeiToGwei(wantBal), dexeth.WeiToGwei(bal), float64(diff.Int64())/dexeth.GweiFactor)
12301218
}
@@ -1441,18 +1429,18 @@ func testRedeem(t *testing.T, assetID uint32) {
14411429
finalStates: []dexeth.SwapStep{dexeth.SSRedeemed},
14421430
addAmt: true,
14431431
},
1444-
// {
1445-
// name: "bad redeemer",
1446-
// sleepNBlocks: 8,
1447-
// redeemerClient: ethClient,
1448-
// redeemer: simnetAcct,
1449-
// redeemerContractor: c,
1450-
// swaps: []*dex.SwapContractDetails{newDetails(4, 1)},
1451-
// redemptions: []*asset.Redemption{newRedeem(secrets[4], secretHashes[4], 1, lockTime)},
1452-
// isRedeemable: []bool{false},
1453-
// finalStates: []dexeth.SwapStep{dexeth.SSInitiated},
1454-
// addAmt: false,
1455-
// },
1432+
{
1433+
name: "bad redeemer",
1434+
sleepNBlocks: 8,
1435+
redeemerClient: ethClient,
1436+
redeemer: simnetAcct,
1437+
redeemerContractor: c,
1438+
swaps: []*dex.SwapContractDetails{newDetails(4, 1)},
1439+
redemptions: []*asset.Redemption{newRedeem(secrets[4], secretHashes[4], 1, lockTime)},
1440+
isRedeemable: []bool{false},
1441+
finalStates: []dexeth.SwapStep{dexeth.SSInitiated},
1442+
addAmt: false,
1443+
},
14561444
{
14571445
name: "bad secret",
14581446
sleepNBlocks: 8,
@@ -1573,9 +1561,9 @@ func testRedeem(t *testing.T, assetID uint32) {
15731561
expGas := gases.RedeemN(len(test.redemptions))
15741562
// Ethereum is weird. For v1, if I use 42,000 here, it will often fail,
15751563
// using all of the gas, so presumably it fails because of insufficient
1576-
// gas. But if I set a higher limit, the it will succeed, and oddly will
1577-
// never use 42,000 gas. Why does it use more gas when I use a lower
1578-
// limit?
1564+
// gas. But if I set a higher limit, then it will succeed, and oddly
1565+
// will never use 42,000 gas. Why does it use more gas when I use a
1566+
// lower limit?
15791567
txOpts, _ = test.redeemerClient.txOpts(ctx, 0, expGas, dexeth.GweiToWei(maxFeeRate))
15801568
tx, err = test.redeemerContractor.redeem(txOpts, test.redemptions)
15811569
if test.expectRedeemErr {
@@ -1603,9 +1591,6 @@ func testRedeem(t *testing.T, assetID uint32) {
16031591
if err != nil && expSuccess {
16041592
t.Fatalf("%s: failed redeem transaction status: %v", test.name, err)
16051593
}
1606-
if expSuccess && receipt.GasUsed > expGas {
1607-
t.Fatalf("%s: gas used, %d, exceeds expected max %d", test.name, receipt.GasUsed, expGas)
1608-
}
16091594

16101595
fmt.Printf("Gas used for %d redeems, success = %t: %d \n", len(test.swaps), expSuccess, receipt.GasUsed)
16111596

@@ -1952,11 +1937,9 @@ func testRefund(t *testing.T, assetID uint32) {
19521937

19531938
diff := new(big.Int).Sub(wantBal, bal)
19541939
if diff.CmpAbs(dexeth.GweiToWei(1)) >= 0 {
1955-
1956-
fmt.Println("Original balance:", fmtBig(originalBal), ", New balance:", fmtBig(bal),
1957-
", Balance change:", fmtBig(new(big.Int).Sub(bal, originalBal)),
1958-
", Tx fees:", fmtBig(txFee), ", Swap val:", fmtBig(dexeth.GweiToWei(amt)))
1959-
1940+
fmt.Println("Original balance:", fmtWei(originalBal), ", New balance:", fmtWei(bal),
1941+
", Balance change:", fmtWei(new(big.Int).Sub(bal, originalBal)),
1942+
", Tx fees:", fmtWei(txFee), ", Swap val:", fmtWei(dexeth.GweiToWei(amt)))
19601943
t.Fatalf("%s: unexpected balance change: want %d got %d, diff = %d",
19611944
test.name, dexeth.WeiToGwei(wantBal), dexeth.WeiToGwei(bal), dexeth.WeiToGwei(diff))
19621945
}
@@ -2342,6 +2325,6 @@ func exportAccountsFromNode(node *node.Node) ([]accounts.Account, error) {
23422325
return ks.Accounts(), nil
23432326
}
23442327

2345-
func fmtBig(v *big.Int) string {
2328+
func fmtWei(v *big.Int) string {
23462329
return fmt.Sprintf("%.9f gwei", float64(new(big.Int).Div(v, big.NewInt(dexeth.GweiFactor)).Int64()))
23472330
}

client/asset/interface.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -182,9 +182,8 @@ type WalletInfo struct {
182182
// TODO: Handle unsupported protocols at the UI (instruct user to update
183183
// dexc).
184184
ProtocolVersions []uint32 `json:"protocolVersions"`
185-
// Version is the Wallet's version number, which is used to signal when
186-
// major changes are made to internal details such as coin ID encoding and
187-
// contract structure that must be common to a server's.
185+
// Version is the highest server backend version supported by the client.
186+
// Deprecated: Use ProtocolVersions.
188187
Version uint32 `json:"version"`
189188
// AvailableWallets is an ordered list of available WalletDefinition. The
190189
// first WalletDefinition is considered the default, and might, for instance

client/asset/ltc/ltc.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ var (
119119
rpcWalletDefinition,
120120
electrumWalletDefinition,
121121
},
122-
ProtocolVersions: []uint32{0},
122+
ProtocolVersions: []uint32{1},
123123
}
124124
)
125125

client/core/types.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ type WalletBalance struct {
104104
// WalletState is the current status of an exchange wallet.
105105
type WalletState struct {
106106
Symbol string `json:"symbol"`
107-
AssetID uint32 `json:"assetID"`
107+
AssetID uint32 `json:"assetID"` // Deprecated: use ProtocolVersions
108108
Version uint32 `json:"version"`
109109
WalletType string `json:"type"`
110110
Traits asset.WalletTrait `json:"traits"`
@@ -117,7 +117,7 @@ type WalletState struct {
117117
PeerCount uint32 `json:"peerCount"`
118118
Synced bool `json:"synced"`
119119
SyncProgress float32 `json:"syncProgress"`
120-
// ProtocolVersions is the supported server protocol versions. Added ~0.6.
120+
// ProtocolVersions is the supported server protocol versions.
121121
ProtocolVersions []uint32 `json:"protocolVersions"`
122122
}
123123

dex/asset.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ func IntDivUp(val, div int64) int64 {
175175
// return (val + div - 1) / div
176176
}
177177

178-
// SwapContractDetails is critical information for one side of a trade.
178+
// SwapContractDetails is critical swap data for one side of a trade.
179179
type SwapContractDetails struct {
180180
// From is the sending address.
181181
From string

dex/networks/eth/params.go

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ import (
1515
"os"
1616
"time"
1717

18-
"decred.org/dcrdex/client/asset"
1918
"decred.org/dcrdex/dex"
2019
v0 "decred.org/dcrdex/dex/networks/eth/contracts/v0"
2120
swapv1 "decred.org/dcrdex/dex/networks/eth/contracts/v1"
@@ -250,15 +249,6 @@ type Initiation struct {
250249
ValueGwei uint64
251250
}
252251

253-
func (i *Initiation) Contract() *asset.Contract {
254-
return &asset.Contract{
255-
Address: i.Participant.String(),
256-
Value: i.ValueGwei,
257-
SecretHash: i.SecretHash[:],
258-
LockTime: uint64(i.LockTime.Unix()),
259-
}
260-
}
261-
262252
// Redemption is the data used to redeem a swap.
263253
type Redemption struct {
264254
Secret [32]byte

server/asset/eth/eth.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,6 @@ type ethFetcher interface {
168168
receipt(context.Context, common.Hash) (*types.Receipt, error)
169169
// token- and asset-specific methods
170170
loadToken(ctx context.Context, assetID uint32) error
171-
// status(ctx context.Context, assetID uint32, contract *dex.SwapContractDetails) (step dexeth.SwapStep, secret [32]byte, blockNumber uint32, err error)
172171
accountBalance(ctx context.Context, assetID uint32, addr common.Address) (*big.Int, error)
173172
}
174173

0 commit comments

Comments
 (0)