/
fund.go
79 lines (67 loc) · 2.65 KB
/
fund.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// SPDX-License-Identifier: GPL-3.0
package publisher
import (
"fmt"
"math/big"
"os"
"github.com/comrade-coop/apocryph/pkg/abi"
pb "github.com/comrade-coop/apocryph/pkg/proto"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
)
func FundPaymentChannel(ethClient *ethclient.Client, publisherAuth *bind.TransactOpts, deployment *pb.Deployment, funds *big.Int, unlockTimeInt *big.Int, mintFunds bool) error {
providerEth := common.BytesToAddress(deployment.Provider.EthereumAddress)
paymentContract := common.BytesToAddress(deployment.Payment.PaymentContractAddress)
podID := common.BytesToHash(deployment.Payment.PodID)
if funds.Cmp(common.Big0) != 0 {
fmt.Fprintf(os.Stderr, "Funding payment channel...\n")
// get a payment contract instance
payment, err := abi.NewPayment(paymentContract, ethClient)
if err != nil {
return fmt.Errorf("Failed instantiating payment contract: %w", err)
}
tokenContract, err := payment.Token(&bind.CallOpts{})
if err != nil {
return fmt.Errorf("Failed resolving token contract address: %w", err)
}
if mintFunds {
token, err := abi.NewMockToken(tokenContract, ethClient)
if err != nil {
return fmt.Errorf("Failed instantiating token contract: %w", err)
}
tx, err := token.Mint(publisherAuth, funds)
if err != nil {
return fmt.Errorf("Failed minting tokens: %w", err)
}
fmt.Fprintf(os.Stderr, "Token mint successful! %v\n", tx.Hash())
}
token, err := abi.NewIERC20(tokenContract, ethClient)
if err != nil {
return fmt.Errorf("Failed instantiating token contract: %w", err)
}
tx, err := token.Approve(publisherAuth, paymentContract, funds)
if err != nil {
return fmt.Errorf("Failed approving token transfer: %w", err)
}
fmt.Fprintf(os.Stderr, "Token approval successful! %v\n", tx.Hash())
channel, err := payment.Channels(&bind.CallOpts{}, publisherAuth.From, providerEth, podID)
if err != nil {
return err
}
if channel.InvestedByPublisher.Cmp(common.Big0) > 0 {
tx, err := payment.Deposit(publisherAuth, providerEth, podID, funds)
if err != nil {
return fmt.Errorf("Failed depositing payment contract funds: %w", err)
}
fmt.Fprintf(os.Stderr, "Payment channel funded with %d extra funds! %v\n", funds, tx.Hash())
} else {
tx, err := payment.CreateChannel(publisherAuth, providerEth, podID, unlockTimeInt, funds)
if err != nil {
return fmt.Errorf("Failed creating payment contract: %w", err)
}
fmt.Fprintf(os.Stderr, "Payment channel created with %d initial funds and %d seconds unlock time! %v\n", funds, unlockTimeInt, tx.Hash())
}
}
return nil
}