Skip to content

Commit

Permalink
fix: map error.
Browse files Browse the repository at this point in the history
  • Loading branch information
iosguang committed Apr 15, 2022
1 parent ecd4bac commit b28a318
Show file tree
Hide file tree
Showing 14 changed files with 76 additions and 43 deletions.
8 changes: 4 additions & 4 deletions core/btc/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func QueryBalance(address, chainnet string) (string, error) {

response, err := httpUtil.Request(http.MethodGet, url, nil, nil)
if err != nil {
return "0", err
return "0", eth.MapToBasicError(err)
}

return parseBalanceResponse(response)
Expand All @@ -73,7 +73,7 @@ func QueryBalancePubkey(pubkey, chainnet string) (string, error) {

response, err := httpUtil.Request(http.MethodGet, url, nil, nil)
if err != nil {
return "0", err
return "0", eth.MapToBasicError(err)
}

return parseBalanceResponse(response)
Expand Down Expand Up @@ -119,7 +119,7 @@ func SendRawTransaction(txHex string, chainnet string) (string, error) {

hash, err := client.SendRawTransaction(tx, false)
if err != nil {
return "", err
return "", eth.MapToBasicError(err)
}

return hash.String(), nil
Expand Down Expand Up @@ -151,7 +151,7 @@ func FetchTransactionDetail(hashString, chainnet string) (*TransactionDetail, er

rawResult, err := client.GetRawTransactionVerbose(hash)
if err != nil {
return nil, err
return nil, eth.MapToBasicError(err)
}

status := eth.TransactionStatusPending
Expand Down
2 changes: 1 addition & 1 deletion core/eth/balance.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ func (e *EthChain) Balance(address string) (string, error) {
defer cancel()
result, err := e.RemoteRpcClient.BalanceAt(ctx, common.HexToAddress(address), nil)
if err != nil {
return "0", err
return "0", MapToBasicError(err)
}
return result.String(), nil
}
2 changes: 1 addition & 1 deletion core/eth/chaininfo.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ func GetChainId(e *EthChain) (string, error) {
defer cancel()
chainId, err := e.RemoteRpcClient.ChainID(ctx)
if err != nil {
return "0", err
return "0", MapToBasicError(err)
}

return chainId.String(), nil
Expand Down
3 changes: 2 additions & 1 deletion core/eth/contract.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ func (e *EthChain) CallContractConstant(out interface{}, contractAddress, abiStr
if !ok {
return errors.New("method not found")
}
return e.CallContractConstantWithPayload(out, contractAddress, hex.EncodeToString(inputParams), method.Outputs, opts)
err = e.CallContractConstantWithPayload(out, contractAddress, hex.EncodeToString(inputParams), method.Outputs, opts)
return MapToBasicError(err)
}

func (e *EthChain) CallContractConstantWithPayload(out interface{}, contractAddress, payload string, outputTypes abi.Arguments, opts *bind.CallOpts) error {
Expand Down
8 changes: 4 additions & 4 deletions core/eth/erc20.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ func (e *EthChain) TokenBalance(contractAddress, address string) (string, error)
common.HexToAddress(address),
)
if err != nil {
return "0", err
return "0", MapToBasicError(err)
}

return result.String(), err
Expand All @@ -124,7 +124,7 @@ func (e *EthChain) TokenDecimal(contractAddress string) (string, error) {
nil,
)
if err != nil {
return "0", err
return "0", MapToBasicError(err)
}
tokenDecimal := strconv.Itoa(int(result))
return tokenDecimal, err
Expand All @@ -145,7 +145,7 @@ func (e *EthChain) TokenSymbol(contractAddress string) (string, error) {
nil,
)
if err != nil {
return "", err
return "", MapToBasicError(err)
}

return tokenSymbol, err
Expand All @@ -166,7 +166,7 @@ func (e *EthChain) TokenName(contractAddress string) (string, error) {
nil,
)
if err != nil {
return "", err
return "", MapToBasicError(err)
}

return tokenName, err
Expand Down
4 changes: 2 additions & 2 deletions core/eth/ethchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,13 @@ func (e *EthChain) CreateRemote(rpcUrl string) (*EthChain, error) {
defer cancel()
rpcClient, err := rpc.DialContext(ctx, rpcUrl)
if err != nil {
return nil, err
return nil, MapToBasicError(err)
}

remoteRpcClient := ethclient.NewClient(rpcClient)
chainId, err := remoteRpcClient.ChainID(ctx)
if err != nil {
return nil, err
return nil, MapToBasicError(err)
}
e.chainId = chainId
e.RpcClient = rpcClient
Expand Down
39 changes: 20 additions & 19 deletions core/eth/ethchain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package eth

import (
"testing"
"time"
)

const (
Expand Down Expand Up @@ -42,25 +41,27 @@ func TestConnect(t *testing.T) {
// t.Fatal(err)
// }
// t.Log(chain)
defer func() {
err := recover()
if err != nil {
t.Log("recover err ", err)
}
}()

chain, _ := NewEthChain().CreateRemote(binanceTestRpcUrl)

for i := 0; i < 100; i++ {
time.Sleep(1 * time.Second)
address := "0xed24fc36d5ee211ea25a80239fb8c4cfd80f12ee"
balance, err := chain.TokenBalance(address, address)
if err != nil {
t.Log("...... catched err", err)
} else {
t.Log("...... balance", balance)
}
// rpc := "https://mainnet.sherpax.io/rpc"
// rpc := "https://bsc-dataseed.binance.org"
// rpc := "https://rinkeby.infura.io/v3/da3717f25f824cc1baa32d812386d93f"
rpc := "https://mainnet.infura.io/v3/da3717f25f824cc1baa32d812386d93f"
// rpc := "https://geth-mainnet.coming.chat/"
chain, err := NewEthChain().CreateRemote(rpc)
if err != nil {
t.Fatal(err)
}

t.Log(chain)
// for i := 0; i < 1; i++ {
// time.Sleep(1 * time.Second)
// address := "0xed24fc36d5ee211ea25a80239fb8c4cfd80f12ee"
// balance, err := chain.TokenBalance(address, address)
// if err != nil {
// t.Log("...... catched err", err)
// } else {
// t.Log("...... balance", balance)
// }
// }

// t.Log("should successd connect", chain)
}
8 changes: 6 additions & 2 deletions core/eth/gas.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ func (e *EthChain) EstimateContractGasLimit(
abiStr,
methodName string,
erc20JsonParams string) (string, error) {
var err error
defer func() {
err = MapToBasicError(err)
}()

parsedAbi, err := abi.JSON(strings.NewReader(abiStr))
if err != nil {
Expand Down Expand Up @@ -104,7 +108,7 @@ func (e *EthChain) estimateGasLimit(msg ethereum.CallMsg) (string, error) {
defer cancel()
gasCount, err := e.RemoteRpcClient.EstimateGas(ctx, msg)
if err != nil {
return DEFAULT_ETH_GAS_LIMIT, err
return DEFAULT_ETH_GAS_LIMIT, MapToBasicError(err)
}
gasLimitStr := strconv.FormatUint(gasCount, 10)
return gasLimitStr, nil
Expand Down Expand Up @@ -139,7 +143,7 @@ func (e *EthChain) EstimateGasLimit(fromAddress string, receiverAddress string,
msg := ethereum.CallMsg{From: from, To: &contractAddressObj, GasPrice: price, Value: value, Data: input}
gasLimit, err := e.estimateGasLimit(msg)
if err != nil {
return DEFAULT_ETH_GAS_LIMIT, err
return DEFAULT_ETH_GAS_LIMIT, MapToBasicError(err)
}
gasLimitDecimal, err := decimal.NewFromString(gasLimit)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion core/eth/nonce.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ func (e *EthChain) Nonce(spenderAddressHex string) (string, error) {
defer cancel()
nonce, err := e.RemoteRpcClient.PendingNonceAt(ctx, common.HexToAddress(spenderAddressHex))
if err != nil {
return "0", err
return "0", MapToBasicError(err)
}
return strconv.FormatUint(nonce, 10), nil
}
2 changes: 1 addition & 1 deletion core/eth/sendTx.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ func (e *EthChain) SendRawTransaction(txHex string) (string, error) {
defer cancel()
err := e.RpcClient.CallContext(ctx, &hash, "eth_sendRawTransaction", txHex)
if err != nil {
return "", err
return "", MapToBasicError(err)
}
return hash.String(), nil
}
5 changes: 5 additions & 0 deletions core/eth/transactionDetail.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,11 @@ func NewTransactionDetailWithJsonString(s string) *TransactionDetail {
// @param hashString 交易的 hash
// @return 详情对象,该对象无法提供 CID 信息
func (e *EthChain) FetchTransactionDetail(hashString string) (*TransactionDetail, error) {
var err error
defer func() {
err = MapToBasicError(err)
}()

ctx, cancel := context.WithTimeout(context.Background(), e.timeout)
defer cancel()
tx, isPending, err := e.RemoteRpcClient.TransactionByHash(ctx, common.HexToHash(hashString))
Expand Down
9 changes: 9 additions & 0 deletions core/eth/util.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package eth

import (
"errors"
"math/big"
"strconv"
"sync"
Expand Down Expand Up @@ -113,3 +114,11 @@ func MapListConcurrentStringToString(strList []string, maper func(string) (strin
}
return result, nil
}

// 将任何其他自定义类型的 error, 转为系统基础的 error 对象
func MapToBasicError(e error) error {
if e == nil {
return e
}
return errors.New(e.Error())
}
22 changes: 17 additions & 5 deletions core/wallet/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,9 @@ func (c *PolkaChain) QueryBalancePubkey(pubkey string) (*PolkaBalance, error) {

func (c *PolkaChain) queryBalance(pubkey []byte) (b *PolkaBalance, err error) {
b = emptyBalance()
defer func() {
err = eth.MapToBasicError(err)
}()

client, err := getConnectedPolkaClient(c.RpcUrl)
if err != nil {
Expand Down Expand Up @@ -166,6 +169,9 @@ func (c *PolkaChain) queryBalance(pubkey []byte) (b *PolkaBalance, err error) {
// 只能通过 chainx 链对象来查询,其他链会抛出 error
func (c *PolkaChain) QueryBalanceXBTC(address string) (b *PolkaBalance, err error) {
b = emptyBalance()
defer func() {
err = eth.MapToBasicError(err)
}()

client, err := getConnectedPolkaClient(c.RpcUrl)
if err != nil {
Expand Down Expand Up @@ -223,6 +229,9 @@ func (c *PolkaChain) QueryBalanceXBTC(address string) (b *PolkaBalance, err erro
func (c *PolkaChain) EstimateFeeForTransaction(transaction *Transaction) (s string, err error) {
s = "0"
wallet := mockWallet()
defer func() {
err = eth.MapToBasicError(err)
}()

fakeHash := "0x38c5a9f6fabb8d8583ed633c469cdeefb988b0d2384937b15e10e9c0a75aa744"
signData, err := transaction.GetSignData(fakeHash, 0, 0, 0)
Expand Down Expand Up @@ -259,6 +268,9 @@ func (c *PolkaChain) EstimateFeeForTransaction(transaction *Transaction) (s stri

// 发起交易
func (c *PolkaChain) SendRawTransaction(txHex string) (s string, err error) {
defer func() {
err = eth.MapToBasicError(err)
}()
client, err := getConnectedPolkaClient(c.RpcUrl)
if err != nil {
return
Expand Down Expand Up @@ -356,17 +368,17 @@ func (t *Transaction) GetSignDataFromChain(chain *PolkaChain, walletAddress stri
var nonce int64
err = client.CallWithBlockHash(cl.api.Client, &nonce, "system_accountNextIndex", nil, walletAddress)
if err != nil {
return nil, err
return nil, eth.MapToBasicError(err)
}

genesisHash, err := cl.api.RPC.Chain.GetBlockHash(0)
if err != nil {
return nil, err
return nil, eth.MapToBasicError(err)
}

runtimeVersion, err := cl.api.RPC.State.GetRuntimeVersionLatest()
if err != nil {
return nil, err
return nil, eth.MapToBasicError(err)
}

return t.GetSignData(genesisHash.Hex(), nonce, int32(runtimeVersion.SpecVersion), int32(runtimeVersion.TransactionVersion))
Expand All @@ -393,7 +405,7 @@ func (c *PolkaChain) FetchScriptHashForMiniX(transferTo, amount string) (*MiniXS

signedBlock, err := cl.api.RPC.Chain.GetBlockLatest()
if err != nil {
return nil, err
return nil, eth.MapToBasicError(err)
}
blockNumber := uint64(signedBlock.Block.Header.Number)
arrNumber := make([]uint64, 0)
Expand All @@ -409,7 +421,7 @@ func (c *PolkaChain) FetchScriptHashForMiniX(transferTo, amount string) (*MiniXS
param["params"] = arr
body, err := c.post(c.RpcUrl, param)
if err != nil {
return nil, err
return nil, eth.MapToBasicError(err)
}
value := make(map[string]interface{})
err = json.Unmarshal(body, &value)
Expand Down
5 changes: 3 additions & 2 deletions core/wallet/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (

gsrpc "github.com/centrifuge/go-substrate-rpc-client/v4"
"github.com/centrifuge/go-substrate-rpc-client/v4/types"
"github.com/coming-chat/wallet-SDK/core/eth"
)

type polkaclient struct {
Expand Down Expand Up @@ -35,7 +36,7 @@ func (c *polkaclient) connectApiIfNeeded() error {
if c.api == nil {
api, err := gsrpc.NewSubstrateAPI(c.rpcUrl)
if err != nil {
return err
return eth.MapToBasicError(err)
}
c.api = api
}
Expand All @@ -49,7 +50,7 @@ func (c *polkaclient) ReloadMetadata() error {
}
meta, err := c.api.RPC.State.GetMetadataLatest()
if err != nil {
return err
return eth.MapToBasicError(err)
}
c.metadata = meta
return nil
Expand Down

0 comments on commit b28a318

Please sign in to comment.