Skip to content

Commit 02bbb14

Browse files
Eknirzelig
authored andcommitted
contracts/swap, swap: refactor contractAddress, remove backend as inputParam, function order in contracts/swap (ethersphere#1748)
* swap: removed duplicate contractAddress (swap.owner.Contract) * contracts/swap: function order in line with order in interface definition * swap: use GetParams helper function, remove debugging print
1 parent 88dba2d commit 02bbb14

File tree

6 files changed

+91
-92
lines changed

6 files changed

+91
-92
lines changed

contracts/swap/swap.go

Lines changed: 56 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,10 @@ type Backend interface {
4646
}
4747

4848
// Deploy deploys an instance of the underlying contract and returns its `Contract` abstraction
49-
func Deploy(auth *bind.TransactOpts, backend bind.ContractBackend, owner common.Address, harddepositTimeout time.Duration) (common.Address, Contract, *types.Transaction, error) {
49+
func Deploy(auth *bind.TransactOpts, backend bind.ContractBackend, owner common.Address, harddepositTimeout time.Duration) (Contract, *types.Transaction, error) {
5050
addr, tx, s, err := contract.DeploySimpleSwap(auth, backend, owner, big.NewInt(int64(harddepositTimeout)))
5151
c := simpleContract{instance: s, address: addr}
52-
return addr, c, tx, err
52+
return c, tx, err
5353
}
5454

5555
// InstanceAt creates a new instance of a contract at a specific address.
@@ -86,64 +86,16 @@ type CashChequeResult struct {
8686

8787
// Params encapsulates some contract parameters (currently mostly informational)
8888
type Params struct {
89-
ContractCode, ContractAbi string
90-
}
91-
92-
// ValidateCode checks that the on-chain code at address matches the expected swap
93-
// contract code.
94-
func ValidateCode(ctx context.Context, b bind.ContractBackend, address common.Address) error {
95-
codeReadFromAddress, err := b.CodeAt(ctx, address, nil)
96-
if err != nil {
97-
return err
98-
}
99-
referenceCode := common.FromHex(contract.SimpleSwapDeployedCode)
100-
if !bytes.Equal(codeReadFromAddress, referenceCode) {
101-
return ErrNotASwapContract
102-
}
103-
return nil
104-
}
105-
106-
// WaitFunc is the default function to wait for transactions
107-
// We can overwrite this in tests so that we don't need to wait for mining
108-
var WaitFunc = waitForTx
109-
110-
// waitForTx waits for transaction to be mined and returns the receipt
111-
func waitForTx(auth *bind.TransactOpts, backend Backend, tx *types.Transaction) (*types.Receipt, error) {
112-
// it blocks here until tx is mined
113-
receipt, err := bind.WaitMined(auth.Context, backend, tx)
114-
if err != nil {
115-
return nil, err
116-
}
117-
// indicate whether the transaction did not revert
118-
if receipt.Status != types.ReceiptStatusSuccessful {
119-
return nil, ErrTransactionReverted
120-
}
121-
return receipt, nil
89+
ContractCode string
90+
ContractAbi string
91+
ContractAddress common.Address
12292
}
12393

12494
type simpleContract struct {
12595
instance *contract.SimpleSwap
12696
address common.Address
12797
}
12898

129-
// ContractParams returns contract information
130-
func (s simpleContract) ContractParams() *Params {
131-
return &Params{
132-
ContractCode: contract.SimpleSwapBin,
133-
ContractAbi: contract.SimpleSwapABI,
134-
}
135-
}
136-
137-
// PaidOut returns the total paid out amount for the given address
138-
func (s simpleContract) PaidOut(opts *bind.CallOpts, addr common.Address) (*big.Int, error) {
139-
return s.instance.PaidOut(opts, addr)
140-
}
141-
142-
// Issuer returns the contract owner from the blockchain
143-
func (s simpleContract) Issuer(opts *bind.CallOpts) (common.Address, error) {
144-
return s.instance.Issuer(opts)
145-
}
146-
14799
// CashChequeBeneficiary cashes the cheque on the blockchain and blocks until the transaction is mined.
148100
func (s simpleContract) CashChequeBeneficiary(auth *bind.TransactOpts, backend Backend, beneficiary common.Address, cumulativePayout *big.Int, ownerSig []byte) (*CashChequeResult, *types.Receipt, error) {
149101
tx, err := s.instance.CashChequeBeneficiary(auth, beneficiary, cumulativePayout, ownerSig)
@@ -177,3 +129,54 @@ func (s simpleContract) CashChequeBeneficiary(auth *bind.TransactOpts, backend B
177129

178130
return result, receipt, nil
179131
}
132+
133+
// ContractParams returns contract information
134+
func (s simpleContract) ContractParams() *Params {
135+
return &Params{
136+
ContractCode: contract.SimpleSwapBin,
137+
ContractAbi: contract.SimpleSwapABI,
138+
ContractAddress: s.address,
139+
}
140+
}
141+
142+
// Issuer returns the contract owner from the blockchain
143+
func (s simpleContract) Issuer(opts *bind.CallOpts) (common.Address, error) {
144+
return s.instance.Issuer(opts)
145+
}
146+
147+
// PaidOut returns the total paid out amount for the given address
148+
func (s simpleContract) PaidOut(opts *bind.CallOpts, addr common.Address) (*big.Int, error) {
149+
return s.instance.PaidOut(opts, addr)
150+
}
151+
152+
// ValidateCode checks that the on-chain code at address matches the expected swap
153+
// contract code.
154+
func ValidateCode(ctx context.Context, b bind.ContractBackend, address common.Address) error {
155+
codeReadFromAddress, err := b.CodeAt(ctx, address, nil)
156+
if err != nil {
157+
return err
158+
}
159+
referenceCode := common.FromHex(contract.SimpleSwapDeployedCode)
160+
if !bytes.Equal(codeReadFromAddress, referenceCode) {
161+
return ErrNotASwapContract
162+
}
163+
return nil
164+
}
165+
166+
// WaitFunc is the default function to wait for transactions
167+
// We can overwrite this in tests so that we don't need to wait for mining
168+
var WaitFunc = waitForTx
169+
170+
// waitForTx waits for transaction to be mined and returns the receipt
171+
func waitForTx(auth *bind.TransactOpts, backend Backend, tx *types.Transaction) (*types.Receipt, error) {
172+
// it blocks here until tx is mined
173+
receipt, err := bind.WaitMined(auth.Context, backend, tx)
174+
if err != nil {
175+
return nil, err
176+
}
177+
// indicate whether the transaction did not revert
178+
if receipt.Status != types.ReceiptStatusSuccessful {
179+
return nil, ErrTransactionReverted
180+
}
181+
return receipt, nil
182+
}

swap/peer.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ func (p *Peer) createCheque() (*Cheque, error) {
138138
cheque = &Cheque{
139139
ChequeParams: ChequeParams{
140140
CumulativePayout: total + amount,
141-
Contract: p.swap.owner.Contract,
141+
Contract: p.swap.GetParams().ContractAddress,
142142
Beneficiary: p.beneficiary,
143143
},
144144
Honey: honey,

swap/protocol.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ func (s *Swap) run(p *p2p.Peer, rw p2p.MsgReadWriter) error {
105105
protoPeer := protocols.NewPeer(p, rw, Spec)
106106

107107
handshake, err := protoPeer.Handshake(context.Background(), &HandshakeMsg{
108-
ContractAddress: s.owner.Contract,
108+
ContractAddress: s.GetParams().ContractAddress,
109109
}, s.verifyHandshake)
110110
if err != nil {
111111
return err

swap/protocol_test.go

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ func TestHandshake(t *testing.T) {
5151
defer clean()
5252

5353
ctx := context.Background()
54-
err = testDeploy(ctx, swap.backend, swap)
54+
err = testDeploy(ctx, swap)
5555
if err != nil {
5656
t.Fatal(err)
5757
}
@@ -83,7 +83,7 @@ func TestHandshake(t *testing.T) {
8383
{
8484
Code: 0,
8585
Msg: &HandshakeMsg{
86-
ContractAddress: swap.owner.Contract,
86+
ContractAddress: swap.GetParams().ContractAddress,
8787
},
8888
Peer: creditor.ID(),
8989
},
@@ -92,7 +92,7 @@ func TestHandshake(t *testing.T) {
9292
{
9393
Code: 0,
9494
Msg: &HandshakeMsg{
95-
ContractAddress: swap.owner.Contract,
95+
ContractAddress: swap.GetParams().ContractAddress,
9696
},
9797
Peer: debitor.ID(),
9898
},
@@ -121,11 +121,11 @@ func TestEmitCheque(t *testing.T) {
121121
ctx := context.Background()
122122

123123
log.Debug("deploy to simulated backend")
124-
err := testDeploy(ctx, creditorSwap.backend, creditorSwap)
124+
err := testDeploy(ctx, creditorSwap)
125125
if err != nil {
126126
t.Fatal(err)
127127
}
128-
err = testDeploy(ctx, debitorSwap.backend, debitorSwap)
128+
err = testDeploy(ctx, debitorSwap)
129129
if err != nil {
130130
t.Fatal(err)
131131
}
@@ -135,7 +135,7 @@ func TestEmitCheque(t *testing.T) {
135135
// create the debitor peer
136136
dPtpPeer := p2p.NewPeer(enode.ID{}, "debitor", []p2p.Cap{})
137137
dProtoPeer := protocols.NewPeer(dPtpPeer, nil, Spec)
138-
debitor, err := creditorSwap.addPeer(dProtoPeer, debitorSwap.owner.address, debitorSwap.owner.Contract)
138+
debitor, err := creditorSwap.addPeer(dProtoPeer, debitorSwap.owner.address, debitorSwap.GetParams().ContractAddress)
139139
if err != nil {
140140
t.Fatal(err)
141141
}
@@ -151,7 +151,7 @@ func TestEmitCheque(t *testing.T) {
151151
log.Debug("create a cheque")
152152
cheque := &Cheque{
153153
ChequeParams: ChequeParams{
154-
Contract: debitorSwap.owner.Contract,
154+
Contract: debitorSwap.GetParams().ContractAddress,
155155
Beneficiary: creditorSwap.owner.address,
156156
CumulativePayout: 42,
157157
},
@@ -202,6 +202,11 @@ func TestTriggerPaymentThreshold(t *testing.T) {
202202
debitorSwap, clean := newTestSwap(t, ownerKey)
203203
defer clean()
204204

205+
ctx := context.Background()
206+
err := testDeploy(ctx, debitorSwap)
207+
if err != nil {
208+
t.Fatal(err)
209+
}
205210
// setup the wait for mined transaction function for testing
206211
cleanup := setupContractTest()
207212
defer cleanup()

swap/swap.go

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,6 @@ type Swap struct {
6161

6262
// Owner encapsulates information related to accessing the contract
6363
type Owner struct {
64-
Contract common.Address // address of swap contract
6564
address common.Address // owner address
6665
privateKey *ecdsa.PrivateKey // private key
6766
publicKey *ecdsa.PublicKey // public key
@@ -130,7 +129,7 @@ func createOwner(prvkey *ecdsa.PrivateKey) *Owner {
130129

131130
// DeploySuccess is for convenience log output
132131
func (s *Swap) DeploySuccess() string {
133-
return fmt.Sprintf("contract: %s, owner: %s, deposit: %v, signer: %x", s.owner.Contract.Hex(), s.owner.address.Hex(), s.params.InitialDepositAmount, s.owner.publicKey)
132+
return fmt.Sprintf("contract: %s, owner: %s, deposit: %v, signer: %x", s.GetParams().ContractAddress.Hex(), s.owner.address.Hex(), s.params.InitialDepositAmount, s.owner.publicKey)
134133
}
135134

136135
// Add is the (sole) accounting function
@@ -217,7 +216,7 @@ func (s *Swap) handleEmitChequeMsg(ctx context.Context, p *Peer, msg *EmitCheque
217216
// The function cashes the cheque by sending it to the blockchain
218217
func cashCheque(s *Swap, otherSwap contract.Contract, opts *bind.TransactOpts, cheque *Cheque) {
219218
// blocks here, as we are waiting for the transaction to be mined
220-
result, receipt, err := otherSwap.CashChequeBeneficiary(opts, s.backend, s.owner.Contract, big.NewInt(int64(cheque.CumulativePayout)), cheque.Signature)
219+
result, receipt, err := otherSwap.CashChequeBeneficiary(opts, s.backend, s.GetParams().ContractAddress, big.NewInt(int64(cheque.CumulativePayout)), cheque.Signature)
221220
if err != nil {
222221
// TODO: do something with the error
223222
// and we actually need to log this error as we are in an async routine; nobody is handling this error for now
@@ -352,16 +351,11 @@ func (s *Swap) Close() error {
352351
return s.store.Close()
353352
}
354353

355-
// GetParams returns contract parameters (Bin, ABI) from the contract
354+
// GetParams returns contract parameters (Bin, ABI, contractAddress) from the contract
356355
func (s *Swap) GetParams() *swap.Params {
357356
return s.contract.ContractParams()
358357
}
359358

360-
// setChequebookAddr sets the chequebook address
361-
func (s *Swap) setChequebookAddr(chequebookAddr common.Address) {
362-
s.owner.Contract = chequebookAddr
363-
}
364-
365359
// getContractOwner retrieve the owner of the chequebook at address from the blockchain
366360
func (s *Swap) getContractOwner(ctx context.Context, address common.Address) (common.Address, error) {
367361
contr, err := contract.InstanceAt(address, s.backend)
@@ -380,7 +374,7 @@ func (s *Swap) StartChequebook(chequebookAddr common.Address) error {
380374
}
381375
log.Info("Using the provided chequebook", "chequebookAddr", chequebookAddr)
382376
} else {
383-
if err := s.Deploy(context.Background(), s.backend); err != nil {
377+
if err := s.Deploy(context.Background()); err != nil {
384378
return err
385379
}
386380
log.Info("New SWAP contract deployed", "contract info", s.DeploySuccess())
@@ -398,42 +392,40 @@ func (s *Swap) BindToContractAt(address common.Address) (err error) {
398392
if err != nil {
399393
return err
400394
}
401-
s.setChequebookAddr(address)
402395
return nil
403396
}
404397

405398
// Deploy deploys the Swap contract and sets the contract address
406-
func (s *Swap) Deploy(ctx context.Context, backend swap.Backend) error {
399+
func (s *Swap) Deploy(ctx context.Context) error {
407400
opts := bind.NewKeyedTransactor(s.owner.privateKey)
408401
// initial topup value
409402
opts.Value = big.NewInt(int64(s.params.InitialDepositAmount))
410403
opts.Context = ctx
411404

412405
log.Info("deploying new swap", "owner", opts.From.Hex())
413-
address, err := s.deployLoop(opts, backend, s.owner.address, defaultHarddepositTimeoutDuration)
406+
address, err := s.deployLoop(opts, s.owner.address, defaultHarddepositTimeoutDuration)
414407
if err != nil {
415408
log.Error("unable to deploy swap", "error", err)
416409
return err
417410
}
418-
s.setChequebookAddr(address)
419411
log.Info("swap deployed", "address", address.Hex(), "owner", opts.From.Hex())
420412

421413
return err
422414
}
423415

424416
// deployLoop repeatedly tries to deploy the swap contract .
425-
func (s *Swap) deployLoop(opts *bind.TransactOpts, backend swap.Backend, owner common.Address, defaultHarddepositTimeoutDuration time.Duration) (addr common.Address, err error) {
417+
func (s *Swap) deployLoop(opts *bind.TransactOpts, owner common.Address, defaultHarddepositTimeoutDuration time.Duration) (addr common.Address, err error) {
426418
var tx *types.Transaction
427419
for try := 0; try < deployRetries; try++ {
428420
if try > 0 {
429421
time.Sleep(deployDelay)
430422
}
431423

432-
if _, s.contract, tx, err = contract.Deploy(opts, backend, owner, defaultHarddepositTimeoutDuration); err != nil {
424+
if s.contract, tx, err = contract.Deploy(opts, s.backend, owner, defaultHarddepositTimeoutDuration); err != nil {
433425
log.Warn("can't send chequebook deploy tx", "try", try, "error", err)
434426
continue
435427
}
436-
if addr, err = bind.WaitDeployed(opts.Context, backend, tx); err != nil {
428+
if addr, err = bind.WaitDeployed(opts.Context, s.backend, tx); err != nil {
437429
log.Warn("chequebook deploy error", "try", try, "error", err)
438430
continue
439431
}

0 commit comments

Comments
 (0)