*: replace all NEP5 occurences to NEP17

This commit is contained in:
Evgenii Stratonikov 2020-11-24 11:14:25 +03:00
parent b97dfae8d8
commit 31eca342eb
33 changed files with 335 additions and 335 deletions

View file

@ -16,7 +16,7 @@ func TestRegisterCandidate(t *testing.T) {
defer e.Close(t)
e.In.WriteString("one\r")
e.Run(t, "neo-go", "wallet", "nep5", "multitransfer",
e.Run(t, "neo-go", "wallet", "nep17", "multitransfer",
"--rpc-endpoint", "http://"+e.RPC.Addr,
"--wallet", validatorWallet,
"--from", validatorAddr,

View file

@ -51,7 +51,7 @@ func TestSignMultisigTx(t *testing.T) {
// Transfer funds to the multisig.
e.In.WriteString("one\r")
e.Run(t, "neo-go", "wallet", "nep5", "multitransfer",
e.Run(t, "neo-go", "wallet", "nep17", "multitransfer",
"--rpc-endpoint", "http://"+e.RPC.Addr,
"--wallet", validatorWallet,
"--from", validatorAddr,
@ -66,7 +66,7 @@ func TestSignMultisigTx(t *testing.T) {
txPath := path.Join(tmpDir, "multisigtx.json")
defer os.Remove(txPath)
e.In.WriteString("pass\r")
e.Run(t, "neo-go", "wallet", "nep5", "transfer",
e.Run(t, "neo-go", "wallet", "nep17", "transfer",
"--rpc-endpoint", "http://"+e.RPC.Addr,
"--wallet", wallet1Path, "--from", multisigAddr,
"--to", priv.Address(), "--token", "neo", "--amount", "1",

View file

@ -15,10 +15,10 @@ import (
"github.com/stretchr/testify/require"
)
func TestNEP5Balance(t *testing.T) {
func TestNEP17Balance(t *testing.T) {
e := newExecutor(t, true)
defer e.Close(t)
cmdbalance := []string{"neo-go", "wallet", "nep5", "balance"}
cmdbalance := []string{"neo-go", "wallet", "nep17", "balance"}
cmdbase := append(cmdbalance,
"--rpc-endpoint", "http://"+e.RPC.Addr,
"--wallet", validatorWallet,
@ -99,7 +99,7 @@ func TestNEP5Balance(t *testing.T) {
return
}
func TestNEP5Transfer(t *testing.T) {
func TestNEP17Transfer(t *testing.T) {
w, err := wallet.NewWalletFromFile("testdata/testwallet.json")
require.NoError(t, err)
defer w.Close()
@ -107,7 +107,7 @@ func TestNEP5Transfer(t *testing.T) {
e := newExecutor(t, true)
defer e.Close(t)
args := []string{
"neo-go", "wallet", "nep5", "transfer",
"neo-go", "wallet", "nep17", "transfer",
"--rpc-endpoint", "http://" + e.RPC.Addr,
"--wallet", validatorWallet,
"--from", validatorAddr,
@ -132,7 +132,7 @@ func TestNEP5Transfer(t *testing.T) {
require.Equal(t, big.NewInt(1), b)
}
func TestNEP5MultiTransfer(t *testing.T) {
func TestNEP17MultiTransfer(t *testing.T) {
privs, _ := generateKeys(t, 3)
e := newExecutor(t, true)
@ -140,7 +140,7 @@ func TestNEP5MultiTransfer(t *testing.T) {
neoContractHash, err := e.Chain.GetNativeContractScriptHash("neo")
require.NoError(t, err)
args := []string{
"neo-go", "wallet", "nep5", "multitransfer",
"neo-go", "wallet", "nep17", "multitransfer",
"--rpc-endpoint", "http://" + e.RPC.Addr,
"--wallet", validatorWallet,
"--from", validatorAddr,
@ -161,7 +161,7 @@ func TestNEP5MultiTransfer(t *testing.T) {
require.Equal(t, big.NewInt(13), b)
}
func TestNEP5ImportToken(t *testing.T) {
func TestNEP17ImportToken(t *testing.T) {
e := newExecutor(t, true)
defer e.Close(t)
@ -174,11 +174,11 @@ func TestNEP5ImportToken(t *testing.T) {
gasContractHash, err := e.Chain.GetNativeContractScriptHash("gas")
require.NoError(t, err)
e.Run(t, "neo-go", "wallet", "init", "--wallet", walletPath)
e.Run(t, "neo-go", "wallet", "nep5", "import",
e.Run(t, "neo-go", "wallet", "nep17", "import",
"--rpc-endpoint", "http://"+e.RPC.Addr,
"--wallet", walletPath,
"--token", gasContractHash.StringLE())
e.Run(t, "neo-go", "wallet", "nep5", "import",
e.Run(t, "neo-go", "wallet", "nep17", "import",
"--rpc-endpoint", "http://"+e.RPC.Addr,
"--wallet", walletPath,
"--token", neoContractHash.StringLE())
@ -192,12 +192,12 @@ func TestNEP5ImportToken(t *testing.T) {
e.checkNextLine(t, "^Address:\\s*"+address.Uint160ToString(gasContractHash))
}
t.Run("WithToken", func(t *testing.T) {
e.Run(t, "neo-go", "wallet", "nep5", "info",
e.Run(t, "neo-go", "wallet", "nep17", "info",
"--wallet", walletPath, "--token", gasContractHash.StringLE())
checkGASInfo(t)
})
t.Run("NoToken", func(t *testing.T) {
e.Run(t, "neo-go", "wallet", "nep5", "info",
e.Run(t, "neo-go", "wallet", "nep17", "info",
"--wallet", walletPath)
checkGASInfo(t)
_, err := e.Out.ReadString('\n')
@ -210,9 +210,9 @@ func TestNEP5ImportToken(t *testing.T) {
})
t.Run("Remove", func(t *testing.T) {
e.In.WriteString("y\r")
e.Run(t, "neo-go", "wallet", "nep5", "remove",
e.Run(t, "neo-go", "wallet", "nep17", "remove",
"--wallet", walletPath, "--token", neoContractHash.StringLE())
e.Run(t, "neo-go", "wallet", "nep5", "info",
e.Run(t, "neo-go", "wallet", "nep17", "info",
"--wallet", walletPath)
checkGASInfo(t)
_, err := e.Out.ReadString('\n')

View file

@ -26,7 +26,7 @@ var (
}
)
func newNEP5Commands() []cli.Command {
func newNEP17Commands() []cli.Command {
balanceFlags := []cli.Flag{
walletPathFlag,
tokenFlag,
@ -69,21 +69,21 @@ func newNEP5Commands() []cli.Command {
Name: "balance",
Usage: "get address balance",
UsageText: "balance --wallet <path> --rpc-endpoint <node> [--timeout <time>] [--address <address>] [--token <hash-or-name>]",
Action: getNEP5Balance,
Action: getNEP17Balance,
Flags: balanceFlags,
},
{
Name: "import",
Usage: "import NEP5 token to a wallet",
Usage: "import NEP17 token to a wallet",
UsageText: "import --wallet <path> --rpc-endpoint <node> --timeout <time> --token <hash>",
Action: importNEP5Token,
Action: importNEP17Token,
Flags: importFlags,
},
{
Name: "info",
Usage: "print imported NEP5 token info",
Usage: "print imported NEP17 token info",
UsageText: "print --wallet <path> [--token <hash-or-name>]",
Action: printNEP5Info,
Action: printNEP17Info,
Flags: []cli.Flag{
walletPathFlag,
cli.StringFlag{
@ -94,9 +94,9 @@ func newNEP5Commands() []cli.Command {
},
{
Name: "remove",
Usage: "remove NEP5 token from the wallet",
Usage: "remove NEP17 token from the wallet",
UsageText: "remove --wallet <path> --token <hash-or-name>",
Action: removeNEP5Token,
Action: removeNEP17Token,
Flags: []cli.Flag{
walletPathFlag,
cli.StringFlag{
@ -108,23 +108,23 @@ func newNEP5Commands() []cli.Command {
},
{
Name: "transfer",
Usage: "transfer NEP5 tokens",
Usage: "transfer NEP17 tokens",
UsageText: "transfer --wallet <path> --rpc-endpoint <node> --timeout <time> --from <addr> --to <addr> --token <hash> --amount string",
Action: transferNEP5,
Action: transferNEP17,
Flags: transferFlags,
},
{
Name: "multitransfer",
Usage: "transfer NEP5 tokens to multiple recipients",
Usage: "transfer NEP17 tokens to multiple recipients",
UsageText: `multitransfer --wallet <path> --rpc-endpoint <node> --timeout <time> --from <addr>` +
` <token1>:<addr1>:<amount1> [<token2>:<addr2>:<amount2> [...]]`,
Action: multiTransferNEP5,
Action: multiTransferNEP17,
Flags: multiTransferFlags,
},
}
}
func getNEP5Balance(ctx *cli.Context) error {
func getNEP17Balance(ctx *cli.Context) error {
var accounts []*wallet.Account
wall, err := openWallet(ctx.String("wallet"))
@ -170,7 +170,7 @@ func getNEP5Balance(ctx *cli.Context) error {
if err != nil {
return cli.NewExitError(fmt.Errorf("invalid account address: %w", err), 1)
}
balances, err := c.GetNEP5Balances(addrHash)
balances, err := c.GetNEP17Balances(addrHash)
if err != nil {
return cli.NewExitError(err, 1)
}
@ -186,7 +186,7 @@ func getNEP5Balance(ctx *cli.Context) error {
asset := balances.Balances[i].Asset
token, err := getMatchingToken(ctx, wall, asset.StringLE())
if err != nil {
token, err = c.NEP5TokenInfo(asset)
token, err = c.NEP17TokenInfo(asset)
}
if err == nil {
if name != "" && !(token.Name == name || token.Symbol == name || token.Address() == name || token.Hash.StringLE() == name) {
@ -215,12 +215,12 @@ func getMatchingToken(ctx *cli.Context, w *wallet.Wallet, name string) (*wallet.
}
func getMatchingTokenRPC(ctx *cli.Context, c *client.Client, addr util.Uint160, name string) (*wallet.Token, error) {
bs, err := c.GetNEP5Balances(addr)
bs, err := c.GetNEP17Balances(addr)
if err != nil {
return nil, err
}
get := func(i int) *wallet.Token {
t, _ := c.NEP5TokenInfo(bs.Balances[i].Asset)
t, _ := c.NEP17TokenInfo(bs.Balances[i].Asset)
return t
}
return getMatchingTokenAux(ctx, get, len(bs.Balances), name)
@ -247,7 +247,7 @@ func getMatchingTokenAux(ctx *cli.Context, get func(i int) *wallet.Token, n int,
return token, nil
}
func importNEP5Token(ctx *cli.Context) error {
func importNEP17Token(ctx *cli.Context) error {
wall, err := openWallet(ctx.String("wallet"))
if err != nil {
return cli.NewExitError(err, 1)
@ -274,7 +274,7 @@ func importNEP5Token(ctx *cli.Context) error {
return cli.NewExitError(err, 1)
}
tok, err := c.NEP5TokenInfo(tokenHash)
tok, err := c.NEP17TokenInfo(tokenHash)
if err != nil {
return cli.NewExitError(fmt.Errorf("can't receive token info: %w", err), 1)
}
@ -296,7 +296,7 @@ func printTokenInfo(ctx *cli.Context, tok *wallet.Token) {
fmt.Fprintf(w, "Address: %s\n", tok.Address())
}
func printNEP5Info(ctx *cli.Context) error {
func printNEP17Info(ctx *cli.Context) error {
wall, err := openWallet(ctx.String("wallet"))
if err != nil {
return cli.NewExitError(err, 1)
@ -321,7 +321,7 @@ func printNEP5Info(ctx *cli.Context) error {
return nil
}
func removeNEP5Token(ctx *cli.Context) error {
func removeNEP17Token(ctx *cli.Context) error {
wall, err := openWallet(ctx.String("wallet"))
if err != nil {
return cli.NewExitError(err, 1)
@ -345,7 +345,7 @@ func removeNEP5Token(ctx *cli.Context) error {
return nil
}
func multiTransferNEP5(ctx *cli.Context) error {
func multiTransferNEP17(ctx *cli.Context) error {
wall, err := openWallet(ctx.String("wallet"))
if err != nil {
return cli.NewExitError(err, 1)
@ -412,7 +412,7 @@ func multiTransferNEP5(ctx *cli.Context) error {
return signAndSendTransfer(ctx, c, acc, recipients)
}
func transferNEP5(ctx *cli.Context) error {
func transferNEP17(ctx *cli.Context) error {
wall, err := openWallet(ctx.String("wallet"))
if err != nil {
return cli.NewExitError(err, 1)
@ -464,7 +464,7 @@ func transferNEP5(ctx *cli.Context) error {
func signAndSendTransfer(ctx *cli.Context, c *client.Client, acc *wallet.Account, recipients []client.TransferTarget) error {
gas := flags.Fixed8FromContext(ctx, "gas")
tx, err := c.CreateNEP5MultiTransferTx(acc, int64(gas), recipients...)
tx, err := c.CreateNEP17MultiTransferTx(acc, int64(gas), recipients...)
if err != nil {
return cli.NewExitError(err, 1)
}

View file

@ -195,9 +195,9 @@ func NewCommands() []cli.Command {
Subcommands: newMultisigCommands(),
},
{
Name: "nep5",
Usage: "work with NEP5 contracts",
Subcommands: newNEP5Commands(),
Name: "nep17",
Usage: "work with NEP17 contracts",
Subcommands: newNEP17Commands(),
},
{
Name: "candidate",
@ -237,7 +237,7 @@ func claimGas(ctx *cli.Context) error {
if err != nil {
return cli.NewExitError(err, 1)
}
hash, err := c.TransferNEP5(acc, scriptHash, neoContractHash, 0, 0)
hash, err := c.TransferNEP17(acc, scriptHash, neoContractHash, 0, 0)
if err != nil {
return cli.NewExitError(err, 1)
}

View file

@ -178,7 +178,7 @@ func TestClaimGas(t *testing.T) {
defer w.Close()
args := []string{
"neo-go", "wallet", "nep5", "multitransfer",
"neo-go", "wallet", "nep17", "multitransfer",
"--rpc-endpoint", "http://" + e.RPC.Addr,
"--wallet", validatorWallet,
"--from", validatorAddr,
@ -258,7 +258,7 @@ func TestImportDeployed(t *testing.T) {
t.Run("Sign", func(t *testing.T) {
e.In.WriteString("one\r")
e.Run(t, "neo-go", "wallet", "nep5", "multitransfer",
e.Run(t, "neo-go", "wallet", "nep17", "multitransfer",
"--rpc-endpoint", "http://"+e.RPC.Addr,
"--wallet", validatorWallet, "--from", validatorAddr,
"neo:"+contractAddr+":10",
@ -269,7 +269,7 @@ func TestImportDeployed(t *testing.T) {
require.NoError(t, err)
e.In.WriteString("pass\r")
e.Run(t, "neo-go", "wallet", "nep5", "transfer",
e.Run(t, "neo-go", "wallet", "nep17", "transfer",
"--rpc-endpoint", "http://"+e.RPC.Addr,
"--wallet", walletPath, "--from", contractAddr,
"--to", privTo.Address(), "--token", "neo", "--amount", "1")

View file

@ -43,8 +43,8 @@ which would yield the response:
| `getblocksysfee` |
| `getconnectioncount` |
| `getcontractstate` |
| `getnep5balances` |
| `getnep5transfers` |
| `getnep17balances` |
| `getnep17transfers` |
| `getpeers` |
| `getrawmempool` |
| `getrawtransaction` |
@ -108,9 +108,9 @@ and we're not accepting issues related to them.
Some additional extensions are implemented as a part of this RPC server.
#### Limits and paging for getnep5transfers
#### Limits and paging for getnep17transfers
`getnep5transfers` RPC call never returns more than 1000 results for one
`getnep17transfers` RPC call never returns more than 1000 results for one
request (within specified time frame). You can pass your own limit via an
additional parameter and then use paging to request the next batch of
transfers.
@ -119,14 +119,14 @@ Example requesting 10 events for address NbTiM6h8r99kpRtb428XcsUk1TzKed2gTc
within 0-1600094189 timestamps:
```json
{ "jsonrpc": "2.0", "id": 5, "method": "getnep5transfers", "params":
{ "jsonrpc": "2.0", "id": 5, "method": "getnep17transfers", "params":
["NbTiM6h8r99kpRtb428XcsUk1TzKed2gTc", 0, 1600094189, 10] }
```
Get the next 10 transfers for the same account within the same time frame:
```json
{ "jsonrpc": "2.0", "id": 5, "method": "getnep5transfers", "params":
{ "jsonrpc": "2.0", "id": 5, "method": "getnep17transfers", "params":
["NbTiM6h8r99kpRtb428XcsUk1TzKed2gTc", 0, 1600094189, 10, 1] }
```

View file

@ -1,4 +1,4 @@
package nep5
package nep17
import (
"github.com/nspcc-dev/neo-go/pkg/interop/runtime"

View file

@ -1,7 +1,7 @@
package tokencontract
import (
"github.com/nspcc-dev/neo-go/examples/token/nep5"
"github.com/nspcc-dev/neo-go/examples/token/nep17"
"github.com/nspcc-dev/neo-go/pkg/interop"
"github.com/nspcc-dev/neo-go/pkg/interop/storage"
"github.com/nspcc-dev/neo-go/pkg/interop/util"
@ -14,14 +14,14 @@ const (
var (
owner = util.FromAddress("NULwe3UAHckN2fzNdcVg31tDiaYtMDwANt")
token nep5.Token
token nep17.Token
ctx storage.Context
)
// init initializes the Token Interface and storage context for the Smart
// Contract to operate with
func init() {
token = nep5.Token{
token = nep17.Token{
Name: "Awesome NEO Token",
Symbol: "ANT",
Decimals: decimals,

View file

@ -791,7 +791,7 @@ func (bc *Blockchain) handleNotification(note *state.NotificationEvent, d *dao.C
}
amount = bigint.FromBytes(bs)
}
bc.processNEP5Transfer(d, h, b, note.ScriptHash, from, to, amount)
bc.processNEP17Transfer(d, h, b, note.ScriptHash, from, to, amount)
}
func parseUint160(addr []byte) util.Uint160 {
@ -801,7 +801,7 @@ func parseUint160(addr []byte) util.Uint160 {
return util.Uint160{}
}
func (bc *Blockchain) processNEP5Transfer(cache *dao.Cached, h util.Uint256, b *block.Block, sc util.Uint160, from, to []byte, amount *big.Int) {
func (bc *Blockchain) processNEP17Transfer(cache *dao.Cached, h util.Uint256, b *block.Block, sc util.Uint160, from, to []byte, amount *big.Int) {
toAddr := parseUint160(to)
fromAddr := parseUint160(from)
var id int32
@ -815,7 +815,7 @@ func (bc *Blockchain) processNEP5Transfer(cache *dao.Cached, h util.Uint256, b *
}
id = assetContract.ID
}
transfer := &state.NEP5Transfer{
transfer := &state.NEP17Transfer{
Asset: id,
From: fromAddr,
To: toAddr,
@ -824,7 +824,7 @@ func (bc *Blockchain) processNEP5Transfer(cache *dao.Cached, h util.Uint256, b *
Tx: h,
}
if !fromAddr.Equals(util.Uint160{}) {
balances, err := cache.GetNEP5Balances(fromAddr)
balances, err := cache.GetNEP17Balances(fromAddr)
if err != nil {
return
}
@ -833,19 +833,19 @@ func (bc *Blockchain) processNEP5Transfer(cache *dao.Cached, h util.Uint256, b *
bs.LastUpdatedBlock = b.Index
balances.Trackers[id] = bs
transfer.Amount = *new(big.Int).Sub(&transfer.Amount, amount)
isBig, err := cache.AppendNEP5Transfer(fromAddr, balances.NextTransferBatch, transfer)
isBig, err := cache.AppendNEP17Transfer(fromAddr, balances.NextTransferBatch, transfer)
if err != nil {
return
}
if isBig {
balances.NextTransferBatch++
}
if err := cache.PutNEP5Balances(fromAddr, balances); err != nil {
if err := cache.PutNEP17Balances(fromAddr, balances); err != nil {
return
}
}
if !toAddr.Equals(util.Uint160{}) {
balances, err := cache.GetNEP5Balances(toAddr)
balances, err := cache.GetNEP17Balances(toAddr)
if err != nil {
return
}
@ -855,27 +855,27 @@ func (bc *Blockchain) processNEP5Transfer(cache *dao.Cached, h util.Uint256, b *
balances.Trackers[id] = bs
transfer.Amount = *amount
isBig, err := cache.AppendNEP5Transfer(toAddr, balances.NextTransferBatch, transfer)
isBig, err := cache.AppendNEP17Transfer(toAddr, balances.NextTransferBatch, transfer)
if err != nil {
return
}
if isBig {
balances.NextTransferBatch++
}
if err := cache.PutNEP5Balances(toAddr, balances); err != nil {
if err := cache.PutNEP17Balances(toAddr, balances); err != nil {
return
}
}
}
// ForEachNEP5Transfer executes f for each nep5 transfer in log.
func (bc *Blockchain) ForEachNEP5Transfer(acc util.Uint160, f func(*state.NEP5Transfer) (bool, error)) error {
balances, err := bc.dao.GetNEP5Balances(acc)
// ForEachNEP17Transfer executes f for each nep17 transfer in log.
func (bc *Blockchain) ForEachNEP17Transfer(acc util.Uint160, f func(*state.NEP17Transfer) (bool, error)) error {
balances, err := bc.dao.GetNEP17Balances(acc)
if err != nil {
return nil
}
for i := int(balances.NextTransferBatch); i >= 0; i-- {
lg, err := bc.dao.GetNEP5TransferLog(acc, uint32(i))
lg, err := bc.dao.GetNEP17TransferLog(acc, uint32(i))
if err != nil {
return nil
}
@ -890,9 +890,9 @@ func (bc *Blockchain) ForEachNEP5Transfer(acc util.Uint160, f func(*state.NEP5Tr
return nil
}
// GetNEP5Balances returns NEP5 balances for the acc.
func (bc *Blockchain) GetNEP5Balances(acc util.Uint160) *state.NEP5Balances {
bs, err := bc.dao.GetNEP5Balances(acc)
// GetNEP17Balances returns NEP17 balances for the acc.
func (bc *Blockchain) GetNEP17Balances(acc util.Uint160) *state.NEP17Balances {
bs, err := bc.dao.GetNEP17Balances(acc)
if err != nil {
return nil
}
@ -901,7 +901,7 @@ func (bc *Blockchain) GetNEP5Balances(acc util.Uint160) *state.NEP5Balances {
// GetUtilityTokenBalance returns utility token (GAS) balance for the acc.
func (bc *Blockchain) GetUtilityTokenBalance(acc util.Uint160) *big.Int {
bs, err := bc.dao.GetNEP5Balances(acc)
bs, err := bc.dao.GetNEP17Balances(acc)
if err != nil {
return big.NewInt(0)
}
@ -912,7 +912,7 @@ func (bc *Blockchain) GetUtilityTokenBalance(acc util.Uint160) *big.Int {
// GetGoverningTokenBalance returns governing token (NEO) balance and the height
// of the last balance change for the account.
func (bc *Blockchain) GetGoverningTokenBalance(acc util.Uint160) (*big.Int, uint32) {
bs, err := bc.dao.GetNEP5Balances(acc)
bs, err := bc.dao.GetNEP17Balances(acc)
if err != nil {
return big.NewInt(0), 0
}

View file

@ -129,7 +129,7 @@ func TestAddBlockStateRoot(t *testing.T) {
sr, err := bc.GetStateRoot(bc.BlockHeight())
require.NoError(t, err)
tx := newNEP5Transfer(bc.contracts.NEO.Hash, neoOwner, util.Uint160{}, 1)
tx := newNEP17Transfer(bc.contracts.NEO.Hash, neoOwner, util.Uint160{}, 1)
tx.ValidUntilBlock = bc.BlockHeight() + 1
addSigners(tx)
require.NoError(t, signTx(bc, tx))

View file

@ -32,7 +32,7 @@ type Blockchainer interface {
GetContractScriptHash(id int32) (util.Uint160, error)
GetEnrollments() ([]state.Validator, error)
GetGoverningTokenBalance(acc util.Uint160) (*big.Int, uint32)
ForEachNEP5Transfer(util.Uint160, func(*state.NEP5Transfer) (bool, error)) error
ForEachNEP17Transfer(util.Uint160, func(*state.NEP17Transfer) (bool, error)) error
GetHeaderHash(int) util.Uint256
GetHeader(hash util.Uint256) (*block.Header, error)
CurrentHeaderHash() util.Uint256
@ -42,7 +42,7 @@ type Blockchainer interface {
GetAppExecResults(util.Uint256, trigger.Type) ([]state.AppExecResult, error)
GetNativeContractScriptHash(string) (util.Uint160, error)
GetNextBlockValidators() ([]*keys.PublicKey, error)
GetNEP5Balances(util.Uint160) *state.NEP5Balances
GetNEP17Balances(util.Uint160) *state.NEP17Balances
GetValidators() ([]*keys.PublicKey, error)
GetStandByCommittee() keys.PublicKeys
GetStandByValidators() keys.PublicKeys

View file

@ -14,17 +14,17 @@ import (
type Cached struct {
DAO
contracts map[util.Uint160]*state.Contract
balances map[util.Uint160]*state.NEP5Balances
transfers map[util.Uint160]map[uint32]*state.NEP5TransferLog
balances map[util.Uint160]*state.NEP17Balances
transfers map[util.Uint160]map[uint32]*state.NEP17TransferLog
dropNEP5Cache bool
dropNEP17Cache bool
}
// NewCached returns new Cached wrapping around given backing store.
func NewCached(d DAO) *Cached {
ctrs := make(map[util.Uint160]*state.Contract)
balances := make(map[util.Uint160]*state.NEP5Balances)
transfers := make(map[util.Uint160]map[uint32]*state.NEP5TransferLog)
balances := make(map[util.Uint160]*state.NEP17Balances)
transfers := make(map[util.Uint160]map[uint32]*state.NEP17TransferLog)
return &Cached{d.GetWrapped(), ctrs, balances, transfers, false}
}
@ -52,50 +52,50 @@ func (cd *Cached) DeleteContractState(hash util.Uint160) error {
return cd.DAO.DeleteContractState(hash)
}
// GetNEP5Balances retrieves NEP5Balances for the acc.
func (cd *Cached) GetNEP5Balances(acc util.Uint160) (*state.NEP5Balances, error) {
// GetNEP17Balances retrieves NEP17Balances for the acc.
func (cd *Cached) GetNEP17Balances(acc util.Uint160) (*state.NEP17Balances, error) {
if bs := cd.balances[acc]; bs != nil {
return bs, nil
}
return cd.DAO.GetNEP5Balances(acc)
return cd.DAO.GetNEP17Balances(acc)
}
// PutNEP5Balances saves NEP5Balances for the acc.
func (cd *Cached) PutNEP5Balances(acc util.Uint160, bs *state.NEP5Balances) error {
// PutNEP17Balances saves NEP17Balances for the acc.
func (cd *Cached) PutNEP17Balances(acc util.Uint160, bs *state.NEP17Balances) error {
cd.balances[acc] = bs
return nil
}
// GetNEP5TransferLog retrieves NEP5TransferLog for the acc.
func (cd *Cached) GetNEP5TransferLog(acc util.Uint160, index uint32) (*state.NEP5TransferLog, error) {
// GetNEP17TransferLog retrieves NEP17TransferLog for the acc.
func (cd *Cached) GetNEP17TransferLog(acc util.Uint160, index uint32) (*state.NEP17TransferLog, error) {
ts := cd.transfers[acc]
if ts != nil && ts[index] != nil {
return ts[index], nil
}
return cd.DAO.GetNEP5TransferLog(acc, index)
return cd.DAO.GetNEP17TransferLog(acc, index)
}
// PutNEP5TransferLog saves NEP5TransferLog for the acc.
func (cd *Cached) PutNEP5TransferLog(acc util.Uint160, index uint32, bs *state.NEP5TransferLog) error {
// PutNEP17TransferLog saves NEP17TransferLog for the acc.
func (cd *Cached) PutNEP17TransferLog(acc util.Uint160, index uint32, bs *state.NEP17TransferLog) error {
ts := cd.transfers[acc]
if ts == nil {
ts = make(map[uint32]*state.NEP5TransferLog, 2)
ts = make(map[uint32]*state.NEP17TransferLog, 2)
cd.transfers[acc] = ts
}
ts[index] = bs
return nil
}
// AppendNEP5Transfer appends new transfer to a transfer event log.
func (cd *Cached) AppendNEP5Transfer(acc util.Uint160, index uint32, tr *state.NEP5Transfer) (bool, error) {
lg, err := cd.GetNEP5TransferLog(acc, index)
// AppendNEP17Transfer appends new transfer to a transfer event log.
func (cd *Cached) AppendNEP17Transfer(acc util.Uint160, index uint32, tr *state.NEP17Transfer) (bool, error) {
lg, err := cd.GetNEP17TransferLog(acc, index)
if err != nil {
return false, err
}
if err := lg.Append(tr); err != nil {
return false, err
}
return lg.Size() >= state.NEP5TransferBatchSize, cd.PutNEP5TransferLog(acc, index, lg)
return lg.Size() >= state.NEP17TransferBatchSize, cd.PutNEP17TransferLog(acc, index, lg)
}
// Persist flushes all the changes made into the (supposedly) persistent
@ -107,8 +107,8 @@ func (cd *Cached) Persist() (int, error) {
// usage scenario it should be good enough if cd doesn't modify object
// caches (accounts/contracts/etc) in any way.
if ok {
if cd.dropNEP5Cache {
lowerCache.balances = make(map[util.Uint160]*state.NEP5Balances)
if cd.dropNEP17Cache {
lowerCache.balances = make(map[util.Uint160]*state.NEP17Balances)
}
var simpleCache *Simple
for simpleCache == nil {
@ -125,7 +125,7 @@ func (cd *Cached) Persist() (int, error) {
buf := io.NewBufBinWriter()
for acc, bs := range cd.balances {
err := cd.DAO.putNEP5Balances(acc, bs, buf)
err := cd.DAO.putNEP17Balances(acc, bs, buf)
if err != nil {
return 0, err
}
@ -133,7 +133,7 @@ func (cd *Cached) Persist() (int, error) {
}
for acc, ts := range cd.transfers {
for ind, lg := range ts {
err := cd.DAO.PutNEP5TransferLog(acc, ind, lg)
err := cd.DAO.PutNEP17TransferLog(acc, ind, lg)
if err != nil {
return 0, err
}

View file

@ -31,7 +31,7 @@ var (
// DAO is a data access object.
type DAO interface {
AppendAppExecResult(aer *state.AppExecResult, buf *io.BufBinWriter) error
AppendNEP5Transfer(acc util.Uint160, index uint32, tr *state.NEP5Transfer) (bool, error)
AppendNEP17Transfer(acc util.Uint160, index uint32, tr *state.NEP17Transfer) (bool, error)
DeleteContractState(hash util.Uint160) error
DeleteStorageItem(id int32, key []byte) error
GetAndDecode(entity io.Serializable, key []byte) error
@ -44,8 +44,8 @@ type DAO interface {
GetCurrentHeaderHeight() (i uint32, h util.Uint256, err error)
GetCurrentStateRootHeight() (uint32, error)
GetHeaderHashes() ([]util.Uint256, error)
GetNEP5Balances(acc util.Uint160) (*state.NEP5Balances, error)
GetNEP5TransferLog(acc util.Uint160, index uint32) (*state.NEP5TransferLog, error)
GetNEP17Balances(acc util.Uint160) (*state.NEP17Balances, error)
GetNEP17TransferLog(acc util.Uint160, index uint32) (*state.NEP17TransferLog, error)
GetAndUpdateNextContractID() (int32, error)
GetStateRoot(height uint32) (*state.MPTRootState, error)
PutStateRoot(root *state.MPTRootState) error
@ -60,15 +60,15 @@ type DAO interface {
PutAppExecResult(aer *state.AppExecResult, buf *io.BufBinWriter) error
PutContractState(cs *state.Contract) error
PutCurrentHeader(hashAndIndex []byte) error
PutNEP5Balances(acc util.Uint160, bs *state.NEP5Balances) error
PutNEP5TransferLog(acc util.Uint160, index uint32, lg *state.NEP5TransferLog) error
PutNEP17Balances(acc util.Uint160, bs *state.NEP17Balances) error
PutNEP17TransferLog(acc util.Uint160, index uint32, lg *state.NEP17TransferLog) error
PutStorageItem(id int32, key []byte, si *state.StorageItem) error
PutVersion(v string) error
Seek(id int32, prefix []byte, f func(k, v []byte))
StoreAsBlock(block *block.Block, buf *io.BufBinWriter) error
StoreAsCurrentBlock(block *block.Block, buf *io.BufBinWriter) error
StoreAsTransaction(tx *transaction.Transaction, index uint32, buf *io.BufBinWriter) error
putNEP5Balances(acc util.Uint160, bs *state.NEP5Balances, buf *io.BufBinWriter) error
putNEP17Balances(acc util.Uint160, bs *state.NEP17Balances, buf *io.BufBinWriter) error
}
// Simple is memCached wrapper around DB, simple DAO implementation.
@ -197,12 +197,12 @@ func (dao *Simple) GetContractScriptHash(id int32) (util.Uint160, error) {
// -- end contracts.
// -- start nep5 balances.
// -- start nep17 balances.
// GetNEP5Balances retrieves nep5 balances from the cache.
func (dao *Simple) GetNEP5Balances(acc util.Uint160) (*state.NEP5Balances, error) {
key := storage.AppendPrefix(storage.STNEP5Balances, acc.BytesBE())
bs := state.NewNEP5Balances()
// GetNEP17Balances retrieves nep17 balances from the cache.
func (dao *Simple) GetNEP17Balances(acc util.Uint160) (*state.NEP17Balances, error) {
key := storage.AppendPrefix(storage.STNEP17Balances, acc.BytesBE())
bs := state.NewNEP17Balances()
err := dao.GetAndDecode(bs, key)
if err != nil && err != storage.ErrKeyNotFound {
return nil, err
@ -210,61 +210,61 @@ func (dao *Simple) GetNEP5Balances(acc util.Uint160) (*state.NEP5Balances, error
return bs, nil
}
// PutNEP5Balances saves nep5 balances from the cache.
func (dao *Simple) PutNEP5Balances(acc util.Uint160, bs *state.NEP5Balances) error {
return dao.putNEP5Balances(acc, bs, io.NewBufBinWriter())
// PutNEP17Balances saves nep17 balances from the cache.
func (dao *Simple) PutNEP17Balances(acc util.Uint160, bs *state.NEP17Balances) error {
return dao.putNEP17Balances(acc, bs, io.NewBufBinWriter())
}
func (dao *Simple) putNEP5Balances(acc util.Uint160, bs *state.NEP5Balances, buf *io.BufBinWriter) error {
key := storage.AppendPrefix(storage.STNEP5Balances, acc.BytesBE())
func (dao *Simple) putNEP17Balances(acc util.Uint160, bs *state.NEP17Balances, buf *io.BufBinWriter) error {
key := storage.AppendPrefix(storage.STNEP17Balances, acc.BytesBE())
return dao.putWithBuffer(bs, key, buf)
}
// -- end nep5 balances.
// -- end nep17 balances.
// -- start transfer log.
func getNEP5TransferLogKey(acc util.Uint160, index uint32) []byte {
func getNEP17TransferLogKey(acc util.Uint160, index uint32) []byte {
key := make([]byte, 1+util.Uint160Size+4)
key[0] = byte(storage.STNEP5Transfers)
key[0] = byte(storage.STNEP17Transfers)
copy(key[1:], acc.BytesBE())
binary.LittleEndian.PutUint32(key[util.Uint160Size:], index)
return key
}
// GetNEP5TransferLog retrieves transfer log from the cache.
func (dao *Simple) GetNEP5TransferLog(acc util.Uint160, index uint32) (*state.NEP5TransferLog, error) {
key := getNEP5TransferLogKey(acc, index)
// GetNEP17TransferLog retrieves transfer log from the cache.
func (dao *Simple) GetNEP17TransferLog(acc util.Uint160, index uint32) (*state.NEP17TransferLog, error) {
key := getNEP17TransferLogKey(acc, index)
value, err := dao.Store.Get(key)
if err != nil {
if err == storage.ErrKeyNotFound {
return new(state.NEP5TransferLog), nil
return new(state.NEP17TransferLog), nil
}
return nil, err
}
return &state.NEP5TransferLog{Raw: value}, nil
return &state.NEP17TransferLog{Raw: value}, nil
}
// PutNEP5TransferLog saves given transfer log in the cache.
func (dao *Simple) PutNEP5TransferLog(acc util.Uint160, index uint32, lg *state.NEP5TransferLog) error {
key := getNEP5TransferLogKey(acc, index)
// PutNEP17TransferLog saves given transfer log in the cache.
func (dao *Simple) PutNEP17TransferLog(acc util.Uint160, index uint32, lg *state.NEP17TransferLog) error {
key := getNEP17TransferLogKey(acc, index)
return dao.Store.Put(key, lg.Raw)
}
// AppendNEP5Transfer appends a single NEP5 transfer to a log.
// AppendNEP17Transfer appends a single NEP17 transfer to a log.
// First return value signalizes that log size has exceeded batch size.
func (dao *Simple) AppendNEP5Transfer(acc util.Uint160, index uint32, tr *state.NEP5Transfer) (bool, error) {
lg, err := dao.GetNEP5TransferLog(acc, index)
func (dao *Simple) AppendNEP17Transfer(acc util.Uint160, index uint32, tr *state.NEP17Transfer) (bool, error) {
lg, err := dao.GetNEP17TransferLog(acc, index)
if err != nil {
if err != storage.ErrKeyNotFound {
return false, err
}
lg = new(state.NEP5TransferLog)
lg = new(state.NEP17TransferLog)
}
if err := lg.Append(tr); err != nil {
return false, err
}
return lg.Size() >= state.NEP5TransferBatchSize, dao.PutNEP5TransferLog(acc, index, lg)
return lg.Size() >= state.NEP17TransferBatchSize, dao.PutNEP17TransferLog(acc, index, lg)
}
// -- end transfer log.

View file

@ -201,7 +201,7 @@ func TestCreateBasicChain(t *testing.T) {
require.Equal(t, big.NewInt(5000_0000), bc.GetUtilityTokenBalance(priv0ScriptHash)) // gas bounty
// Move some NEO to one simple account.
txMoveNeo := newNEP5Transfer(neoHash, neoOwner, priv0ScriptHash, neoAmount)
txMoveNeo := newNEP17Transfer(neoHash, neoOwner, priv0ScriptHash, neoAmount)
txMoveNeo.ValidUntilBlock = validUntilBlock
txMoveNeo.Nonce = getNextNonce()
txMoveNeo.Signers = []transaction.Signer{{
@ -212,7 +212,7 @@ func TestCreateBasicChain(t *testing.T) {
}}
require.NoError(t, signTx(bc, txMoveNeo))
// Move some GAS to one simple account.
txMoveGas := newNEP5Transfer(gasHash, neoOwner, priv0ScriptHash, int64(util.Fixed8FromInt64(1000)))
txMoveGas := newNEP17Transfer(gasHash, neoOwner, priv0ScriptHash, int64(util.Fixed8FromInt64(1000)))
txMoveGas.ValidUntilBlock = validUntilBlock
txMoveGas.Nonce = getNextNonce()
txMoveGas.Signers = []transaction.Signer{{
@ -270,7 +270,7 @@ func TestCreateBasicChain(t *testing.T) {
t.Logf("txInv: %s", txInv.Hash().StringLE())
priv1 := testchain.PrivateKeyByID(1)
txNeo0to1 := newNEP5Transfer(neoHash, priv0ScriptHash, priv1.GetScriptHash(), 1000)
txNeo0to1 := newNEP17Transfer(neoHash, priv0ScriptHash, priv1.GetScriptHash(), 1000)
txNeo0to1.Nonce = getNextNonce()
txNeo0to1.ValidUntilBlock = validUntilBlock
txNeo0to1.Signers = []transaction.Signer{
@ -295,7 +295,7 @@ func TestCreateBasicChain(t *testing.T) {
initTx.Signers = []transaction.Signer{{Account: priv0ScriptHash}}
require.NoError(t, addNetworkFee(bc, initTx, acc0))
require.NoError(t, acc0.SignTx(initTx))
transferTx := newNEP5Transfer(sh, sh, priv0.GetScriptHash(), 1000)
transferTx := newNEP17Transfer(sh, sh, priv0.GetScriptHash(), 1000)
transferTx.Nonce = getNextNonce()
transferTx.ValidUntilBlock = validUntilBlock
transferTx.Signers = []transaction.Signer{
@ -313,7 +313,7 @@ func TestCreateBasicChain(t *testing.T) {
require.NoError(t, bc.AddBlock(b))
t.Logf("recieveRublesTx: %v", transferTx.Hash().StringLE())
transferTx = newNEP5Transfer(sh, priv0.GetScriptHash(), priv1.GetScriptHash(), 123)
transferTx = newNEP17Transfer(sh, priv0.GetScriptHash(), priv1.GetScriptHash(), 123)
transferTx.Nonce = getNextNonce()
transferTx.ValidUntilBlock = validUntilBlock
transferTx.Signers = []transaction.Signer{
@ -364,7 +364,7 @@ func TestCreateBasicChain(t *testing.T) {
}
// Prepare some transaction for future submission.
txSendRaw := newNEP5Transfer(neoHash, priv0ScriptHash, priv1.GetScriptHash(), int64(util.Fixed8FromInt64(1000)))
txSendRaw := newNEP17Transfer(neoHash, priv0ScriptHash, priv1.GetScriptHash(), int64(util.Fixed8FromInt64(1000)))
txSendRaw.ValidUntilBlock = validUntilBlock
txSendRaw.Nonce = getNextNonce()
txSendRaw.Signers = []transaction.Signer{{
@ -380,7 +380,7 @@ func TestCreateBasicChain(t *testing.T) {
t.Logf("sendrawtransaction: %s", hex.EncodeToString(bw.Bytes()))
}
func newNEP5Transfer(sc, from, to util.Uint160, amount int64) *transaction.Transaction {
func newNEP17Transfer(sc, from, to util.Uint160, amount int64) *transaction.Transaction {
w := io.NewBufBinWriter()
emit.AppCallWithOperationAndArgs(w.BinWriter, sc, "transfer", from, to, amount, nil)
emit.Opcodes(w.BinWriter, opcode.ASSERT)

View file

@ -45,7 +45,7 @@ func newGAS() *GAS {
}
func (g *GAS) increaseBalance(_ *interop.Context, _ util.Uint160, si *state.StorageItem, amount *big.Int) error {
acc, err := state.NEP5BalanceStateFromBytes(si.Value)
acc, err := state.NEP17BalanceStateFromBytes(si.Value)
if err != nil {
return err
}

View file

@ -238,7 +238,7 @@ func (c *nep17TokenNative) TransferInternal(ic *interop.Context, from, to util.U
func (c *nep17TokenNative) balanceOf(ic *interop.Context, args []stackitem.Item) stackitem.Item {
h := toUint160(args[0])
bs, err := ic.DAO.GetNEP5Balances(h)
bs, err := ic.DAO.GetNEP17Balances(h)
if err != nil {
panic(err)
}

View file

@ -313,7 +313,7 @@ func TestNEO_TransferOnPayment(t *testing.T) {
require.NoError(t, bc.dao.PutContractState(cs))
const amount = 2
tx := newNEP5Transfer(bc.contracts.NEO.Hash, neoOwner, cs.ScriptHash(), amount)
tx := newNEP17Transfer(bc.contracts.NEO.Hash, neoOwner, cs.ScriptHash(), amount)
tx.SystemFee += 1_000_000
tx.NetworkFee = 10_000_000
tx.ValidUntilBlock = bc.BlockHeight() + 1

View file

@ -9,21 +9,21 @@ import (
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
)
// NEP5BalanceState represents balance state of a NEP5-token.
type NEP5BalanceState struct {
// NEP17BalanceState represents balance state of a NEP17-token.
type NEP17BalanceState struct {
Balance big.Int
}
// NEOBalanceState represents balance state of a NEO-token.
type NEOBalanceState struct {
NEP5BalanceState
NEP17BalanceState
BalanceHeight uint32
VoteTo *keys.PublicKey
}
// NEP5BalanceStateFromBytes converts serialized NEP5BalanceState to structure.
func NEP5BalanceStateFromBytes(b []byte) (*NEP5BalanceState, error) {
balance := new(NEP5BalanceState)
// NEP17BalanceStateFromBytes converts serialized NEP17BalanceState to structure.
func NEP17BalanceStateFromBytes(b []byte) (*NEP17BalanceState, error) {
balance := new(NEP17BalanceState)
if len(b) == 0 {
return balance, nil
}
@ -35,8 +35,8 @@ func NEP5BalanceStateFromBytes(b []byte) (*NEP5BalanceState, error) {
return balance, nil
}
// Bytes returns serialized NEP5BalanceState.
func (s *NEP5BalanceState) Bytes() []byte {
// Bytes returns serialized NEP17BalanceState.
func (s *NEP17BalanceState) Bytes() []byte {
w := io.NewBufBinWriter()
s.EncodeBinary(w.BinWriter)
if w.Err != nil {
@ -45,22 +45,22 @@ func (s *NEP5BalanceState) Bytes() []byte {
return w.Bytes()
}
func (s *NEP5BalanceState) toStackItem() stackitem.Item {
func (s *NEP17BalanceState) toStackItem() stackitem.Item {
return stackitem.NewStruct([]stackitem.Item{stackitem.NewBigInteger(&s.Balance)})
}
func (s *NEP5BalanceState) fromStackItem(item stackitem.Item) {
func (s *NEP17BalanceState) fromStackItem(item stackitem.Item) {
s.Balance = *item.(*stackitem.Struct).Value().([]stackitem.Item)[0].Value().(*big.Int)
}
// EncodeBinary implements io.Serializable interface.
func (s *NEP5BalanceState) EncodeBinary(w *io.BinWriter) {
func (s *NEP17BalanceState) EncodeBinary(w *io.BinWriter) {
si := s.toStackItem()
stackitem.EncodeBinaryStackItem(si, w)
}
// DecodeBinary implements io.Serializable interface.
func (s *NEP5BalanceState) DecodeBinary(r *io.BinReader) {
func (s *NEP17BalanceState) DecodeBinary(r *io.BinReader) {
si := stackitem.DecodeBinaryStackItem(r)
if r.Err != nil {
return
@ -109,7 +109,7 @@ func (s *NEOBalanceState) DecodeBinary(r *io.BinReader) {
}
func (s *NEOBalanceState) toStackItem() stackitem.Item {
result := s.NEP5BalanceState.toStackItem().(*stackitem.Struct)
result := s.NEP17BalanceState.toStackItem().(*stackitem.Struct)
result.Append(stackitem.NewBigInteger(big.NewInt(int64(s.BalanceHeight))))
if s.VoteTo != nil {
result.Append(stackitem.NewByteArray(s.VoteTo.Bytes()))

View file

@ -8,11 +8,11 @@ import (
"github.com/nspcc-dev/neo-go/pkg/util"
)
// NEP5TransferBatchSize is the maximum number of entries for NEP5TransferLog.
const NEP5TransferBatchSize = 128
// NEP17TransferBatchSize is the maximum number of entries for NEP17TransferLog.
const NEP17TransferBatchSize = 128
// NEP5Tracker contains info about a single account in a NEP5 contract.
type NEP5Tracker struct {
// NEP17Tracker contains info about a single account in a NEP17 contract.
type NEP17Tracker struct {
// Balance is the current balance of the account.
Balance big.Int
// LastUpdatedBlock is a number of block when last `transfer` to or from the
@ -20,14 +20,14 @@ type NEP5Tracker struct {
LastUpdatedBlock uint32
}
// NEP5TransferLog is a log of NEP5 token transfers for the specific command.
type NEP5TransferLog struct {
// NEP17TransferLog is a log of NEP17 token transfers for the specific command.
type NEP17TransferLog struct {
Raw []byte
}
// NEP5Transfer represents a single NEP5 Transfer event.
type NEP5Transfer struct {
// Asset is a NEP5 contract ID.
// NEP17Transfer represents a single NEP17 Transfer event.
type NEP17Transfer struct {
// Asset is a NEP17 contract ID.
Asset int32
// Address is the address of the sender.
From util.Uint160
@ -44,29 +44,29 @@ type NEP5Transfer struct {
Tx util.Uint256
}
// NEP5Balances is a map of the NEP5 contract IDs
// NEP17Balances is a map of the NEP17 contract IDs
// to the corresponding structures.
type NEP5Balances struct {
Trackers map[int32]NEP5Tracker
type NEP17Balances struct {
Trackers map[int32]NEP17Tracker
// NextTransferBatch stores an index of the next transfer batch.
NextTransferBatch uint32
}
// NewNEP5Balances returns new NEP5Balances.
func NewNEP5Balances() *NEP5Balances {
return &NEP5Balances{
Trackers: make(map[int32]NEP5Tracker),
// NewNEP17Balances returns new NEP17Balances.
func NewNEP17Balances() *NEP17Balances {
return &NEP17Balances{
Trackers: make(map[int32]NEP17Tracker),
}
}
// DecodeBinary implements io.Serializable interface.
func (bs *NEP5Balances) DecodeBinary(r *io.BinReader) {
func (bs *NEP17Balances) DecodeBinary(r *io.BinReader) {
bs.NextTransferBatch = r.ReadU32LE()
lenBalances := r.ReadVarUint()
m := make(map[int32]NEP5Tracker, lenBalances)
m := make(map[int32]NEP17Tracker, lenBalances)
for i := 0; i < int(lenBalances); i++ {
key := int32(r.ReadU32LE())
var tr NEP5Tracker
var tr NEP17Tracker
tr.DecodeBinary(r)
m[key] = tr
}
@ -74,7 +74,7 @@ func (bs *NEP5Balances) DecodeBinary(r *io.BinReader) {
}
// EncodeBinary implements io.Serializable interface.
func (bs *NEP5Balances) EncodeBinary(w *io.BinWriter) {
func (bs *NEP17Balances) EncodeBinary(w *io.BinWriter) {
w.WriteU32LE(bs.NextTransferBatch)
w.WriteVarUint(uint64(len(bs.Trackers)))
for k, v := range bs.Trackers {
@ -84,7 +84,7 @@ func (bs *NEP5Balances) EncodeBinary(w *io.BinWriter) {
}
// Append appends single transfer to a log.
func (lg *NEP5TransferLog) Append(tr *NEP5Transfer) error {
func (lg *NEP17TransferLog) Append(tr *NEP17Transfer) error {
w := io.NewBufBinWriter()
// The first entry, set up counter.
if len(lg.Raw) == 0 {
@ -102,11 +102,11 @@ func (lg *NEP5TransferLog) Append(tr *NEP5Transfer) error {
}
// ForEach iterates over transfer log returning on first error.
func (lg *NEP5TransferLog) ForEach(f func(*NEP5Transfer) (bool, error)) (bool, error) {
func (lg *NEP17TransferLog) ForEach(f func(*NEP17Transfer) (bool, error)) (bool, error) {
if lg == nil || len(lg.Raw) == 0 {
return true, nil
}
transfers := make([]NEP5Transfer, lg.Size())
transfers := make([]NEP17Transfer, lg.Size())
r := io.NewBinReaderFromBuf(lg.Raw[1:])
for i := 0; i < lg.Size(); i++ {
transfers[i].DecodeBinary(r)
@ -127,7 +127,7 @@ func (lg *NEP5TransferLog) ForEach(f func(*NEP5Transfer) (bool, error)) (bool, e
}
// Size returns an amount of transfer written in log.
func (lg *NEP5TransferLog) Size() int {
func (lg *NEP17TransferLog) Size() int {
if len(lg.Raw) == 0 {
return 0
}
@ -135,19 +135,19 @@ func (lg *NEP5TransferLog) Size() int {
}
// EncodeBinary implements io.Serializable interface.
func (t *NEP5Tracker) EncodeBinary(w *io.BinWriter) {
func (t *NEP17Tracker) EncodeBinary(w *io.BinWriter) {
w.WriteVarBytes(bigint.ToBytes(&t.Balance))
w.WriteU32LE(t.LastUpdatedBlock)
}
// DecodeBinary implements io.Serializable interface.
func (t *NEP5Tracker) DecodeBinary(r *io.BinReader) {
func (t *NEP17Tracker) DecodeBinary(r *io.BinReader) {
t.Balance = *bigint.FromBytes(r.ReadVarBytes())
t.LastUpdatedBlock = r.ReadU32LE()
}
// EncodeBinary implements io.Serializable interface.
func (t *NEP5Transfer) EncodeBinary(w *io.BinWriter) {
func (t *NEP17Transfer) EncodeBinary(w *io.BinWriter) {
w.WriteU32LE(uint32(t.Asset))
w.WriteBytes(t.Tx[:])
w.WriteBytes(t.From[:])
@ -159,7 +159,7 @@ func (t *NEP5Transfer) EncodeBinary(w *io.BinWriter) {
}
// DecodeBinary implements io.Serializable interface.
func (t *NEP5Transfer) DecodeBinary(r *io.BinReader) {
func (t *NEP17Transfer) DecodeBinary(r *io.BinReader) {
t.Asset = int32(r.ReadU32LE())
r.ReadBytes(t.Tx[:])
r.ReadBytes(t.From[:])

View file

@ -12,16 +12,16 @@ import (
"github.com/stretchr/testify/require"
)
func TestNEP5TransferLog_Append(t *testing.T) {
func TestNEP17TransferLog_Append(t *testing.T) {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
expected := []*NEP5Transfer{
expected := []*NEP17Transfer{
randomTransfer(r),
randomTransfer(r),
randomTransfer(r),
randomTransfer(r),
}
lg := new(NEP5TransferLog)
lg := new(NEP17TransferLog)
for _, tr := range expected {
require.NoError(t, lg.Append(tr))
}
@ -29,7 +29,7 @@ func TestNEP5TransferLog_Append(t *testing.T) {
require.Equal(t, len(expected), lg.Size())
i := len(expected) - 1
cont, err := lg.ForEach(func(tr *NEP5Transfer) (bool, error) {
cont, err := lg.ForEach(func(tr *NEP17Transfer) (bool, error) {
require.Equal(t, expected[i], tr)
i--
return true, nil
@ -38,17 +38,17 @@ func TestNEP5TransferLog_Append(t *testing.T) {
require.True(t, cont)
}
func TestNEP5Tracker_EncodeBinary(t *testing.T) {
expected := &NEP5Tracker{
func TestNEP17Tracker_EncodeBinary(t *testing.T) {
expected := &NEP17Tracker{
Balance: *big.NewInt(int64(rand.Uint64())),
LastUpdatedBlock: rand.Uint32(),
}
testserdes.EncodeDecodeBinary(t, expected, new(NEP5Tracker))
testserdes.EncodeDecodeBinary(t, expected, new(NEP17Tracker))
}
func TestNEP5Transfer_DecodeBinary(t *testing.T) {
expected := &NEP5Transfer{
func TestNEP17Transfer_DecodeBinary(t *testing.T) {
expected := &NEP17Transfer{
Asset: 123,
From: util.Uint160{5, 6, 7},
To: util.Uint160{8, 9, 10},
@ -58,11 +58,11 @@ func TestNEP5Transfer_DecodeBinary(t *testing.T) {
Tx: util.Uint256{8, 5, 3},
}
testserdes.EncodeDecodeBinary(t, expected, new(NEP5Transfer))
testserdes.EncodeDecodeBinary(t, expected, new(NEP17Transfer))
}
func randomTransfer(r *rand.Rand) *NEP5Transfer {
return &NEP5Transfer{
func randomTransfer(r *rand.Rand) *NEP17Transfer {
return &NEP17Transfer{
Amount: *big.NewInt(int64(r.Uint64())),
Block: r.Uint32(),
Asset: int32(random.Int(10, 10000000)),

View file

@ -16,8 +16,8 @@ const (
STContract KeyPrefix = 0x50
STContractID KeyPrefix = 0x51
STStorage KeyPrefix = 0x70
STNEP5Transfers KeyPrefix = 0x72
STNEP5Balances KeyPrefix = 0x73
STNEP17Transfers KeyPrefix = 0x72
STNEP17Balances KeyPrefix = 0x73
IXHeaderHashList KeyPrefix = 0x80
SYSCurrentBlock KeyPrefix = 0xc0
SYSCurrentHeader KeyPrefix = 0xc1

View file

@ -103,10 +103,10 @@ func (chain testChain) GetHeader(hash util.Uint256) (*block.Header, error) {
func (chain testChain) GetNextBlockValidators() ([]*keys.PublicKey, error) {
panic("TODO")
}
func (chain testChain) ForEachNEP5Transfer(util.Uint160, func(*state.NEP5Transfer) (bool, error)) error {
func (chain testChain) ForEachNEP17Transfer(util.Uint160, func(*state.NEP17Transfer) (bool, error)) error {
panic("TODO")
}
func (chain testChain) GetNEP5Balances(util.Uint160) *state.NEP5Balances {
func (chain testChain) GetNEP17Balances(util.Uint160) *state.NEP17Balances {
panic("TODO")
}
func (chain testChain) GetValidators() ([]*keys.PublicKey, error) {

View file

@ -27,8 +27,8 @@ Supported methods
getblocksysfee
getconnectioncount
getcontractstate
getnep5balances
getnep5transfers
getnep17balances
getnep17transfers
getpeers
getrawmempool
getrawtransaction

View file

@ -29,7 +29,7 @@ func Example() {
fmt.Println(err)
os.Exit(1)
}
resp, err := c.GetNEP5Balances(addr)
resp, err := c.GetNEP17Balances(addr)
if err != nil {
fmt.Println(err)
os.Exit(1)

View file

@ -23,50 +23,50 @@ type TransferTarget struct {
Amount int64
}
// NEP5Decimals invokes `decimals` NEP5 method on a specified contract.
func (c *Client) NEP5Decimals(tokenHash util.Uint160) (int64, error) {
// NEP17Decimals invokes `decimals` NEP17 method on a specified contract.
func (c *Client) NEP17Decimals(tokenHash util.Uint160) (int64, error) {
result, err := c.InvokeFunction(tokenHash, "decimals", []smartcontract.Parameter{}, nil)
if err != nil {
return 0, err
}
err = getInvocationError(result)
if err != nil {
return 0, fmt.Errorf("failed to get NEP5 decimals: %w", err)
return 0, fmt.Errorf("failed to get NEP17 decimals: %w", err)
}
return topIntFromStack(result.Stack)
}
// NEP5Symbol invokes `symbol` NEP5 method on a specified contract.
func (c *Client) NEP5Symbol(tokenHash util.Uint160) (string, error) {
// NEP17Symbol invokes `symbol` NEP17 method on a specified contract.
func (c *Client) NEP17Symbol(tokenHash util.Uint160) (string, error) {
result, err := c.InvokeFunction(tokenHash, "symbol", []smartcontract.Parameter{}, nil)
if err != nil {
return "", err
}
err = getInvocationError(result)
if err != nil {
return "", fmt.Errorf("failed to get NEP5 symbol: %w", err)
return "", fmt.Errorf("failed to get NEP17 symbol: %w", err)
}
return topStringFromStack(result.Stack)
}
// NEP5TotalSupply invokes `totalSupply` NEP5 method on a specified contract.
func (c *Client) NEP5TotalSupply(tokenHash util.Uint160) (int64, error) {
// NEP17TotalSupply invokes `totalSupply` NEP17 method on a specified contract.
func (c *Client) NEP17TotalSupply(tokenHash util.Uint160) (int64, error) {
result, err := c.InvokeFunction(tokenHash, "totalSupply", []smartcontract.Parameter{}, nil)
if err != nil {
return 0, err
}
err = getInvocationError(result)
if err != nil {
return 0, fmt.Errorf("failed to get NEP5 total supply: %w", err)
return 0, fmt.Errorf("failed to get NEP17 total supply: %w", err)
}
return topIntFromStack(result.Stack)
}
// NEP5BalanceOf invokes `balanceOf` NEP5 method on a specified contract.
func (c *Client) NEP5BalanceOf(tokenHash, acc util.Uint160) (int64, error) {
// NEP17BalanceOf invokes `balanceOf` NEP17 method on a specified contract.
func (c *Client) NEP17BalanceOf(tokenHash, acc util.Uint160) (int64, error) {
result, err := c.InvokeFunction(tokenHash, "balanceOf", []smartcontract.Parameter{{
Type: smartcontract.Hash160Type,
Value: acc,
@ -76,44 +76,44 @@ func (c *Client) NEP5BalanceOf(tokenHash, acc util.Uint160) (int64, error) {
}
err = getInvocationError(result)
if err != nil {
return 0, fmt.Errorf("failed to get NEP5 balance: %w", err)
return 0, fmt.Errorf("failed to get NEP17 balance: %w", err)
}
return topIntFromStack(result.Stack)
}
// NEP5TokenInfo returns full NEP5 token info.
func (c *Client) NEP5TokenInfo(tokenHash util.Uint160) (*wallet.Token, error) {
// NEP17TokenInfo returns full NEP17 token info.
func (c *Client) NEP17TokenInfo(tokenHash util.Uint160) (*wallet.Token, error) {
cs, err := c.GetContractStateByHash(tokenHash)
if err != nil {
return nil, err
}
symbol, err := c.NEP5Symbol(tokenHash)
symbol, err := c.NEP17Symbol(tokenHash)
if err != nil {
return nil, err
}
decimals, err := c.NEP5Decimals(tokenHash)
decimals, err := c.NEP17Decimals(tokenHash)
if err != nil {
return nil, err
}
return wallet.NewToken(tokenHash, cs.Manifest.Name, symbol, decimals), nil
}
// CreateNEP5TransferTx creates an invocation transaction for the 'transfer'
// method of a given contract (token) to move specified amount of NEP5 assets
// CreateNEP17TransferTx creates an invocation transaction for the 'transfer'
// method of a given contract (token) to move specified amount of NEP17 assets
// (in FixedN format using contract's number of decimals) to given account and
// returns it. The returned transaction is not signed.
func (c *Client) CreateNEP5TransferTx(acc *wallet.Account, to util.Uint160, token util.Uint160, amount int64, gas int64) (*transaction.Transaction, error) {
return c.CreateNEP5MultiTransferTx(acc, gas, TransferTarget{
func (c *Client) CreateNEP17TransferTx(acc *wallet.Account, to util.Uint160, token util.Uint160, amount int64, gas int64) (*transaction.Transaction, error) {
return c.CreateNEP17MultiTransferTx(acc, gas, TransferTarget{
Token: token,
Address: to,
Amount: amount,
})
}
// CreateNEP5MultiTransferTx creates an invocation transaction for performing NEP5 transfers
// CreateNEP17MultiTransferTx creates an invocation transaction for performing NEP17 transfers
// from a single sender to multiple recipients.
func (c *Client) CreateNEP5MultiTransferTx(acc *wallet.Account, gas int64, recipients ...TransferTarget) (*transaction.Transaction, error) {
func (c *Client) CreateNEP17MultiTransferTx(acc *wallet.Account, gas int64, recipients ...TransferTarget) (*transaction.Transaction, error) {
from, err := address.StringToUint160(acc.Address)
if err != nil {
return nil, fmt.Errorf("bad account address: %w", err)
@ -171,12 +171,12 @@ func (c *Client) CreateTxFromScript(script []byte, acc *wallet.Account, sysFee,
return tx, nil
}
// TransferNEP5 creates an invocation transaction that invokes 'transfer' method
// on a given token to move specified amount of NEP5 assets (in FixedN format
// TransferNEP17 creates an invocation transaction that invokes 'transfer' method
// on a given token to move specified amount of NEP17 assets (in FixedN format
// using contract's number of decimals) to given account and sends it to the
// network returning just a hash of it.
func (c *Client) TransferNEP5(acc *wallet.Account, to util.Uint160, token util.Uint160, amount int64, gas int64) (util.Uint256, error) {
tx, err := c.CreateNEP5TransferTx(acc, to, token, amount, gas)
func (c *Client) TransferNEP17(acc *wallet.Account, to util.Uint160, token util.Uint160, amount int64, gas int64) (util.Uint256, error) {
tx, err := c.CreateNEP17TransferTx(acc, to, token, amount, gas)
if err != nil {
return util.Uint256{}, err
}
@ -188,9 +188,9 @@ func (c *Client) TransferNEP5(acc *wallet.Account, to util.Uint160, token util.U
return c.SendRawTransaction(tx)
}
// MultiTransferNEP5 is similar to TransferNEP5, buf allows to have multiple recipients.
func (c *Client) MultiTransferNEP5(acc *wallet.Account, gas int64, recipients ...TransferTarget) (util.Uint256, error) {
tx, err := c.CreateNEP5MultiTransferTx(acc, gas, recipients...)
// MultiTransferNEP17 is similar to TransferNEP17, buf allows to have multiple recipients.
func (c *Client) MultiTransferNEP17(acc *wallet.Account, gas int64, recipients ...TransferTarget) (util.Uint256, error) {
tx, err := c.CreateNEP17MultiTransferTx(acc, gas, recipients...)
if err != nil {
return util.Uint256{}, err
}

View file

@ -232,22 +232,22 @@ func (c *Client) getContractState(param interface{}) (*state.Contract, error) {
return resp, nil
}
// GetNEP5Balances is a wrapper for getnep5balances RPC.
func (c *Client) GetNEP5Balances(address util.Uint160) (*result.NEP5Balances, error) {
// GetNEP17Balances is a wrapper for getnep17balances RPC.
func (c *Client) GetNEP17Balances(address util.Uint160) (*result.NEP17Balances, error) {
params := request.NewRawParams(address.StringLE())
resp := new(result.NEP5Balances)
if err := c.performRequest("getnep5balances", params, resp); err != nil {
resp := new(result.NEP17Balances)
if err := c.performRequest("getnep17balances", params, resp); err != nil {
return nil, err
}
return resp, nil
}
// GetNEP5Transfers is a wrapper for getnep5transfers RPC. Address parameter
// GetNEP17Transfers is a wrapper for getnep17transfers RPC. Address parameter
// is mandatory, while all the others are optional. Start and stop parameters
// are supported since neo-go 0.77.0 and limit and page since neo-go 0.78.0.
// These parameters are positional in the JSON-RPC call, you can't specify limit
// and not specify start/stop for example.
func (c *Client) GetNEP5Transfers(address string, start, stop *uint32, limit, page *int) (*result.NEP5Transfers, error) {
func (c *Client) GetNEP17Transfers(address string, start, stop *uint32, limit, page *int) (*result.NEP17Transfers, error) {
params := request.NewRawParams(address)
if start != nil {
params.Values = append(params.Values, *start)
@ -267,8 +267,8 @@ func (c *Client) GetNEP5Transfers(address string, start, stop *uint32, limit, pa
} else if stop != nil || limit != nil || page != nil {
return nil, errors.New("bad parameters")
}
resp := new(result.NEP5Transfers)
if err := c.performRequest("getnep5transfers", params, resp); err != nil {
resp := new(result.NEP17Transfers)
if err := c.performRequest("getnep17transfers", params, resp); err != nil {
return nil, err
}
return resp, nil

View file

@ -434,7 +434,7 @@ var rpcClientTestCases = map[string][]rpcClientTestCase{
},
},
},
"getnep5balances": {
"getnep17balances": {
{
name: "positive",
invoke: func(c *Client) (interface{}, error) {
@ -442,7 +442,7 @@ var rpcClientTestCases = map[string][]rpcClientTestCase{
if err != nil {
panic(err)
}
return c.GetNEP5Balances(hash)
return c.GetNEP17Balances(hash)
},
serverResponse: `{"jsonrpc":"2.0","id":1,"result":{"balance":[{"assethash":"a48b6e1291ba24211ad11bb90ae2a10bf1fcd5a8","amount":"50000000000","lastupdatedblock":251604}],"address":"AY6eqWjsUFCzsVELG7yG72XDukKvC34p2w"}}`,
result: func(c *Client) interface{} {
@ -450,8 +450,8 @@ var rpcClientTestCases = map[string][]rpcClientTestCase{
if err != nil {
panic(err)
}
return &result.NEP5Balances{
Balances: []result.NEP5Balance{{
return &result.NEP17Balances{
Balances: []result.NEP17Balance{{
Asset: hash,
Amount: "50000000000",
LastUpdated: 251604,
@ -461,11 +461,11 @@ var rpcClientTestCases = map[string][]rpcClientTestCase{
},
},
},
"getnep5transfers": {
"getnep17transfers": {
{
name: "positive",
invoke: func(c *Client) (interface{}, error) {
return c.GetNEP5Transfers("AbHgdBaWEnHkCiLtDZXjhvhaAK2cwFh5pF", nil, nil, nil, nil)
return c.GetNEP17Transfers("AbHgdBaWEnHkCiLtDZXjhvhaAK2cwFh5pF", nil, nil, nil, nil)
},
serverResponse: `{"jsonrpc":"2.0","id":1,"result":{"sent":[],"received":[{"timestamp":1555651816,"assethash":"600c4f5200db36177e3e8a09e9f18e2fc7d12a0f","transferaddress":"AYwgBNMepiv5ocGcyNT4mA8zPLTQ8pDBis","amount":"1000000","blockindex":436036,"transfernotifyindex":0,"txhash":"df7683ece554ecfb85cf41492c5f143215dd43ef9ec61181a28f922da06aba58"}],"address":"AbHgdBaWEnHkCiLtDZXjhvhaAK2cwFh5pF"}}`,
result: func(c *Client) interface{} {
@ -477,9 +477,9 @@ var rpcClientTestCases = map[string][]rpcClientTestCase{
if err != nil {
panic(err)
}
return &result.NEP5Transfers{
Sent: []result.NEP5Transfer{},
Received: []result.NEP5Transfer{
return &result.NEP17Transfers{
Sent: []result.NEP17Transfer{},
Received: []result.NEP17Transfer{
{
Timestamp: 1555651816,
Asset: assetHash,
@ -1040,38 +1040,38 @@ var rpcClientErrorCases = map[string][]rpcClientErrorCase{
},
},
{
name: "getnep5balances_invalid_params_error",
name: "getnep17balances_invalid_params_error",
invoke: func(c *Client) (interface{}, error) {
return c.GetNEP5Balances(util.Uint160{})
return c.GetNEP17Balances(util.Uint160{})
},
},
{
name: "getnep5transfers_invalid_params_error",
name: "getnep17transfers_invalid_params_error",
invoke: func(c *Client) (interface{}, error) {
return c.GetNEP5Transfers("", nil, nil, nil, nil)
return c.GetNEP17Transfers("", nil, nil, nil, nil)
},
},
{
name: "getnep5transfers_invalid_params_error 2",
name: "getnep17transfers_invalid_params_error 2",
invoke: func(c *Client) (interface{}, error) {
var stop uint32
return c.GetNEP5Transfers("NbTiM6h8r99kpRtb428XcsUk1TzKed2gTc", nil, &stop, nil, nil)
return c.GetNEP17Transfers("NbTiM6h8r99kpRtb428XcsUk1TzKed2gTc", nil, &stop, nil, nil)
},
},
{
name: "getnep5transfers_invalid_params_error 3",
name: "getnep17transfers_invalid_params_error 3",
invoke: func(c *Client) (interface{}, error) {
var start uint32
var limit int
return c.GetNEP5Transfers("NbTiM6h8r99kpRtb428XcsUk1TzKed2gTc", &start, nil, &limit, nil)
return c.GetNEP17Transfers("NbTiM6h8r99kpRtb428XcsUk1TzKed2gTc", &start, nil, &limit, nil)
},
},
{
name: "getnep5transfers_invalid_params_error 4",
name: "getnep17transfers_invalid_params_error 4",
invoke: func(c *Client) (interface{}, error) {
var start, stop uint32
var page int
return c.GetNEP5Transfers("NbTiM6h8r99kpRtb428XcsUk1TzKed2gTc", &start, &stop, nil, &page)
return c.GetNEP17Transfers("NbTiM6h8r99kpRtb428XcsUk1TzKed2gTc", &start, &stop, nil, &page)
},
},
{
@ -1227,15 +1227,15 @@ var rpcClientErrorCases = map[string][]rpcClientErrorCase{
},
},
{
name: "getnep5balances_unmarshalling_error",
name: "getnep17balances_unmarshalling_error",
invoke: func(c *Client) (interface{}, error) {
return c.GetNEP5Balances(util.Uint160{})
return c.GetNEP17Balances(util.Uint160{})
},
},
{
name: "getnep5transfers_unmarshalling_error",
name: "getnep17transfers_unmarshalling_error",
invoke: func(c *Client) (interface{}, error) {
return c.GetNEP5Transfers("", nil, nil, nil, nil)
return c.GetNEP17Transfers("", nil, nil, nil, nil)
},
},
{

View file

@ -4,28 +4,28 @@ import (
"github.com/nspcc-dev/neo-go/pkg/util"
)
// NEP5Balances is a result for the getnep5balances RPC call.
type NEP5Balances struct {
Balances []NEP5Balance `json:"balance"`
Address string `json:"address"`
// NEP17Balances is a result for the getnep17balances RPC call.
type NEP17Balances struct {
Balances []NEP17Balance `json:"balance"`
Address string `json:"address"`
}
// NEP5Balance represents balance for the single token contract.
type NEP5Balance struct {
// NEP17Balance represents balance for the single token contract.
type NEP17Balance struct {
Asset util.Uint160 `json:"assethash"`
Amount string `json:"amount"`
LastUpdated uint32 `json:"lastupdatedblock"`
}
// NEP5Transfers is a result for the getnep5transfers RPC.
type NEP5Transfers struct {
Sent []NEP5Transfer `json:"sent"`
Received []NEP5Transfer `json:"received"`
Address string `json:"address"`
// NEP17Transfers is a result for the getnep17transfers RPC.
type NEP17Transfers struct {
Sent []NEP17Transfer `json:"sent"`
Received []NEP17Transfer `json:"received"`
Address string `json:"address"`
}
// NEP5Transfer represents single NEP5 transfer event.
type NEP5Transfer struct {
// NEP17Transfer represents single NEP17 transfer event.
type NEP17Transfer struct {
Timestamp uint64 `json:"timestamp"`
Asset util.Uint160 `json:"assethash"`
Address string `json:"transferaddress,omitempty"`

View file

@ -19,7 +19,7 @@ import (
"github.com/stretchr/testify/require"
)
func TestClient_NEP5(t *testing.T) {
func TestClient_NEP17(t *testing.T) {
chain, rpcSrv, httpSrv := initServerWithInMemoryChain(t)
defer chain.Close()
defer rpcSrv.Shutdown()
@ -32,22 +32,22 @@ func TestClient_NEP5(t *testing.T) {
require.NoError(t, err)
t.Run("Decimals", func(t *testing.T) {
d, err := c.NEP5Decimals(h)
d, err := c.NEP17Decimals(h)
require.NoError(t, err)
require.EqualValues(t, 2, d)
})
t.Run("TotalSupply", func(t *testing.T) {
s, err := c.NEP5TotalSupply(h)
s, err := c.NEP17TotalSupply(h)
require.NoError(t, err)
require.EqualValues(t, 1_000_000, s)
})
t.Run("Symbol", func(t *testing.T) {
sym, err := c.NEP5Symbol(h)
sym, err := c.NEP17Symbol(h)
require.NoError(t, err)
require.Equal(t, "RUB", sym)
})
t.Run("TokenInfo", func(t *testing.T) {
tok, err := c.NEP5TokenInfo(h)
tok, err := c.NEP17TokenInfo(h)
require.NoError(t, err)
require.Equal(t, h, tok.Hash)
require.Equal(t, "Rubl", tok.Name)
@ -56,7 +56,7 @@ func TestClient_NEP5(t *testing.T) {
})
t.Run("BalanceOf", func(t *testing.T) {
acc := testchain.PrivateKeyByID(0).GetScriptHash()
b, err := c.NEP5BalanceOf(h, acc)
b, err := c.NEP17BalanceOf(h, acc)
require.NoError(t, err)
require.EqualValues(t, 877, b)
})
@ -259,7 +259,7 @@ func TestCreateTxFromScript(t *testing.T) {
})
}
func TestCreateNEP5TransferTx(t *testing.T) {
func TestCreateNEP17TransferTx(t *testing.T) {
chain, rpcSrv, httpSrv := initServerWithInMemoryChain(t)
defer chain.Close()
defer rpcSrv.Shutdown()
@ -275,7 +275,7 @@ func TestCreateNEP5TransferTx(t *testing.T) {
gasContractHash, err := c.GetNativeContractHash("gas")
require.NoError(t, err)
tx, err := c.CreateNEP5TransferTx(acc, util.Uint160{}, gasContractHash, 1000, 0)
tx, err := c.CreateNEP17TransferTx(acc, util.Uint160{}, gasContractHash, 1000, 0)
require.NoError(t, err)
require.NoError(t, acc.SignTx(tx))
require.NoError(t, chain.VerifyTx(tx))

View file

@ -97,8 +97,8 @@ var rpcHandlers = map[string]func(*Server, request.Params) (interface{}, *respon
"getcommittee": (*Server).getCommittee,
"getconnectioncount": (*Server).getConnectionCount,
"getcontractstate": (*Server).getContractState,
"getnep5balances": (*Server).getNEP5Balances,
"getnep5transfers": (*Server).getNEP5Transfers,
"getnep17balances": (*Server).getNEP17Balances,
"getnep17transfers": (*Server).getNEP17Transfers,
"getpeers": (*Server).getPeers,
"getproof": (*Server).getProof,
"getrawmempool": (*Server).getRawMempool,
@ -550,16 +550,16 @@ func (s *Server) getApplicationLog(reqParams request.Params) (interface{}, *resp
return result.NewApplicationLog(hash, appExecResults, trig), nil
}
func (s *Server) getNEP5Balances(ps request.Params) (interface{}, *response.Error) {
func (s *Server) getNEP17Balances(ps request.Params) (interface{}, *response.Error) {
u, err := ps.Value(0).GetUint160FromAddressOrHex()
if err != nil {
return nil, response.ErrInvalidParams
}
as := s.chain.GetNEP5Balances(u)
bs := &result.NEP5Balances{
as := s.chain.GetNEP17Balances(u)
bs := &result.NEP17Balances{
Address: address.Uint160ToString(u),
Balances: []result.NEP5Balance{},
Balances: []result.NEP17Balance{},
}
if as != nil {
cache := make(map[int32]util.Uint160)
@ -568,7 +568,7 @@ func (s *Server) getNEP5Balances(ps request.Params) (interface{}, *response.Erro
if err != nil {
continue
}
bs.Balances = append(bs.Balances, result.NEP5Balance{
bs.Balances = append(bs.Balances, result.NEP17Balance{
Asset: h,
Amount: bal.Balance.String(),
LastUpdated: bal.LastUpdatedBlock,
@ -628,7 +628,7 @@ func getTimestampsAndLimit(ps request.Params, index int) (uint64, uint64, int, i
return start, end, limit, page, nil
}
func (s *Server) getNEP5Transfers(ps request.Params) (interface{}, *response.Error) {
func (s *Server) getNEP17Transfers(ps request.Params) (interface{}, *response.Error) {
u, err := ps.Value(0).GetUint160FromAddressOrHex()
if err != nil {
return nil, response.ErrInvalidParams
@ -639,14 +639,14 @@ func (s *Server) getNEP5Transfers(ps request.Params) (interface{}, *response.Err
return nil, response.NewInvalidParamsError(err.Error(), err)
}
bs := &result.NEP5Transfers{
bs := &result.NEP17Transfers{
Address: address.Uint160ToString(u),
Received: []result.NEP5Transfer{},
Sent: []result.NEP5Transfer{},
Received: []result.NEP17Transfer{},
Sent: []result.NEP17Transfer{},
}
cache := make(map[int32]util.Uint160)
var resCount, frameCount int
err = s.chain.ForEachNEP5Transfer(u, func(tr *state.NEP5Transfer) (bool, error) {
err = s.chain.ForEachNEP17Transfer(u, func(tr *state.NEP17Transfer) (bool, error) {
// Iterating from newest to oldest, not yet reached required
// time frame, continue looping.
if tr.Timestamp > end {
@ -668,7 +668,7 @@ func (s *Server) getNEP5Transfers(ps request.Params) (interface{}, *response.Err
return false, err
}
transfer := result.NEP5Transfer{
transfer := result.NEP17Transfer{
Timestamp: tr.Timestamp,
Asset: h,
Index: tr.Block,
@ -696,7 +696,7 @@ func (s *Server) getNEP5Transfers(ps request.Params) (interface{}, *response.Err
return true, nil
})
if err != nil {
return nil, response.NewInternalServerError("invalid NEP5 transfer log", err)
return nil, response.NewInternalServerError("invalid NEP17 transfer log", err)
}
return bs, nil
}

View file

@ -202,7 +202,7 @@ var rpcTestCases = map[string][]rpcTestCase{
},
},
"getnep5balances": {
"getnep17balances": {
{
name: "no params",
params: `[]`,
@ -216,17 +216,17 @@ var rpcTestCases = map[string][]rpcTestCase{
{
name: "positive",
params: `["` + testchain.PrivateKeyByID(0).GetScriptHash().StringLE() + `"]`,
result: func(e *executor) interface{} { return &result.NEP5Balances{} },
check: checkNep5Balances,
result: func(e *executor) interface{} { return &result.NEP17Balances{} },
check: checkNep17Balances,
},
{
name: "positive_address",
params: `["` + address.Uint160ToString(testchain.PrivateKeyByID(0).GetScriptHash()) + `"]`,
result: func(e *executor) interface{} { return &result.NEP5Balances{} },
check: checkNep5Balances,
result: func(e *executor) interface{} { return &result.NEP17Balances{} },
check: checkNep17Balances,
},
},
"getnep5transfers": {
"getnep17transfers": {
{
name: "no params",
params: `[]`,
@ -275,14 +275,14 @@ var rpcTestCases = map[string][]rpcTestCase{
{
name: "positive",
params: `["` + testchain.PrivateKeyByID(0).Address() + `", 0]`,
result: func(e *executor) interface{} { return &result.NEP5Transfers{} },
check: checkNep5Transfers,
result: func(e *executor) interface{} { return &result.NEP17Transfers{} },
check: checkNep17Transfers,
},
{
name: "positive_hash",
params: `["` + testchain.PrivateKeyByID(0).GetScriptHash().StringLE() + `", 0]`,
result: func(e *executor) interface{} { return &result.NEP5Transfers{} },
check: checkNep5Transfers,
result: func(e *executor) interface{} { return &result.NEP17Transfers{} },
check: checkNep17Transfers,
},
},
"getproof": {
@ -1198,8 +1198,8 @@ func testRPCProtocol(t *testing.T, doRPCCall func(string, string, *testing.T) []
assert.ElementsMatch(t, expected, actual)
})
t.Run("getnep5transfers", func(t *testing.T) {
testNEP5T := func(t *testing.T, start, stop, limit, page int, sent, rcvd []int) {
t.Run("getnep17transfers", func(t *testing.T) {
testNEP17T := func(t *testing.T, start, stop, limit, page int, sent, rcvd []int) {
ps := []string{`"` + testchain.PrivateKeyByID(0).Address() + `"`}
if start != 0 {
h, err := e.chain.GetHeader(e.chain.GetHeaderHash(start))
@ -1228,19 +1228,19 @@ func testRPCProtocol(t *testing.T, doRPCCall func(string, string, *testing.T) []
ps = append(ps, strconv.FormatInt(int64(page), 10))
}
p := strings.Join(ps, ", ")
rpc := fmt.Sprintf(`{"jsonrpc": "2.0", "id": 1, "method": "getnep5transfers", "params": [%s]}`, p)
rpc := fmt.Sprintf(`{"jsonrpc": "2.0", "id": 1, "method": "getnep17transfers", "params": [%s]}`, p)
body := doRPCCall(rpc, httpSrv.URL, t)
res := checkErrGetResult(t, body, false)
actual := new(result.NEP5Transfers)
actual := new(result.NEP17Transfers)
require.NoError(t, json.Unmarshal(res, actual))
checkNep5TransfersAux(t, e, actual, sent, rcvd)
checkNep17TransfersAux(t, e, actual, sent, rcvd)
}
t.Run("time frame only", func(t *testing.T) { testNEP5T(t, 4, 5, 0, 0, []int{3, 4, 5, 6}, []int{1, 2}) })
t.Run("no res", func(t *testing.T) { testNEP5T(t, 100, 100, 0, 0, []int{}, []int{}) })
t.Run("limit", func(t *testing.T) { testNEP5T(t, 1, 7, 3, 0, []int{0, 1}, []int{0}) })
t.Run("limit 2", func(t *testing.T) { testNEP5T(t, 4, 5, 2, 0, []int{3}, []int{1}) })
t.Run("limit with page", func(t *testing.T) { testNEP5T(t, 1, 7, 3, 1, []int{2, 3}, []int{1}) })
t.Run("limit with page 2", func(t *testing.T) { testNEP5T(t, 1, 7, 3, 2, []int{4, 5}, []int{2}) })
t.Run("time frame only", func(t *testing.T) { testNEP17T(t, 4, 5, 0, 0, []int{3, 4, 5, 6}, []int{1, 2}) })
t.Run("no res", func(t *testing.T) { testNEP17T(t, 100, 100, 0, 0, []int{}, []int{}) })
t.Run("limit", func(t *testing.T) { testNEP17T(t, 1, 7, 3, 0, []int{0, 1}, []int{0}) })
t.Run("limit 2", func(t *testing.T) { testNEP17T(t, 4, 5, 2, 0, []int{3}, []int{1}) })
t.Run("limit with page", func(t *testing.T) { testNEP17T(t, 1, 7, 3, 1, []int{2, 3}, []int{1}) })
t.Run("limit with page 2", func(t *testing.T) { testNEP17T(t, 1, 7, 3, 2, []int{4, 5}, []int{2}) })
})
}
@ -1326,13 +1326,13 @@ func doRPCCallOverHTTP(rpcCall string, url string, t *testing.T) []byte {
return bytes.TrimSpace(body)
}
func checkNep5Balances(t *testing.T, e *executor, acc interface{}) {
res, ok := acc.(*result.NEP5Balances)
func checkNep17Balances(t *testing.T, e *executor, acc interface{}) {
res, ok := acc.(*result.NEP17Balances)
require.True(t, ok)
rubles, err := util.Uint160DecodeStringLE(testContractHash)
require.NoError(t, err)
expected := result.NEP5Balances{
Balances: []result.NEP5Balance{
expected := result.NEP17Balances{
Balances: []result.NEP17Balance{
{
Asset: rubles,
Amount: "877",
@ -1354,12 +1354,12 @@ func checkNep5Balances(t *testing.T, e *executor, acc interface{}) {
require.ElementsMatch(t, expected.Balances, res.Balances)
}
func checkNep5Transfers(t *testing.T, e *executor, acc interface{}) {
checkNep5TransfersAux(t, e, acc, []int{0, 1, 2, 3, 4, 5, 6, 7, 8}, []int{0, 1, 2, 3, 4, 5, 6})
func checkNep17Transfers(t *testing.T, e *executor, acc interface{}) {
checkNep17TransfersAux(t, e, acc, []int{0, 1, 2, 3, 4, 5, 6, 7, 8}, []int{0, 1, 2, 3, 4, 5, 6})
}
func checkNep5TransfersAux(t *testing.T, e *executor, acc interface{}, sent, rcvd []int) {
res, ok := acc.(*result.NEP5Transfers)
func checkNep17TransfersAux(t *testing.T, e *executor, acc interface{}, sent, rcvd []int) {
res, ok := acc.(*result.NEP17Transfers)
require.True(t, ok)
rublesHash, err := util.Uint160DecodeStringLE(testContractHash)
require.NoError(t, err)
@ -1410,8 +1410,8 @@ func checkNep5TransfersAux(t *testing.T, e *executor, acc interface{}, sent, rcv
// * to check chain events consistency
// Technically these could be retrieved from application log, but that would almost
// duplicate the Server method.
expected := result.NEP5Transfers{
Sent: []result.NEP5Transfer{
expected := result.NEP17Transfers{
Sent: []result.NEP17Transfer{
{
Timestamp: blockDeploy2.Timestamp,
Asset: e.chain.UtilityTokenHash(),
@ -1487,7 +1487,7 @@ func checkNep5TransfersAux(t *testing.T, e *executor, acc interface{}, sent, rcv
TxHash: blockCtrDeploy.Hash(),
},
},
Received: []result.NEP5Transfer{
Received: []result.NEP17Transfer{
{
Timestamp: blockGASBounty.Timestamp,
Asset: e.chain.UtilityTokenHash(),
@ -1547,7 +1547,7 @@ func checkNep5TransfersAux(t *testing.T, e *executor, acc interface{}, sent, rcv
require.Equal(t, expected.Address, res.Address)
arr := make([]result.NEP5Transfer, 0, len(expected.Sent))
arr := make([]result.NEP17Transfer, 0, len(expected.Sent))
for i := range expected.Sent {
for _, j := range sent {
if i == j {

View file

@ -13,9 +13,9 @@ func TestToken_MarshalJSON(t *testing.T) {
h, err := util.Uint160DecodeStringLE("f8d448b227991cf07cb96a6f9c0322437f1599b9")
require.NoError(t, err)
tok := NewToken(h, "NEP5 Standard", "NEP5", 8)
require.Equal(t, "NEP5 Standard", tok.Name)
require.Equal(t, "NEP5", tok.Symbol)
tok := NewToken(h, "NEP17 Standard", "NEP17", 8)
require.Equal(t, "NEP17 Standard", tok.Name)
require.Equal(t, "NEP17", tok.Symbol)
require.EqualValues(t, 8, tok.Decimals)
require.Equal(t, h, tok.Hash)
require.Equal(t, "NcqKahsZ93ZyYS5bep8G2TY1zRB7tfUPdK", tok.Address())