61 lines
1.4 KiB
Go
61 lines
1.4 KiB
Go
|
package evm
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"strings"
|
||
|
"sync"
|
||
|
|
||
|
"github.com/ethereum/go-ethereum/common"
|
||
|
"github.com/pkg/errors"
|
||
|
)
|
||
|
|
||
|
type TokenMapper interface {
|
||
|
AddToken(symbol string, address common.Address)
|
||
|
AddAlias(alias string, symbol string)
|
||
|
GetTokenAddress(symbol string) (common.Address, error)
|
||
|
}
|
||
|
|
||
|
type tokenMapper struct {
|
||
|
aliases map[string]string
|
||
|
tokens map[string]common.Address
|
||
|
lock *sync.Mutex
|
||
|
}
|
||
|
|
||
|
func NewTokenMapper() TokenMapper {
|
||
|
return &tokenMapper{
|
||
|
aliases: make(map[string]string),
|
||
|
tokens: make(map[string]common.Address),
|
||
|
lock: &sync.Mutex{},
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (t *tokenMapper) AddToken(symbol string, address common.Address) {
|
||
|
t.lock.Lock()
|
||
|
defer t.lock.Unlock()
|
||
|
t.tokens[strings.ToUpper(symbol)] = address
|
||
|
}
|
||
|
func (t *tokenMapper) AddAlias(alias string, symbol string) {
|
||
|
t.lock.Lock()
|
||
|
defer t.lock.Unlock()
|
||
|
t.aliases[strings.ToUpper(alias)] = strings.ToUpper(symbol)
|
||
|
}
|
||
|
|
||
|
func (t *tokenMapper) GetTokenAddress(symbol string) (common.Address, error) {
|
||
|
t.lock.Lock()
|
||
|
defer t.lock.Unlock()
|
||
|
symbol = strings.ToUpper(symbol)
|
||
|
lsymbol := symbol
|
||
|
if alias, ok := t.aliases[symbol]; ok {
|
||
|
lsymbol = alias
|
||
|
}
|
||
|
address, ok := t.tokens[lsymbol]
|
||
|
if !ok {
|
||
|
aliasmsg := ""
|
||
|
if lsymbol != symbol {
|
||
|
aliasmsg = fmt.Sprintf(" (alias of %s", symbol)
|
||
|
}
|
||
|
return common.Address{}, errors.Errorf("no address registered for symbol %s%s", lsymbol, aliasmsg)
|
||
|
}
|
||
|
return address, nil
|
||
|
}
|