-
Notifications
You must be signed in to change notification settings - Fork 338
/
erc20.go
93 lines (77 loc) · 2.26 KB
/
erc20.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Copyright 2021 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package erc20
import (
"context"
"errors"
"math/big"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethersphere/bee/pkg/sctx"
"github.com/ethersphere/bee/pkg/transaction"
"github.com/ethersphere/go-sw3-abi/sw3abi"
)
var (
erc20ABI = transaction.ParseABIUnchecked(sw3abi.ERC20ABIv0_3_1)
errDecodeABI = errors.New("could not decode abi data")
)
type Service interface {
BalanceOf(ctx context.Context, address common.Address) (*big.Int, error)
Transfer(ctx context.Context, address common.Address, value *big.Int) (common.Hash, error)
}
type erc20Service struct {
backend transaction.Backend
transactionService transaction.Service
address common.Address
}
func New(backend transaction.Backend, transactionService transaction.Service, address common.Address) Service {
return &erc20Service{
backend: backend,
transactionService: transactionService,
address: address,
}
}
func (c *erc20Service) BalanceOf(ctx context.Context, address common.Address) (*big.Int, error) {
callData, err := erc20ABI.Pack("balanceOf", address)
if err != nil {
return nil, err
}
output, err := c.transactionService.Call(ctx, &transaction.TxRequest{
To: &c.address,
Data: callData,
})
if err != nil {
return nil, err
}
results, err := erc20ABI.Unpack("balanceOf", output)
if err != nil {
return nil, err
}
if len(results) != 1 {
return nil, errDecodeABI
}
balance, ok := abi.ConvertType(results[0], new(big.Int)).(*big.Int)
if !ok || balance == nil {
return nil, errDecodeABI
}
return balance, nil
}
func (c *erc20Service) Transfer(ctx context.Context, address common.Address, value *big.Int) (common.Hash, error) {
callData, err := erc20ABI.Pack("transfer", address, value)
if err != nil {
return common.Hash{}, err
}
request := &transaction.TxRequest{
To: &c.address,
Data: callData,
GasPrice: sctx.GetGasPrice(ctx),
GasLimit: 0,
Value: big.NewInt(0),
}
txHash, err := c.transactionService.Send(ctx, request)
if err != nil {
return common.Hash{}, err
}
return txHash, nil
}