diff --git a/cli/query/query.go b/cli/query/query.go index e7c4461..1518fa8 100644 --- a/cli/query/query.go +++ b/cli/query/query.go @@ -17,9 +17,9 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/encoding/address" "github.com/tutus-one/tutus-chain/pkg/encoding/fixedn" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient/invoker" - "github.com/tutus-one/tutus-chain/pkg/rpcclient/neo" + "github.com/tutus-one/tutus-chain/pkg/rpcclient/tutus" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm" "github.com/tutus-one/tutus-chain/pkg/vm/vmstate" @@ -315,7 +315,7 @@ func queryVoter(ctx *cli.Context) error { return exitErr } - neoToken := neo.NewReader(invoker.New(c, nil)) + neoToken := tutus.NewReader(invoker.New(c, nil)) st, err := neoToken.GetAccountState(addr) if err != nil { diff --git a/cli/server/metrics.go b/cli/server/metrics.go index ddea09d..6409f63 100644 --- a/cli/server/metrics.go +++ b/cli/server/metrics.go @@ -6,13 +6,13 @@ import ( var neogoVersion = prometheus.NewGaugeVec( prometheus.GaugeOpts{ - Help: "NeoGo version", + Help: "Tutus version", Name: "version", Namespace: "neogo", }, []string{"version"}) -func setNeoGoVersion(nodeVer string) { +func setTutusVersion(nodeVer string) { neogoVersion.WithLabelValues(nodeVer).Add(1) } diff --git a/cli/server/server.go b/cli/server/server.go index 2824f4a..a96a389 100644 --- a/cli/server/server.go +++ b/cli/server/server.go @@ -83,7 +83,7 @@ func NewCommands() []*cli.Command { return []*cli.Command{ { Name: "node", - Usage: "Start a NeoGo node", + Usage: "Start a Tutus node", UsageText: "neo-go node [--config-path path] [-d] [-p/-m/-t] [--config-file file] [--force-timestamp-logs]", Action: startServer, Flags: cfgFlags, @@ -526,7 +526,7 @@ func startServer(ctx *cli.Context) error { errChan := make(chan error) rpcServer := rpcsrv.New(chain, cfg.ApplicationConfiguration.RPC, serv, oracleSrv, log, errChan) serv.AddService(rpcServer) - setNeoGoVersion(config.Version) + setTutusVersion(config.Version) serv.Start() if !cfg.ApplicationConfiguration.RPC.StartWhenSynchronized { // Run RPC server in a separate routine. This is necessary to avoid a potential @@ -697,7 +697,7 @@ func initBlockChain(cfg config.Config, log *zap.Logger) (*core.Blockchain, stora return chain, store, nil } -// Logo returns NeoGo logo. +// Logo returns Tutus logo. func Logo() string { return ` _ ____________ __________ diff --git a/cli/smartcontract/contract_test.go b/cli/smartcontract/contract_test.go index 0deff1e..b1a40a9 100644 --- a/cli/smartcontract/contract_test.go +++ b/cli/smartcontract/contract_test.go @@ -24,7 +24,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/crypto/keys" "github.com/tutus-one/tutus-chain/pkg/encoding/address" "github.com/tutus-one/tutus-chain/pkg/encoding/fixedn" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/smartcontract/manifest" "github.com/tutus-one/tutus-chain/pkg/smartcontract/nef" "github.com/tutus-one/tutus-chain/pkg/smartcontract/trigger" @@ -176,7 +176,7 @@ package testcontract import ( "github.com/tutus-one/tutus-chain/pkg/interop/contract" "github.com/tutus-one/tutus-chain/pkg/interop/native/ledger" - "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" "myimport.com/testcontract" ) @@ -185,22 +185,22 @@ const Hash = "\x10\x32\x54\x76\x98\x89\x67\x45\x23\x01\x10\x32\x54\x76\x98\x89\x // Block invokes `+"`block`"+` method of contract. func Block() *ledger.Block { - return neogointernal.CallWithToken(Hash, "block", int(contract.All)).(*ledger.Block) + return tutusinternal.CallWithToken(Hash, "block", int(contract.All)).(*ledger.Block) } // Blocks invokes `+"`blocks`"+` method of contract. func Blocks() []*ledger.Block { - return neogointernal.CallWithToken(Hash, "blocks", int(contract.All)).([]*ledger.Block) + return tutusinternal.CallWithToken(Hash, "blocks", int(contract.All)).([]*ledger.Block) } // ToArray invokes `+"`toArray`"+` method of contract. func ToArray(m map[int]string) []testcontract.MyPair { - return neogointernal.CallWithToken(Hash, "toArray", int(contract.All), m).([]testcontract.MyPair) + return tutusinternal.CallWithToken(Hash, "toArray", int(contract.All), m).([]testcontract.MyPair) } // ToMap invokes `+"`toMap`"+` method of contract. func ToMap(a []testcontract.MyPair) map[int]string { - return neogointernal.CallWithToken(Hash, "toMap", int(contract.All), a).(map[int]string) + return tutusinternal.CallWithToken(Hash, "toMap", int(contract.All), a).(map[int]string) } `, string(bs)) } diff --git a/cli/smartcontract/generate_test.go b/cli/smartcontract/generate_test.go index d85239c..38c69ce 100644 --- a/cli/smartcontract/generate_test.go +++ b/cli/smartcontract/generate_test.go @@ -161,7 +161,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/interop/contract" "github.com/tutus-one/tutus-chain/pkg/interop/iterator" "github.com/tutus-one/tutus-chain/pkg/interop/native/ledger" - "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" "github.com/tutus-one/tutus-chain/pkg/interop/storage" ) @@ -170,62 +170,62 @@ const Hash = "\x04\x08\x15\x16\x23\x42\x43\x44\x00\x01\xca\xfe\xba\xbe\xde\xad\x // Sum invokes ` + "`sum`" + ` method of contract. func Sum(first int, second int) int { - return neogointernal.CallWithToken(Hash, "sum", int(contract.All), first, second).(int) + return tutusinternal.CallWithToken(Hash, "sum", int(contract.All), first, second).(int) } // Sum2 invokes ` + "`sum`" + ` method of contract. func Sum2(first int, second int, third int) int { - return neogointernal.CallWithToken(Hash, "sum", int(contract.All), first, second, third).(int) + return tutusinternal.CallWithToken(Hash, "sum", int(contract.All), first, second, third).(int) } // Sum3 invokes ` + "`sum3`" + ` method of contract. func Sum3() int { - return neogointernal.CallWithToken(Hash, "sum3", int(contract.ReadOnly)).(int) + return tutusinternal.CallWithToken(Hash, "sum3", int(contract.ReadOnly)).(int) } // Zum invokes ` + "`zum`" + ` method of contract. func Zum(typev int, typev_ int, funcv int) int { - return neogointernal.CallWithToken(Hash, "zum", int(contract.All), typev, typev_, funcv).(int) + return tutusinternal.CallWithToken(Hash, "zum", int(contract.All), typev, typev_, funcv).(int) } // JustExecute invokes ` + "`justExecute`" + ` method of contract. func JustExecute(arr []any) { - neogointernal.CallWithTokenNoRet(Hash, "justExecute", int(contract.All), arr) + tutusinternal.CallWithTokenNoRet(Hash, "justExecute", int(contract.All), arr) } // GetPublicKey invokes ` + "`getPublicKey`" + ` method of contract. func GetPublicKey() interop.PublicKey { - return neogointernal.CallWithToken(Hash, "getPublicKey", int(contract.All)).(interop.PublicKey) + return tutusinternal.CallWithToken(Hash, "getPublicKey", int(contract.All)).(interop.PublicKey) } // OtherTypes invokes ` + "`otherTypes`" + ` method of contract. func OtherTypes(ctr interop.Hash160, tx interop.Hash256, sig interop.Signature, data any) bool { - return neogointernal.CallWithToken(Hash, "otherTypes", int(contract.All), ctr, tx, sig, data).(bool) + return tutusinternal.CallWithToken(Hash, "otherTypes", int(contract.All), ctr, tx, sig, data).(bool) } // SearchStorage invokes ` + "`searchStorage`" + ` method of contract. func SearchStorage(ctx storage.Context) iterator.Iterator { - return neogointernal.CallWithToken(Hash, "searchStorage", int(contract.All), ctx).(iterator.Iterator) + return tutusinternal.CallWithToken(Hash, "searchStorage", int(contract.All), ctx).(iterator.Iterator) } // GetFromMap invokes ` + "`getFromMap`" + ` method of contract. func GetFromMap(intMap map[string]int, indices []string) []int { - return neogointernal.CallWithToken(Hash, "getFromMap", int(contract.All), intMap, indices).([]int) + return tutusinternal.CallWithToken(Hash, "getFromMap", int(contract.All), intMap, indices).([]int) } // DoSomething invokes ` + "`doSomething`" + ` method of contract. func DoSomething(bytes []byte, str string) any { - return neogointernal.CallWithToken(Hash, "doSomething", int(contract.ReadStates), bytes, str).(any) + return tutusinternal.CallWithToken(Hash, "doSomething", int(contract.ReadStates), bytes, str).(any) } // GetBlockWrapper invokes ` + "`getBlockWrapper`" + ` method of contract. func GetBlockWrapper() ledger.Block { - return neogointernal.CallWithToken(Hash, "getBlockWrapper", int(contract.All)).(ledger.Block) + return tutusinternal.CallWithToken(Hash, "getBlockWrapper", int(contract.All)).(ledger.Block) } // MyFunc invokes ` + "`myFunc`" + ` method of contract. func MyFunc(in map[int]mycontract.Input) []mycontract.Output { - return neogointernal.CallWithToken(Hash, "myFunc", int(contract.All), in).([]mycontract.Output) + return tutusinternal.CallWithToken(Hash, "myFunc", int(contract.All), in).([]mycontract.Output) } ` @@ -365,7 +365,7 @@ package myspacecontract import ( "github.com/tutus-one/tutus-chain/pkg/interop/contract" - "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" ) // Hash contains contract hash in big-endian form. @@ -373,7 +373,7 @@ const Hash = "\x04\x08\x15\x16\x23\x42\x43\x44\x00\x01\xca\xfe\xba\xbe\xde\xad\x // Get invokes `+"`get`"+` method of contract. func Get() int { - return neogointernal.CallWithToken(Hash, "get", int(contract.ReadOnly)).(int) + return tutusinternal.CallWithToken(Hash, "get", int(contract.ReadOnly)).(int) } `, string(data)) e.Run(t, []string{"", "contract", "generate-rpcwrapper", @@ -390,7 +390,7 @@ func Get() int { package myspacecontract import ( - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient/unwrap" "github.com/tutus-one/tutus-chain/pkg/util" "math/big" diff --git a/cli/smartcontract/rpcbindings/notifications/rpcbindings/extended/rpcbindings_test.go b/cli/smartcontract/rpcbindings/notifications/rpcbindings/extended/rpcbindings_test.go index b796512..65f2cc1 100644 --- a/cli/smartcontract/rpcbindings/notifications/rpcbindings/extended/rpcbindings_test.go +++ b/cli/smartcontract/rpcbindings/notifications/rpcbindings/extended/rpcbindings_test.go @@ -1,746 +1,746 @@ -// Code generated by neo-go contract generate-rpcwrapper --manifest --out [--hash ] [--config ]; DO NOT EDIT. - -// Package structs contains RPC wrappers for Notifications contract. -package structs - -import ( - "errors" - "fmt" - "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" - "github.com/tutus-one/tutus-chain/pkg/smartcontract" - "github.com/tutus-one/tutus-chain/pkg/util" - "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" - "math/big" - "unicode/utf8" -) - -// Hash contains contract hash. -var Hash = util.Uint160{0x33, 0x22, 0x11, 0x0, 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x0} - -// CrazyStruct is a contract-specific crazyStruct type used by its methods. -type CrazyStruct struct { - I *big.Int - B bool -} - -// SimpleStruct is a contract-specific simpleStruct type used by its methods. -type SimpleStruct struct { - I *big.Int -} - -// ComplicatedNameEvent represents "! complicated name %$#" event emitted by the contract. -type ComplicatedNameEvent struct { - ComplicatedParam string -} - -// SomeMapEvent represents "SomeMap" event emitted by the contract. -type SomeMapEvent struct { - M map[*big.Int]map[string][]util.Uint160 -} - -// SomeStructEvent represents "SomeStruct" event emitted by the contract. -type SomeStructEvent struct { - S *CrazyStruct -} - -// SomeArrayEvent represents "SomeArray" event emitted by the contract. -type SomeArrayEvent struct { - A [][]*big.Int -} - -// SomeUnexportedFieldEvent represents "SomeUnexportedField" event emitted by the contract. -type SomeUnexportedFieldEvent struct { - S *SimpleStruct -} - -// Actor is used by Contract to call state-changing methods. -type Actor interface { - MakeCall(contract util.Uint160, method string, params ...any) (*transaction.Transaction, error) - MakeRun(script []byte) (*transaction.Transaction, error) - MakeUnsignedCall(contract util.Uint160, method string, attrs []transaction.Attribute, params ...any) (*transaction.Transaction, error) - MakeUnsignedRun(script []byte, attrs []transaction.Attribute) (*transaction.Transaction, error) - SendCall(contract util.Uint160, method string, params ...any) (util.Uint256, uint32, error) - SendRun(script []byte) (util.Uint256, uint32, error) -} - -// Contract implements all contract methods. -type Contract struct { - actor Actor - hash util.Uint160 -} - -// New creates an instance of Contract using Hash and the given Actor. -func New(actor Actor) *Contract { - var hash = Hash - return &Contract{actor, hash} -} - -// Array creates a transaction invoking `array` method of the contract. -// This transaction is signed and immediately sent to the network. -// The values returned are its hash, ValidUntilBlock value and error if any. -func (c *Contract) Array() (util.Uint256, uint32, error) { - return c.actor.SendCall(c.hash, "array") -} - -// ArrayTransaction creates a transaction invoking `array` method of the contract. -// This transaction is signed, but not sent to the network, instead it's -// returned to the caller. -func (c *Contract) ArrayTransaction() (*transaction.Transaction, error) { - return c.actor.MakeCall(c.hash, "array") -} - -// ArrayUnsigned creates a transaction invoking `array` method of the contract. -// This transaction is not signed, it's simply returned to the caller. -// Any fields of it that do not affect fees can be changed (ValidUntilBlock, -// Nonce), fee values (NetworkFee, SystemFee) can be increased as well. -func (c *Contract) ArrayUnsigned() (*transaction.Transaction, error) { - return c.actor.MakeUnsignedCall(c.hash, "array", nil) -} - -// CrazyMap creates a transaction invoking `crazyMap` method of the contract. -// This transaction is signed and immediately sent to the network. -// The values returned are its hash, ValidUntilBlock value and error if any. -func (c *Contract) CrazyMap() (util.Uint256, uint32, error) { - return c.actor.SendCall(c.hash, "crazyMap") -} - -// CrazyMapTransaction creates a transaction invoking `crazyMap` method of the contract. -// This transaction is signed, but not sent to the network, instead it's -// returned to the caller. -func (c *Contract) CrazyMapTransaction() (*transaction.Transaction, error) { - return c.actor.MakeCall(c.hash, "crazyMap") -} - -// CrazyMapUnsigned creates a transaction invoking `crazyMap` method of the contract. -// This transaction is not signed, it's simply returned to the caller. -// Any fields of it that do not affect fees can be changed (ValidUntilBlock, -// Nonce), fee values (NetworkFee, SystemFee) can be increased as well. -func (c *Contract) CrazyMapUnsigned() (*transaction.Transaction, error) { - return c.actor.MakeUnsignedCall(c.hash, "crazyMap", nil) -} - -// Main creates a transaction invoking `main` method of the contract. -// This transaction is signed and immediately sent to the network. -// The values returned are its hash, ValidUntilBlock value and error if any. -func (c *Contract) Main() (util.Uint256, uint32, error) { - return c.actor.SendCall(c.hash, "main") -} - -// MainTransaction creates a transaction invoking `main` method of the contract. -// This transaction is signed, but not sent to the network, instead it's -// returned to the caller. -func (c *Contract) MainTransaction() (*transaction.Transaction, error) { - return c.actor.MakeCall(c.hash, "main") -} - -// MainUnsigned creates a transaction invoking `main` method of the contract. -// This transaction is not signed, it's simply returned to the caller. -// Any fields of it that do not affect fees can be changed (ValidUntilBlock, -// Nonce), fee values (NetworkFee, SystemFee) can be increased as well. -func (c *Contract) MainUnsigned() (*transaction.Transaction, error) { - return c.actor.MakeUnsignedCall(c.hash, "main", nil) -} - -// Struct creates a transaction invoking `struct` method of the contract. -// This transaction is signed and immediately sent to the network. -// The values returned are its hash, ValidUntilBlock value and error if any. -func (c *Contract) Struct() (util.Uint256, uint32, error) { - return c.actor.SendCall(c.hash, "struct") -} - -// StructTransaction creates a transaction invoking `struct` method of the contract. -// This transaction is signed, but not sent to the network, instead it's -// returned to the caller. -func (c *Contract) StructTransaction() (*transaction.Transaction, error) { - return c.actor.MakeCall(c.hash, "struct") -} - -// StructUnsigned creates a transaction invoking `struct` method of the contract. -// This transaction is not signed, it's simply returned to the caller. -// Any fields of it that do not affect fees can be changed (ValidUntilBlock, -// Nonce), fee values (NetworkFee, SystemFee) can be increased as well. -func (c *Contract) StructUnsigned() (*transaction.Transaction, error) { - return c.actor.MakeUnsignedCall(c.hash, "struct", nil) -} - -// UnexportedField creates a transaction invoking `unexportedField` method of the contract. -// This transaction is signed and immediately sent to the network. -// The values returned are its hash, ValidUntilBlock value and error if any. -func (c *Contract) UnexportedField() (util.Uint256, uint32, error) { - return c.actor.SendCall(c.hash, "unexportedField") -} - -// UnexportedFieldTransaction creates a transaction invoking `unexportedField` method of the contract. -// This transaction is signed, but not sent to the network, instead it's -// returned to the caller. -func (c *Contract) UnexportedFieldTransaction() (*transaction.Transaction, error) { - return c.actor.MakeCall(c.hash, "unexportedField") -} - -// UnexportedFieldUnsigned creates a transaction invoking `unexportedField` method of the contract. -// This transaction is not signed, it's simply returned to the caller. -// Any fields of it that do not affect fees can be changed (ValidUntilBlock, -// Nonce), fee values (NetworkFee, SystemFee) can be increased as well. -func (c *Contract) UnexportedFieldUnsigned() (*transaction.Transaction, error) { - return c.actor.MakeUnsignedCall(c.hash, "unexportedField", nil) -} - -// itemToCrazyStruct converts stack item into *CrazyStruct. -// NULL item is returned as nil pointer without error. -func itemToCrazyStruct(item stackitem.Item, err error) (*CrazyStruct, error) { - if err != nil { - return nil, err - } - _, null := item.(stackitem.Null) - if null { - return nil, nil - } - var res = new(CrazyStruct) - err = res.FromStackItem(item) - return res, err -} - -// Ensure *CrazyStruct is a proper [stackitem.Convertible]. -var _ = stackitem.Convertible(&CrazyStruct{}) - -// Ensure *CrazyStruct is a proper [smartcontract.Convertible]. -var _ = smartcontract.Convertible(&CrazyStruct{}) - -// FromStackItem retrieves fields of CrazyStruct from the given -// [stackitem.Item] or returns an error if it's not possible to do to so. -// It implements [stackitem.Convertible] interface. -func (res *CrazyStruct) FromStackItem(item stackitem.Item) error { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 2 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - res.I, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field I: %w", err) - } - - index++ - res.B, err = arr[index].TryBool() - if err != nil { - return fmt.Errorf("field B: %w", err) - } - - return nil -} - -// ToStackItem creates [stackitem.Item] representing CrazyStruct. -// It implements [stackitem.Convertible] interface. -func (res *CrazyStruct) ToStackItem() (stackitem.Item, error) { - if res == nil { - return stackitem.Null{}, nil - } - - var ( - err error - itm stackitem.Item - items = make([]stackitem.Item, 0, 2) - ) - itm, err = (*stackitem.BigInteger)(res.I), error(nil) - if err != nil { - return nil, fmt.Errorf("field I: %w", err) - } - items = append(items, itm) - - itm, err = stackitem.NewBool(res.B), error(nil) - if err != nil { - return nil, fmt.Errorf("field B: %w", err) - } - items = append(items, itm) - - return stackitem.NewStruct(items), nil -} - -// ToSCParameter creates [smartcontract.Parameter] representing CrazyStruct. -// It implements [smartcontract.Convertible] interface so that CrazyStruct -// could be used with invokers. -func (res *CrazyStruct) ToSCParameter() (smartcontract.Parameter, error) { - if res == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var ( - err error - prm smartcontract.Parameter - prms = make([]smartcontract.Parameter, 0, 2) - ) - prm, err = smartcontract.NewParameterFromValue(res.I) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field I: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.B) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field B: %w", err) - } - prms = append(prms, prm) - - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil -} - -// itemToSimpleStruct converts stack item into *SimpleStruct. -// NULL item is returned as nil pointer without error. -func itemToSimpleStruct(item stackitem.Item, err error) (*SimpleStruct, error) { - if err != nil { - return nil, err - } - _, null := item.(stackitem.Null) - if null { - return nil, nil - } - var res = new(SimpleStruct) - err = res.FromStackItem(item) - return res, err -} - -// Ensure *SimpleStruct is a proper [stackitem.Convertible]. -var _ = stackitem.Convertible(&SimpleStruct{}) - -// Ensure *SimpleStruct is a proper [smartcontract.Convertible]. -var _ = smartcontract.Convertible(&SimpleStruct{}) - -// FromStackItem retrieves fields of SimpleStruct from the given -// [stackitem.Item] or returns an error if it's not possible to do to so. -// It implements [stackitem.Convertible] interface. -func (res *SimpleStruct) FromStackItem(item stackitem.Item) error { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 1 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - res.I, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field I: %w", err) - } - - return nil -} - -// ToStackItem creates [stackitem.Item] representing SimpleStruct. -// It implements [stackitem.Convertible] interface. -func (res *SimpleStruct) ToStackItem() (stackitem.Item, error) { - if res == nil { - return stackitem.Null{}, nil - } - - var ( - err error - itm stackitem.Item - items = make([]stackitem.Item, 0, 1) - ) - itm, err = (*stackitem.BigInteger)(res.I), error(nil) - if err != nil { - return nil, fmt.Errorf("field I: %w", err) - } - items = append(items, itm) - - return stackitem.NewStruct(items), nil -} - -// ToSCParameter creates [smartcontract.Parameter] representing SimpleStruct. -// It implements [smartcontract.Convertible] interface so that SimpleStruct -// could be used with invokers. -func (res *SimpleStruct) ToSCParameter() (smartcontract.Parameter, error) { - if res == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var ( - err error - prm smartcontract.Parameter - prms = make([]smartcontract.Parameter, 0, 1) - ) - prm, err = smartcontract.NewParameterFromValue(res.I) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field I: %w", err) - } - prms = append(prms, prm) - - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil -} - -// ComplicatedNameEventsFromApplicationLog retrieves a set of all emitted events -// with "! complicated name %$#" name from the provided [result.ApplicationLog]. -func ComplicatedNameEventsFromApplicationLog(log *result.ApplicationLog) ([]*ComplicatedNameEvent, error) { - if log == nil { - return nil, errors.New("nil application log") - } - - var res []*ComplicatedNameEvent - for i, ex := range log.Executions { - for j, e := range ex.Events { - if e.Name != "! complicated name %$#" { - continue - } - event := new(ComplicatedNameEvent) - err := event.FromStackItem(e.Item) - if err != nil { - return nil, fmt.Errorf("failed to deserialize ComplicatedNameEvent from stackitem (execution #%d, event #%d): %w", i, j, err) - } - res = append(res, event) - } - } - - return res, nil -} - -// FromStackItem converts provided [stackitem.Array] to ComplicatedNameEvent or -// returns an error if it's not possible to do to so. -func (e *ComplicatedNameEvent) FromStackItem(item *stackitem.Array) error { - if item == nil { - return errors.New("nil item") - } - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 1 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - e.ComplicatedParam, err = func(item stackitem.Item) (string, error) { - b, err := item.TryBytes() - if err != nil { - return "", err - } - if !utf8.Valid(b) { - return "", errors.New("not a UTF-8 string") - } - return string(b), nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field ComplicatedParam: %w", err) - } - - return nil -} - -// SomeMapEventsFromApplicationLog retrieves a set of all emitted events -// with "SomeMap" name from the provided [result.ApplicationLog]. -func SomeMapEventsFromApplicationLog(log *result.ApplicationLog) ([]*SomeMapEvent, error) { - if log == nil { - return nil, errors.New("nil application log") - } - - var res []*SomeMapEvent - for i, ex := range log.Executions { - for j, e := range ex.Events { - if e.Name != "SomeMap" { - continue - } - event := new(SomeMapEvent) - err := event.FromStackItem(e.Item) - if err != nil { - return nil, fmt.Errorf("failed to deserialize SomeMapEvent from stackitem (execution #%d, event #%d): %w", i, j, err) - } - res = append(res, event) - } - } - - return res, nil -} - -// FromStackItem converts provided [stackitem.Array] to SomeMapEvent or -// returns an error if it's not possible to do to so. -func (e *SomeMapEvent) FromStackItem(item *stackitem.Array) error { - if item == nil { - return errors.New("nil item") - } - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 1 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - e.M, err = func(item stackitem.Item) (map[*big.Int]map[string][]util.Uint160, error) { - m, ok := item.Value().([]stackitem.MapElement) - if !ok { - return nil, fmt.Errorf("%s is not a map", item.Type().String()) - } - res := make(map[*big.Int]map[string][]util.Uint160) - for i := range m { - k, err := m[i].Key.TryInteger() - if err != nil { - return nil, fmt.Errorf("key %d: %w", i, err) - } - v, err := func(item stackitem.Item) (map[string][]util.Uint160, error) { - m, ok := item.Value().([]stackitem.MapElement) - if !ok { - return nil, fmt.Errorf("%s is not a map", item.Type().String()) - } - res := make(map[string][]util.Uint160) - for i := range m { - k, err := func(item stackitem.Item) (string, error) { - b, err := item.TryBytes() - if err != nil { - return "", err - } - if !utf8.Valid(b) { - return "", errors.New("not a UTF-8 string") - } - return string(b), nil - }(m[i].Key) - if err != nil { - return nil, fmt.Errorf("key %d: %w", i, err) - } - v, err := func(item stackitem.Item) ([]util.Uint160, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([]util.Uint160, len(arr)) - for i := range res { - res[i], err = func(item stackitem.Item) (util.Uint160, error) { - b, err := item.TryBytes() - if err != nil { - return util.Uint160{}, err - } - u, err := util.Uint160DecodeBytesBE(b) - if err != nil { - return util.Uint160{}, err - } - return u, nil - }(arr[i]) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(m[i].Value) - if err != nil { - return nil, fmt.Errorf("value %d: %w", i, err) - } - res[k] = v - } - return res, nil - }(m[i].Value) - if err != nil { - return nil, fmt.Errorf("value %d: %w", i, err) - } - res[k] = v - } - return res, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field M: %w", err) - } - - return nil -} - -// SomeStructEventsFromApplicationLog retrieves a set of all emitted events -// with "SomeStruct" name from the provided [result.ApplicationLog]. -func SomeStructEventsFromApplicationLog(log *result.ApplicationLog) ([]*SomeStructEvent, error) { - if log == nil { - return nil, errors.New("nil application log") - } - - var res []*SomeStructEvent - for i, ex := range log.Executions { - for j, e := range ex.Events { - if e.Name != "SomeStruct" { - continue - } - event := new(SomeStructEvent) - err := event.FromStackItem(e.Item) - if err != nil { - return nil, fmt.Errorf("failed to deserialize SomeStructEvent from stackitem (execution #%d, event #%d): %w", i, j, err) - } - res = append(res, event) - } - } - - return res, nil -} - -// FromStackItem converts provided [stackitem.Array] to SomeStructEvent or -// returns an error if it's not possible to do to so. -func (e *SomeStructEvent) FromStackItem(item *stackitem.Array) error { - if item == nil { - return errors.New("nil item") - } - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 1 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - e.S, err = itemToCrazyStruct(arr[index], nil) - if err != nil { - return fmt.Errorf("field S: %w", err) - } - - return nil -} - -// SomeArrayEventsFromApplicationLog retrieves a set of all emitted events -// with "SomeArray" name from the provided [result.ApplicationLog]. -func SomeArrayEventsFromApplicationLog(log *result.ApplicationLog) ([]*SomeArrayEvent, error) { - if log == nil { - return nil, errors.New("nil application log") - } - - var res []*SomeArrayEvent - for i, ex := range log.Executions { - for j, e := range ex.Events { - if e.Name != "SomeArray" { - continue - } - event := new(SomeArrayEvent) - err := event.FromStackItem(e.Item) - if err != nil { - return nil, fmt.Errorf("failed to deserialize SomeArrayEvent from stackitem (execution #%d, event #%d): %w", i, j, err) - } - res = append(res, event) - } - } - - return res, nil -} - -// FromStackItem converts provided [stackitem.Array] to SomeArrayEvent or -// returns an error if it's not possible to do to so. -func (e *SomeArrayEvent) FromStackItem(item *stackitem.Array) error { - if item == nil { - return errors.New("nil item") - } - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 1 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - e.A, err = func(item stackitem.Item) ([][]*big.Int, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([][]*big.Int, len(arr)) - for i := range res { - res[i], err = func(item stackitem.Item) ([]*big.Int, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([]*big.Int, len(arr)) - for i := range res { - res[i], err = arr[i].TryInteger() - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(arr[i]) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field A: %w", err) - } - - return nil -} - -// SomeUnexportedFieldEventsFromApplicationLog retrieves a set of all emitted events -// with "SomeUnexportedField" name from the provided [result.ApplicationLog]. -func SomeUnexportedFieldEventsFromApplicationLog(log *result.ApplicationLog) ([]*SomeUnexportedFieldEvent, error) { - if log == nil { - return nil, errors.New("nil application log") - } - - var res []*SomeUnexportedFieldEvent - for i, ex := range log.Executions { - for j, e := range ex.Events { - if e.Name != "SomeUnexportedField" { - continue - } - event := new(SomeUnexportedFieldEvent) - err := event.FromStackItem(e.Item) - if err != nil { - return nil, fmt.Errorf("failed to deserialize SomeUnexportedFieldEvent from stackitem (execution #%d, event #%d): %w", i, j, err) - } - res = append(res, event) - } - } - - return res, nil -} - -// FromStackItem converts provided [stackitem.Array] to SomeUnexportedFieldEvent or -// returns an error if it's not possible to do to so. -func (e *SomeUnexportedFieldEvent) FromStackItem(item *stackitem.Array) error { - if item == nil { - return errors.New("nil item") - } - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 1 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - e.S, err = itemToSimpleStruct(arr[index], nil) - if err != nil { - return fmt.Errorf("field S: %w", err) - } - - return nil -} +// Code generated by neo-go contract generate-rpcwrapper --manifest --out [--hash ] [--config ]; DO NOT EDIT. + +// Package structs contains RPC wrappers for Notifications contract. +package structs + +import ( + "errors" + "fmt" + "github.com/tutus-one/tutus-chain/pkg/core/transaction" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" + "github.com/tutus-one/tutus-chain/pkg/smartcontract" + "github.com/tutus-one/tutus-chain/pkg/util" + "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" + "math/big" + "unicode/utf8" +) + +// Hash contains contract hash. +var Hash = util.Uint160{0x33, 0x22, 0x11, 0x0, 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x0} + +// CrazyStruct is a contract-specific crazyStruct type used by its methods. +type CrazyStruct struct { + I *big.Int + B bool +} + +// SimpleStruct is a contract-specific simpleStruct type used by its methods. +type SimpleStruct struct { + I *big.Int +} + +// ComplicatedNameEvent represents "! complicated name %$#" event emitted by the contract. +type ComplicatedNameEvent struct { + ComplicatedParam string +} + +// SomeMapEvent represents "SomeMap" event emitted by the contract. +type SomeMapEvent struct { + M map[*big.Int]map[string][]util.Uint160 +} + +// SomeStructEvent represents "SomeStruct" event emitted by the contract. +type SomeStructEvent struct { + S *CrazyStruct +} + +// SomeArrayEvent represents "SomeArray" event emitted by the contract. +type SomeArrayEvent struct { + A [][]*big.Int +} + +// SomeUnexportedFieldEvent represents "SomeUnexportedField" event emitted by the contract. +type SomeUnexportedFieldEvent struct { + S *SimpleStruct +} + +// Actor is used by Contract to call state-changing methods. +type Actor interface { + MakeCall(contract util.Uint160, method string, params ...any) (*transaction.Transaction, error) + MakeRun(script []byte) (*transaction.Transaction, error) + MakeUnsignedCall(contract util.Uint160, method string, attrs []transaction.Attribute, params ...any) (*transaction.Transaction, error) + MakeUnsignedRun(script []byte, attrs []transaction.Attribute) (*transaction.Transaction, error) + SendCall(contract util.Uint160, method string, params ...any) (util.Uint256, uint32, error) + SendRun(script []byte) (util.Uint256, uint32, error) +} + +// Contract implements all contract methods. +type Contract struct { + actor Actor + hash util.Uint160 +} + +// New creates an instance of Contract using Hash and the given Actor. +func New(actor Actor) *Contract { + var hash = Hash + return &Contract{actor, hash} +} + +// Array creates a transaction invoking `array` method of the contract. +// This transaction is signed and immediately sent to the network. +// The values returned are its hash, ValidUntilBlock value and error if any. +func (c *Contract) Array() (util.Uint256, uint32, error) { + return c.actor.SendCall(c.hash, "array") +} + +// ArrayTransaction creates a transaction invoking `array` method of the contract. +// This transaction is signed, but not sent to the network, instead it's +// returned to the caller. +func (c *Contract) ArrayTransaction() (*transaction.Transaction, error) { + return c.actor.MakeCall(c.hash, "array") +} + +// ArrayUnsigned creates a transaction invoking `array` method of the contract. +// This transaction is not signed, it's simply returned to the caller. +// Any fields of it that do not affect fees can be changed (ValidUntilBlock, +// Nonce), fee values (NetworkFee, SystemFee) can be increased as well. +func (c *Contract) ArrayUnsigned() (*transaction.Transaction, error) { + return c.actor.MakeUnsignedCall(c.hash, "array", nil) +} + +// CrazyMap creates a transaction invoking `crazyMap` method of the contract. +// This transaction is signed and immediately sent to the network. +// The values returned are its hash, ValidUntilBlock value and error if any. +func (c *Contract) CrazyMap() (util.Uint256, uint32, error) { + return c.actor.SendCall(c.hash, "crazyMap") +} + +// CrazyMapTransaction creates a transaction invoking `crazyMap` method of the contract. +// This transaction is signed, but not sent to the network, instead it's +// returned to the caller. +func (c *Contract) CrazyMapTransaction() (*transaction.Transaction, error) { + return c.actor.MakeCall(c.hash, "crazyMap") +} + +// CrazyMapUnsigned creates a transaction invoking `crazyMap` method of the contract. +// This transaction is not signed, it's simply returned to the caller. +// Any fields of it that do not affect fees can be changed (ValidUntilBlock, +// Nonce), fee values (NetworkFee, SystemFee) can be increased as well. +func (c *Contract) CrazyMapUnsigned() (*transaction.Transaction, error) { + return c.actor.MakeUnsignedCall(c.hash, "crazyMap", nil) +} + +// Main creates a transaction invoking `main` method of the contract. +// This transaction is signed and immediately sent to the network. +// The values returned are its hash, ValidUntilBlock value and error if any. +func (c *Contract) Main() (util.Uint256, uint32, error) { + return c.actor.SendCall(c.hash, "main") +} + +// MainTransaction creates a transaction invoking `main` method of the contract. +// This transaction is signed, but not sent to the network, instead it's +// returned to the caller. +func (c *Contract) MainTransaction() (*transaction.Transaction, error) { + return c.actor.MakeCall(c.hash, "main") +} + +// MainUnsigned creates a transaction invoking `main` method of the contract. +// This transaction is not signed, it's simply returned to the caller. +// Any fields of it that do not affect fees can be changed (ValidUntilBlock, +// Nonce), fee values (NetworkFee, SystemFee) can be increased as well. +func (c *Contract) MainUnsigned() (*transaction.Transaction, error) { + return c.actor.MakeUnsignedCall(c.hash, "main", nil) +} + +// Struct creates a transaction invoking `struct` method of the contract. +// This transaction is signed and immediately sent to the network. +// The values returned are its hash, ValidUntilBlock value and error if any. +func (c *Contract) Struct() (util.Uint256, uint32, error) { + return c.actor.SendCall(c.hash, "struct") +} + +// StructTransaction creates a transaction invoking `struct` method of the contract. +// This transaction is signed, but not sent to the network, instead it's +// returned to the caller. +func (c *Contract) StructTransaction() (*transaction.Transaction, error) { + return c.actor.MakeCall(c.hash, "struct") +} + +// StructUnsigned creates a transaction invoking `struct` method of the contract. +// This transaction is not signed, it's simply returned to the caller. +// Any fields of it that do not affect fees can be changed (ValidUntilBlock, +// Nonce), fee values (NetworkFee, SystemFee) can be increased as well. +func (c *Contract) StructUnsigned() (*transaction.Transaction, error) { + return c.actor.MakeUnsignedCall(c.hash, "struct", nil) +} + +// UnexportedField creates a transaction invoking `unexportedField` method of the contract. +// This transaction is signed and immediately sent to the network. +// The values returned are its hash, ValidUntilBlock value and error if any. +func (c *Contract) UnexportedField() (util.Uint256, uint32, error) { + return c.actor.SendCall(c.hash, "unexportedField") +} + +// UnexportedFieldTransaction creates a transaction invoking `unexportedField` method of the contract. +// This transaction is signed, but not sent to the network, instead it's +// returned to the caller. +func (c *Contract) UnexportedFieldTransaction() (*transaction.Transaction, error) { + return c.actor.MakeCall(c.hash, "unexportedField") +} + +// UnexportedFieldUnsigned creates a transaction invoking `unexportedField` method of the contract. +// This transaction is not signed, it's simply returned to the caller. +// Any fields of it that do not affect fees can be changed (ValidUntilBlock, +// Nonce), fee values (NetworkFee, SystemFee) can be increased as well. +func (c *Contract) UnexportedFieldUnsigned() (*transaction.Transaction, error) { + return c.actor.MakeUnsignedCall(c.hash, "unexportedField", nil) +} + +// itemToCrazyStruct converts stack item into *CrazyStruct. +// NULL item is returned as nil pointer without error. +func itemToCrazyStruct(item stackitem.Item, err error) (*CrazyStruct, error) { + if err != nil { + return nil, err + } + _, null := item.(stackitem.Null) + if null { + return nil, nil + } + var res = new(CrazyStruct) + err = res.FromStackItem(item) + return res, err +} + +// Ensure *CrazyStruct is a proper [stackitem.Convertible]. +var _ = stackitem.Convertible(&CrazyStruct{}) + +// Ensure *CrazyStruct is a proper [smartcontract.Convertible]. +var _ = smartcontract.Convertible(&CrazyStruct{}) + +// FromStackItem retrieves fields of CrazyStruct from the given +// [stackitem.Item] or returns an error if it's not possible to do to so. +// It implements [stackitem.Convertible] interface. +func (res *CrazyStruct) FromStackItem(item stackitem.Item) error { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 2 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + res.I, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field I: %w", err) + } + + index++ + res.B, err = arr[index].TryBool() + if err != nil { + return fmt.Errorf("field B: %w", err) + } + + return nil +} + +// ToStackItem creates [stackitem.Item] representing CrazyStruct. +// It implements [stackitem.Convertible] interface. +func (res *CrazyStruct) ToStackItem() (stackitem.Item, error) { + if res == nil { + return stackitem.Null{}, nil + } + + var ( + err error + itm stackitem.Item + items = make([]stackitem.Item, 0, 2) + ) + itm, err = (*stackitem.BigInteger)(res.I), error(nil) + if err != nil { + return nil, fmt.Errorf("field I: %w", err) + } + items = append(items, itm) + + itm, err = stackitem.NewBool(res.B), error(nil) + if err != nil { + return nil, fmt.Errorf("field B: %w", err) + } + items = append(items, itm) + + return stackitem.NewStruct(items), nil +} + +// ToSCParameter creates [smartcontract.Parameter] representing CrazyStruct. +// It implements [smartcontract.Convertible] interface so that CrazyStruct +// could be used with invokers. +func (res *CrazyStruct) ToSCParameter() (smartcontract.Parameter, error) { + if res == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var ( + err error + prm smartcontract.Parameter + prms = make([]smartcontract.Parameter, 0, 2) + ) + prm, err = smartcontract.NewParameterFromValue(res.I) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field I: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.B) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field B: %w", err) + } + prms = append(prms, prm) + + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil +} + +// itemToSimpleStruct converts stack item into *SimpleStruct. +// NULL item is returned as nil pointer without error. +func itemToSimpleStruct(item stackitem.Item, err error) (*SimpleStruct, error) { + if err != nil { + return nil, err + } + _, null := item.(stackitem.Null) + if null { + return nil, nil + } + var res = new(SimpleStruct) + err = res.FromStackItem(item) + return res, err +} + +// Ensure *SimpleStruct is a proper [stackitem.Convertible]. +var _ = stackitem.Convertible(&SimpleStruct{}) + +// Ensure *SimpleStruct is a proper [smartcontract.Convertible]. +var _ = smartcontract.Convertible(&SimpleStruct{}) + +// FromStackItem retrieves fields of SimpleStruct from the given +// [stackitem.Item] or returns an error if it's not possible to do to so. +// It implements [stackitem.Convertible] interface. +func (res *SimpleStruct) FromStackItem(item stackitem.Item) error { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 1 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + res.I, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field I: %w", err) + } + + return nil +} + +// ToStackItem creates [stackitem.Item] representing SimpleStruct. +// It implements [stackitem.Convertible] interface. +func (res *SimpleStruct) ToStackItem() (stackitem.Item, error) { + if res == nil { + return stackitem.Null{}, nil + } + + var ( + err error + itm stackitem.Item + items = make([]stackitem.Item, 0, 1) + ) + itm, err = (*stackitem.BigInteger)(res.I), error(nil) + if err != nil { + return nil, fmt.Errorf("field I: %w", err) + } + items = append(items, itm) + + return stackitem.NewStruct(items), nil +} + +// ToSCParameter creates [smartcontract.Parameter] representing SimpleStruct. +// It implements [smartcontract.Convertible] interface so that SimpleStruct +// could be used with invokers. +func (res *SimpleStruct) ToSCParameter() (smartcontract.Parameter, error) { + if res == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var ( + err error + prm smartcontract.Parameter + prms = make([]smartcontract.Parameter, 0, 1) + ) + prm, err = smartcontract.NewParameterFromValue(res.I) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field I: %w", err) + } + prms = append(prms, prm) + + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil +} + +// ComplicatedNameEventsFromApplicationLog retrieves a set of all emitted events +// with "! complicated name %$#" name from the provided [result.ApplicationLog]. +func ComplicatedNameEventsFromApplicationLog(log *result.ApplicationLog) ([]*ComplicatedNameEvent, error) { + if log == nil { + return nil, errors.New("nil application log") + } + + var res []*ComplicatedNameEvent + for i, ex := range log.Executions { + for j, e := range ex.Events { + if e.Name != "! complicated name %$#" { + continue + } + event := new(ComplicatedNameEvent) + err := event.FromStackItem(e.Item) + if err != nil { + return nil, fmt.Errorf("failed to deserialize ComplicatedNameEvent from stackitem (execution #%d, event #%d): %w", i, j, err) + } + res = append(res, event) + } + } + + return res, nil +} + +// FromStackItem converts provided [stackitem.Array] to ComplicatedNameEvent or +// returns an error if it's not possible to do to so. +func (e *ComplicatedNameEvent) FromStackItem(item *stackitem.Array) error { + if item == nil { + return errors.New("nil item") + } + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 1 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + e.ComplicatedParam, err = func(item stackitem.Item) (string, error) { + b, err := item.TryBytes() + if err != nil { + return "", err + } + if !utf8.Valid(b) { + return "", errors.New("not a UTF-8 string") + } + return string(b), nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field ComplicatedParam: %w", err) + } + + return nil +} + +// SomeMapEventsFromApplicationLog retrieves a set of all emitted events +// with "SomeMap" name from the provided [result.ApplicationLog]. +func SomeMapEventsFromApplicationLog(log *result.ApplicationLog) ([]*SomeMapEvent, error) { + if log == nil { + return nil, errors.New("nil application log") + } + + var res []*SomeMapEvent + for i, ex := range log.Executions { + for j, e := range ex.Events { + if e.Name != "SomeMap" { + continue + } + event := new(SomeMapEvent) + err := event.FromStackItem(e.Item) + if err != nil { + return nil, fmt.Errorf("failed to deserialize SomeMapEvent from stackitem (execution #%d, event #%d): %w", i, j, err) + } + res = append(res, event) + } + } + + return res, nil +} + +// FromStackItem converts provided [stackitem.Array] to SomeMapEvent or +// returns an error if it's not possible to do to so. +func (e *SomeMapEvent) FromStackItem(item *stackitem.Array) error { + if item == nil { + return errors.New("nil item") + } + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 1 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + e.M, err = func(item stackitem.Item) (map[*big.Int]map[string][]util.Uint160, error) { + m, ok := item.Value().([]stackitem.MapElement) + if !ok { + return nil, fmt.Errorf("%s is not a map", item.Type().String()) + } + res := make(map[*big.Int]map[string][]util.Uint160) + for i := range m { + k, err := m[i].Key.TryInteger() + if err != nil { + return nil, fmt.Errorf("key %d: %w", i, err) + } + v, err := func(item stackitem.Item) (map[string][]util.Uint160, error) { + m, ok := item.Value().([]stackitem.MapElement) + if !ok { + return nil, fmt.Errorf("%s is not a map", item.Type().String()) + } + res := make(map[string][]util.Uint160) + for i := range m { + k, err := func(item stackitem.Item) (string, error) { + b, err := item.TryBytes() + if err != nil { + return "", err + } + if !utf8.Valid(b) { + return "", errors.New("not a UTF-8 string") + } + return string(b), nil + }(m[i].Key) + if err != nil { + return nil, fmt.Errorf("key %d: %w", i, err) + } + v, err := func(item stackitem.Item) ([]util.Uint160, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([]util.Uint160, len(arr)) + for i := range res { + res[i], err = func(item stackitem.Item) (util.Uint160, error) { + b, err := item.TryBytes() + if err != nil { + return util.Uint160{}, err + } + u, err := util.Uint160DecodeBytesBE(b) + if err != nil { + return util.Uint160{}, err + } + return u, nil + }(arr[i]) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(m[i].Value) + if err != nil { + return nil, fmt.Errorf("value %d: %w", i, err) + } + res[k] = v + } + return res, nil + }(m[i].Value) + if err != nil { + return nil, fmt.Errorf("value %d: %w", i, err) + } + res[k] = v + } + return res, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field M: %w", err) + } + + return nil +} + +// SomeStructEventsFromApplicationLog retrieves a set of all emitted events +// with "SomeStruct" name from the provided [result.ApplicationLog]. +func SomeStructEventsFromApplicationLog(log *result.ApplicationLog) ([]*SomeStructEvent, error) { + if log == nil { + return nil, errors.New("nil application log") + } + + var res []*SomeStructEvent + for i, ex := range log.Executions { + for j, e := range ex.Events { + if e.Name != "SomeStruct" { + continue + } + event := new(SomeStructEvent) + err := event.FromStackItem(e.Item) + if err != nil { + return nil, fmt.Errorf("failed to deserialize SomeStructEvent from stackitem (execution #%d, event #%d): %w", i, j, err) + } + res = append(res, event) + } + } + + return res, nil +} + +// FromStackItem converts provided [stackitem.Array] to SomeStructEvent or +// returns an error if it's not possible to do to so. +func (e *SomeStructEvent) FromStackItem(item *stackitem.Array) error { + if item == nil { + return errors.New("nil item") + } + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 1 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + e.S, err = itemToCrazyStruct(arr[index], nil) + if err != nil { + return fmt.Errorf("field S: %w", err) + } + + return nil +} + +// SomeArrayEventsFromApplicationLog retrieves a set of all emitted events +// with "SomeArray" name from the provided [result.ApplicationLog]. +func SomeArrayEventsFromApplicationLog(log *result.ApplicationLog) ([]*SomeArrayEvent, error) { + if log == nil { + return nil, errors.New("nil application log") + } + + var res []*SomeArrayEvent + for i, ex := range log.Executions { + for j, e := range ex.Events { + if e.Name != "SomeArray" { + continue + } + event := new(SomeArrayEvent) + err := event.FromStackItem(e.Item) + if err != nil { + return nil, fmt.Errorf("failed to deserialize SomeArrayEvent from stackitem (execution #%d, event #%d): %w", i, j, err) + } + res = append(res, event) + } + } + + return res, nil +} + +// FromStackItem converts provided [stackitem.Array] to SomeArrayEvent or +// returns an error if it's not possible to do to so. +func (e *SomeArrayEvent) FromStackItem(item *stackitem.Array) error { + if item == nil { + return errors.New("nil item") + } + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 1 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + e.A, err = func(item stackitem.Item) ([][]*big.Int, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([][]*big.Int, len(arr)) + for i := range res { + res[i], err = func(item stackitem.Item) ([]*big.Int, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([]*big.Int, len(arr)) + for i := range res { + res[i], err = arr[i].TryInteger() + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(arr[i]) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field A: %w", err) + } + + return nil +} + +// SomeUnexportedFieldEventsFromApplicationLog retrieves a set of all emitted events +// with "SomeUnexportedField" name from the provided [result.ApplicationLog]. +func SomeUnexportedFieldEventsFromApplicationLog(log *result.ApplicationLog) ([]*SomeUnexportedFieldEvent, error) { + if log == nil { + return nil, errors.New("nil application log") + } + + var res []*SomeUnexportedFieldEvent + for i, ex := range log.Executions { + for j, e := range ex.Events { + if e.Name != "SomeUnexportedField" { + continue + } + event := new(SomeUnexportedFieldEvent) + err := event.FromStackItem(e.Item) + if err != nil { + return nil, fmt.Errorf("failed to deserialize SomeUnexportedFieldEvent from stackitem (execution #%d, event #%d): %w", i, j, err) + } + res = append(res, event) + } + } + + return res, nil +} + +// FromStackItem converts provided [stackitem.Array] to SomeUnexportedFieldEvent or +// returns an error if it's not possible to do to so. +func (e *SomeUnexportedFieldEvent) FromStackItem(item *stackitem.Array) error { + if item == nil { + return errors.New("nil item") + } + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 1 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + e.S, err = itemToSimpleStruct(arr[index], nil) + if err != nil { + return fmt.Errorf("field S: %w", err) + } + + return nil +} diff --git a/cli/smartcontract/rpcbindings/notifications/rpcbindings/guessed/rpcbindings_test.go b/cli/smartcontract/rpcbindings/notifications/rpcbindings/guessed/rpcbindings_test.go index c15e730..78675a7 100644 --- a/cli/smartcontract/rpcbindings/notifications/rpcbindings/guessed/rpcbindings_test.go +++ b/cli/smartcontract/rpcbindings/notifications/rpcbindings/guessed/rpcbindings_test.go @@ -1,759 +1,759 @@ -// Code generated by neo-go contract generate-rpcwrapper --manifest --out [--hash ] [--config ]; DO NOT EDIT. - -// Package structs contains RPC wrappers for Notifications contract. -package structs - -import ( - "errors" - "fmt" - "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" - "github.com/tutus-one/tutus-chain/pkg/smartcontract" - "github.com/tutus-one/tutus-chain/pkg/util" - "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" - "math/big" - "unicode/utf8" -) - -// Hash contains contract hash. -var Hash = util.Uint160{0x33, 0x22, 0x11, 0x0, 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x0} - -// Unnamed is a contract-specific unnamed type used by its methods. -type Unnamed struct { - I *big.Int - B bool -} - -// UnnamedX is a contract-specific unnamedX type used by its methods. -type UnnamedX struct { - I *big.Int -} - -// ComplicatedNameEvent represents "! complicated name %$#" event emitted by the contract. -type ComplicatedNameEvent struct { - ComplicatedParam string -} - -// SomeMapEvent represents "SomeMap" event emitted by the contract. -type SomeMapEvent struct { - M map[*big.Int][]map[string][]util.Uint160 -} - -// SomeStructEvent represents "SomeStruct" event emitted by the contract. -type SomeStructEvent struct { - S *Unnamed -} - -// SomeArrayEvent represents "SomeArray" event emitted by the contract. -type SomeArrayEvent struct { - A [][]*big.Int -} - -// SomeUnexportedFieldEvent represents "SomeUnexportedField" event emitted by the contract. -type SomeUnexportedFieldEvent struct { - S *UnnamedX -} - -// Actor is used by Contract to call state-changing methods. -type Actor interface { - MakeCall(contract util.Uint160, method string, params ...any) (*transaction.Transaction, error) - MakeRun(script []byte) (*transaction.Transaction, error) - MakeUnsignedCall(contract util.Uint160, method string, attrs []transaction.Attribute, params ...any) (*transaction.Transaction, error) - MakeUnsignedRun(script []byte, attrs []transaction.Attribute) (*transaction.Transaction, error) - SendCall(contract util.Uint160, method string, params ...any) (util.Uint256, uint32, error) - SendRun(script []byte) (util.Uint256, uint32, error) -} - -// Contract implements all contract methods. -type Contract struct { - actor Actor - hash util.Uint160 -} - -// New creates an instance of Contract using Hash and the given Actor. -func New(actor Actor) *Contract { - var hash = Hash - return &Contract{actor, hash} -} - -// Array creates a transaction invoking `array` method of the contract. -// This transaction is signed and immediately sent to the network. -// The values returned are its hash, ValidUntilBlock value and error if any. -func (c *Contract) Array() (util.Uint256, uint32, error) { - return c.actor.SendCall(c.hash, "array") -} - -// ArrayTransaction creates a transaction invoking `array` method of the contract. -// This transaction is signed, but not sent to the network, instead it's -// returned to the caller. -func (c *Contract) ArrayTransaction() (*transaction.Transaction, error) { - return c.actor.MakeCall(c.hash, "array") -} - -// ArrayUnsigned creates a transaction invoking `array` method of the contract. -// This transaction is not signed, it's simply returned to the caller. -// Any fields of it that do not affect fees can be changed (ValidUntilBlock, -// Nonce), fee values (NetworkFee, SystemFee) can be increased as well. -func (c *Contract) ArrayUnsigned() (*transaction.Transaction, error) { - return c.actor.MakeUnsignedCall(c.hash, "array", nil) -} - -// CrazyMap creates a transaction invoking `crazyMap` method of the contract. -// This transaction is signed and immediately sent to the network. -// The values returned are its hash, ValidUntilBlock value and error if any. -func (c *Contract) CrazyMap() (util.Uint256, uint32, error) { - return c.actor.SendCall(c.hash, "crazyMap") -} - -// CrazyMapTransaction creates a transaction invoking `crazyMap` method of the contract. -// This transaction is signed, but not sent to the network, instead it's -// returned to the caller. -func (c *Contract) CrazyMapTransaction() (*transaction.Transaction, error) { - return c.actor.MakeCall(c.hash, "crazyMap") -} - -// CrazyMapUnsigned creates a transaction invoking `crazyMap` method of the contract. -// This transaction is not signed, it's simply returned to the caller. -// Any fields of it that do not affect fees can be changed (ValidUntilBlock, -// Nonce), fee values (NetworkFee, SystemFee) can be increased as well. -func (c *Contract) CrazyMapUnsigned() (*transaction.Transaction, error) { - return c.actor.MakeUnsignedCall(c.hash, "crazyMap", nil) -} - -// Main creates a transaction invoking `main` method of the contract. -// This transaction is signed and immediately sent to the network. -// The values returned are its hash, ValidUntilBlock value and error if any. -func (c *Contract) Main() (util.Uint256, uint32, error) { - return c.actor.SendCall(c.hash, "main") -} - -// MainTransaction creates a transaction invoking `main` method of the contract. -// This transaction is signed, but not sent to the network, instead it's -// returned to the caller. -func (c *Contract) MainTransaction() (*transaction.Transaction, error) { - return c.actor.MakeCall(c.hash, "main") -} - -// MainUnsigned creates a transaction invoking `main` method of the contract. -// This transaction is not signed, it's simply returned to the caller. -// Any fields of it that do not affect fees can be changed (ValidUntilBlock, -// Nonce), fee values (NetworkFee, SystemFee) can be increased as well. -func (c *Contract) MainUnsigned() (*transaction.Transaction, error) { - return c.actor.MakeUnsignedCall(c.hash, "main", nil) -} - -// Struct creates a transaction invoking `struct` method of the contract. -// This transaction is signed and immediately sent to the network. -// The values returned are its hash, ValidUntilBlock value and error if any. -func (c *Contract) Struct() (util.Uint256, uint32, error) { - return c.actor.SendCall(c.hash, "struct") -} - -// StructTransaction creates a transaction invoking `struct` method of the contract. -// This transaction is signed, but not sent to the network, instead it's -// returned to the caller. -func (c *Contract) StructTransaction() (*transaction.Transaction, error) { - return c.actor.MakeCall(c.hash, "struct") -} - -// StructUnsigned creates a transaction invoking `struct` method of the contract. -// This transaction is not signed, it's simply returned to the caller. -// Any fields of it that do not affect fees can be changed (ValidUntilBlock, -// Nonce), fee values (NetworkFee, SystemFee) can be increased as well. -func (c *Contract) StructUnsigned() (*transaction.Transaction, error) { - return c.actor.MakeUnsignedCall(c.hash, "struct", nil) -} - -// UnexportedField creates a transaction invoking `unexportedField` method of the contract. -// This transaction is signed and immediately sent to the network. -// The values returned are its hash, ValidUntilBlock value and error if any. -func (c *Contract) UnexportedField() (util.Uint256, uint32, error) { - return c.actor.SendCall(c.hash, "unexportedField") -} - -// UnexportedFieldTransaction creates a transaction invoking `unexportedField` method of the contract. -// This transaction is signed, but not sent to the network, instead it's -// returned to the caller. -func (c *Contract) UnexportedFieldTransaction() (*transaction.Transaction, error) { - return c.actor.MakeCall(c.hash, "unexportedField") -} - -// UnexportedFieldUnsigned creates a transaction invoking `unexportedField` method of the contract. -// This transaction is not signed, it's simply returned to the caller. -// Any fields of it that do not affect fees can be changed (ValidUntilBlock, -// Nonce), fee values (NetworkFee, SystemFee) can be increased as well. -func (c *Contract) UnexportedFieldUnsigned() (*transaction.Transaction, error) { - return c.actor.MakeUnsignedCall(c.hash, "unexportedField", nil) -} - -// itemToUnnamed converts stack item into *Unnamed. -// NULL item is returned as nil pointer without error. -func itemToUnnamed(item stackitem.Item, err error) (*Unnamed, error) { - if err != nil { - return nil, err - } - _, null := item.(stackitem.Null) - if null { - return nil, nil - } - var res = new(Unnamed) - err = res.FromStackItem(item) - return res, err -} - -// Ensure *Unnamed is a proper [stackitem.Convertible]. -var _ = stackitem.Convertible(&Unnamed{}) - -// Ensure *Unnamed is a proper [smartcontract.Convertible]. -var _ = smartcontract.Convertible(&Unnamed{}) - -// FromStackItem retrieves fields of Unnamed from the given -// [stackitem.Item] or returns an error if it's not possible to do to so. -// It implements [stackitem.Convertible] interface. -func (res *Unnamed) FromStackItem(item stackitem.Item) error { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 2 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - res.I, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field I: %w", err) - } - - index++ - res.B, err = arr[index].TryBool() - if err != nil { - return fmt.Errorf("field B: %w", err) - } - - return nil -} - -// ToStackItem creates [stackitem.Item] representing Unnamed. -// It implements [stackitem.Convertible] interface. -func (res *Unnamed) ToStackItem() (stackitem.Item, error) { - if res == nil { - return stackitem.Null{}, nil - } - - var ( - err error - itm stackitem.Item - items = make([]stackitem.Item, 0, 2) - ) - itm, err = (*stackitem.BigInteger)(res.I), error(nil) - if err != nil { - return nil, fmt.Errorf("field I: %w", err) - } - items = append(items, itm) - - itm, err = stackitem.NewBool(res.B), error(nil) - if err != nil { - return nil, fmt.Errorf("field B: %w", err) - } - items = append(items, itm) - - return stackitem.NewStruct(items), nil -} - -// ToSCParameter creates [smartcontract.Parameter] representing Unnamed. -// It implements [smartcontract.Convertible] interface so that Unnamed -// could be used with invokers. -func (res *Unnamed) ToSCParameter() (smartcontract.Parameter, error) { - if res == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var ( - err error - prm smartcontract.Parameter - prms = make([]smartcontract.Parameter, 0, 2) - ) - prm, err = smartcontract.NewParameterFromValue(res.I) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field I: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.B) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field B: %w", err) - } - prms = append(prms, prm) - - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil -} - -// itemToUnnamedX converts stack item into *UnnamedX. -// NULL item is returned as nil pointer without error. -func itemToUnnamedX(item stackitem.Item, err error) (*UnnamedX, error) { - if err != nil { - return nil, err - } - _, null := item.(stackitem.Null) - if null { - return nil, nil - } - var res = new(UnnamedX) - err = res.FromStackItem(item) - return res, err -} - -// Ensure *UnnamedX is a proper [stackitem.Convertible]. -var _ = stackitem.Convertible(&UnnamedX{}) - -// Ensure *UnnamedX is a proper [smartcontract.Convertible]. -var _ = smartcontract.Convertible(&UnnamedX{}) - -// FromStackItem retrieves fields of UnnamedX from the given -// [stackitem.Item] or returns an error if it's not possible to do to so. -// It implements [stackitem.Convertible] interface. -func (res *UnnamedX) FromStackItem(item stackitem.Item) error { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 1 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - res.I, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field I: %w", err) - } - - return nil -} - -// ToStackItem creates [stackitem.Item] representing UnnamedX. -// It implements [stackitem.Convertible] interface. -func (res *UnnamedX) ToStackItem() (stackitem.Item, error) { - if res == nil { - return stackitem.Null{}, nil - } - - var ( - err error - itm stackitem.Item - items = make([]stackitem.Item, 0, 1) - ) - itm, err = (*stackitem.BigInteger)(res.I), error(nil) - if err != nil { - return nil, fmt.Errorf("field I: %w", err) - } - items = append(items, itm) - - return stackitem.NewStruct(items), nil -} - -// ToSCParameter creates [smartcontract.Parameter] representing UnnamedX. -// It implements [smartcontract.Convertible] interface so that UnnamedX -// could be used with invokers. -func (res *UnnamedX) ToSCParameter() (smartcontract.Parameter, error) { - if res == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var ( - err error - prm smartcontract.Parameter - prms = make([]smartcontract.Parameter, 0, 1) - ) - prm, err = smartcontract.NewParameterFromValue(res.I) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field I: %w", err) - } - prms = append(prms, prm) - - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil -} - -// ComplicatedNameEventsFromApplicationLog retrieves a set of all emitted events -// with "! complicated name %$#" name from the provided [result.ApplicationLog]. -func ComplicatedNameEventsFromApplicationLog(log *result.ApplicationLog) ([]*ComplicatedNameEvent, error) { - if log == nil { - return nil, errors.New("nil application log") - } - - var res []*ComplicatedNameEvent - for i, ex := range log.Executions { - for j, e := range ex.Events { - if e.Name != "! complicated name %$#" { - continue - } - event := new(ComplicatedNameEvent) - err := event.FromStackItem(e.Item) - if err != nil { - return nil, fmt.Errorf("failed to deserialize ComplicatedNameEvent from stackitem (execution #%d, event #%d): %w", i, j, err) - } - res = append(res, event) - } - } - - return res, nil -} - -// FromStackItem converts provided [stackitem.Array] to ComplicatedNameEvent or -// returns an error if it's not possible to do to so. -func (e *ComplicatedNameEvent) FromStackItem(item *stackitem.Array) error { - if item == nil { - return errors.New("nil item") - } - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 1 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - e.ComplicatedParam, err = func(item stackitem.Item) (string, error) { - b, err := item.TryBytes() - if err != nil { - return "", err - } - if !utf8.Valid(b) { - return "", errors.New("not a UTF-8 string") - } - return string(b), nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field ComplicatedParam: %w", err) - } - - return nil -} - -// SomeMapEventsFromApplicationLog retrieves a set of all emitted events -// with "SomeMap" name from the provided [result.ApplicationLog]. -func SomeMapEventsFromApplicationLog(log *result.ApplicationLog) ([]*SomeMapEvent, error) { - if log == nil { - return nil, errors.New("nil application log") - } - - var res []*SomeMapEvent - for i, ex := range log.Executions { - for j, e := range ex.Events { - if e.Name != "SomeMap" { - continue - } - event := new(SomeMapEvent) - err := event.FromStackItem(e.Item) - if err != nil { - return nil, fmt.Errorf("failed to deserialize SomeMapEvent from stackitem (execution #%d, event #%d): %w", i, j, err) - } - res = append(res, event) - } - } - - return res, nil -} - -// FromStackItem converts provided [stackitem.Array] to SomeMapEvent or -// returns an error if it's not possible to do to so. -func (e *SomeMapEvent) FromStackItem(item *stackitem.Array) error { - if item == nil { - return errors.New("nil item") - } - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 1 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - e.M, err = func(item stackitem.Item) (map[*big.Int][]map[string][]util.Uint160, error) { - m, ok := item.Value().([]stackitem.MapElement) - if !ok { - return nil, fmt.Errorf("%s is not a map", item.Type().String()) - } - res := make(map[*big.Int][]map[string][]util.Uint160) - for i := range m { - k, err := m[i].Key.TryInteger() - if err != nil { - return nil, fmt.Errorf("key %d: %w", i, err) - } - v, err := func(item stackitem.Item) ([]map[string][]util.Uint160, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([]map[string][]util.Uint160, len(arr)) - for i := range res { - res[i], err = func(item stackitem.Item) (map[string][]util.Uint160, error) { - m, ok := item.Value().([]stackitem.MapElement) - if !ok { - return nil, fmt.Errorf("%s is not a map", item.Type().String()) - } - res := make(map[string][]util.Uint160) - for i := range m { - k, err := func(item stackitem.Item) (string, error) { - b, err := item.TryBytes() - if err != nil { - return "", err - } - if !utf8.Valid(b) { - return "", errors.New("not a UTF-8 string") - } - return string(b), nil - }(m[i].Key) - if err != nil { - return nil, fmt.Errorf("key %d: %w", i, err) - } - v, err := func(item stackitem.Item) ([]util.Uint160, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([]util.Uint160, len(arr)) - for i := range res { - res[i], err = func(item stackitem.Item) (util.Uint160, error) { - b, err := item.TryBytes() - if err != nil { - return util.Uint160{}, err - } - u, err := util.Uint160DecodeBytesBE(b) - if err != nil { - return util.Uint160{}, err - } - return u, nil - }(arr[i]) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(m[i].Value) - if err != nil { - return nil, fmt.Errorf("value %d: %w", i, err) - } - res[k] = v - } - return res, nil - }(arr[i]) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(m[i].Value) - if err != nil { - return nil, fmt.Errorf("value %d: %w", i, err) - } - res[k] = v - } - return res, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field M: %w", err) - } - - return nil -} - -// SomeStructEventsFromApplicationLog retrieves a set of all emitted events -// with "SomeStruct" name from the provided [result.ApplicationLog]. -func SomeStructEventsFromApplicationLog(log *result.ApplicationLog) ([]*SomeStructEvent, error) { - if log == nil { - return nil, errors.New("nil application log") - } - - var res []*SomeStructEvent - for i, ex := range log.Executions { - for j, e := range ex.Events { - if e.Name != "SomeStruct" { - continue - } - event := new(SomeStructEvent) - err := event.FromStackItem(e.Item) - if err != nil { - return nil, fmt.Errorf("failed to deserialize SomeStructEvent from stackitem (execution #%d, event #%d): %w", i, j, err) - } - res = append(res, event) - } - } - - return res, nil -} - -// FromStackItem converts provided [stackitem.Array] to SomeStructEvent or -// returns an error if it's not possible to do to so. -func (e *SomeStructEvent) FromStackItem(item *stackitem.Array) error { - if item == nil { - return errors.New("nil item") - } - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 1 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - e.S, err = itemToUnnamed(arr[index], nil) - if err != nil { - return fmt.Errorf("field S: %w", err) - } - - return nil -} - -// SomeArrayEventsFromApplicationLog retrieves a set of all emitted events -// with "SomeArray" name from the provided [result.ApplicationLog]. -func SomeArrayEventsFromApplicationLog(log *result.ApplicationLog) ([]*SomeArrayEvent, error) { - if log == nil { - return nil, errors.New("nil application log") - } - - var res []*SomeArrayEvent - for i, ex := range log.Executions { - for j, e := range ex.Events { - if e.Name != "SomeArray" { - continue - } - event := new(SomeArrayEvent) - err := event.FromStackItem(e.Item) - if err != nil { - return nil, fmt.Errorf("failed to deserialize SomeArrayEvent from stackitem (execution #%d, event #%d): %w", i, j, err) - } - res = append(res, event) - } - } - - return res, nil -} - -// FromStackItem converts provided [stackitem.Array] to SomeArrayEvent or -// returns an error if it's not possible to do to so. -func (e *SomeArrayEvent) FromStackItem(item *stackitem.Array) error { - if item == nil { - return errors.New("nil item") - } - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 1 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - e.A, err = func(item stackitem.Item) ([][]*big.Int, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([][]*big.Int, len(arr)) - for i := range res { - res[i], err = func(item stackitem.Item) ([]*big.Int, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([]*big.Int, len(arr)) - for i := range res { - res[i], err = arr[i].TryInteger() - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(arr[i]) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field A: %w", err) - } - - return nil -} - -// SomeUnexportedFieldEventsFromApplicationLog retrieves a set of all emitted events -// with "SomeUnexportedField" name from the provided [result.ApplicationLog]. -func SomeUnexportedFieldEventsFromApplicationLog(log *result.ApplicationLog) ([]*SomeUnexportedFieldEvent, error) { - if log == nil { - return nil, errors.New("nil application log") - } - - var res []*SomeUnexportedFieldEvent - for i, ex := range log.Executions { - for j, e := range ex.Events { - if e.Name != "SomeUnexportedField" { - continue - } - event := new(SomeUnexportedFieldEvent) - err := event.FromStackItem(e.Item) - if err != nil { - return nil, fmt.Errorf("failed to deserialize SomeUnexportedFieldEvent from stackitem (execution #%d, event #%d): %w", i, j, err) - } - res = append(res, event) - } - } - - return res, nil -} - -// FromStackItem converts provided [stackitem.Array] to SomeUnexportedFieldEvent or -// returns an error if it's not possible to do to so. -func (e *SomeUnexportedFieldEvent) FromStackItem(item *stackitem.Array) error { - if item == nil { - return errors.New("nil item") - } - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 1 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - e.S, err = itemToUnnamedX(arr[index], nil) - if err != nil { - return fmt.Errorf("field S: %w", err) - } - - return nil -} +// Code generated by neo-go contract generate-rpcwrapper --manifest --out [--hash ] [--config ]; DO NOT EDIT. + +// Package structs contains RPC wrappers for Notifications contract. +package structs + +import ( + "errors" + "fmt" + "github.com/tutus-one/tutus-chain/pkg/core/transaction" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" + "github.com/tutus-one/tutus-chain/pkg/smartcontract" + "github.com/tutus-one/tutus-chain/pkg/util" + "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" + "math/big" + "unicode/utf8" +) + +// Hash contains contract hash. +var Hash = util.Uint160{0x33, 0x22, 0x11, 0x0, 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x0} + +// Unnamed is a contract-specific unnamed type used by its methods. +type Unnamed struct { + I *big.Int + B bool +} + +// UnnamedX is a contract-specific unnamedX type used by its methods. +type UnnamedX struct { + I *big.Int +} + +// ComplicatedNameEvent represents "! complicated name %$#" event emitted by the contract. +type ComplicatedNameEvent struct { + ComplicatedParam string +} + +// SomeMapEvent represents "SomeMap" event emitted by the contract. +type SomeMapEvent struct { + M map[*big.Int][]map[string][]util.Uint160 +} + +// SomeStructEvent represents "SomeStruct" event emitted by the contract. +type SomeStructEvent struct { + S *Unnamed +} + +// SomeArrayEvent represents "SomeArray" event emitted by the contract. +type SomeArrayEvent struct { + A [][]*big.Int +} + +// SomeUnexportedFieldEvent represents "SomeUnexportedField" event emitted by the contract. +type SomeUnexportedFieldEvent struct { + S *UnnamedX +} + +// Actor is used by Contract to call state-changing methods. +type Actor interface { + MakeCall(contract util.Uint160, method string, params ...any) (*transaction.Transaction, error) + MakeRun(script []byte) (*transaction.Transaction, error) + MakeUnsignedCall(contract util.Uint160, method string, attrs []transaction.Attribute, params ...any) (*transaction.Transaction, error) + MakeUnsignedRun(script []byte, attrs []transaction.Attribute) (*transaction.Transaction, error) + SendCall(contract util.Uint160, method string, params ...any) (util.Uint256, uint32, error) + SendRun(script []byte) (util.Uint256, uint32, error) +} + +// Contract implements all contract methods. +type Contract struct { + actor Actor + hash util.Uint160 +} + +// New creates an instance of Contract using Hash and the given Actor. +func New(actor Actor) *Contract { + var hash = Hash + return &Contract{actor, hash} +} + +// Array creates a transaction invoking `array` method of the contract. +// This transaction is signed and immediately sent to the network. +// The values returned are its hash, ValidUntilBlock value and error if any. +func (c *Contract) Array() (util.Uint256, uint32, error) { + return c.actor.SendCall(c.hash, "array") +} + +// ArrayTransaction creates a transaction invoking `array` method of the contract. +// This transaction is signed, but not sent to the network, instead it's +// returned to the caller. +func (c *Contract) ArrayTransaction() (*transaction.Transaction, error) { + return c.actor.MakeCall(c.hash, "array") +} + +// ArrayUnsigned creates a transaction invoking `array` method of the contract. +// This transaction is not signed, it's simply returned to the caller. +// Any fields of it that do not affect fees can be changed (ValidUntilBlock, +// Nonce), fee values (NetworkFee, SystemFee) can be increased as well. +func (c *Contract) ArrayUnsigned() (*transaction.Transaction, error) { + return c.actor.MakeUnsignedCall(c.hash, "array", nil) +} + +// CrazyMap creates a transaction invoking `crazyMap` method of the contract. +// This transaction is signed and immediately sent to the network. +// The values returned are its hash, ValidUntilBlock value and error if any. +func (c *Contract) CrazyMap() (util.Uint256, uint32, error) { + return c.actor.SendCall(c.hash, "crazyMap") +} + +// CrazyMapTransaction creates a transaction invoking `crazyMap` method of the contract. +// This transaction is signed, but not sent to the network, instead it's +// returned to the caller. +func (c *Contract) CrazyMapTransaction() (*transaction.Transaction, error) { + return c.actor.MakeCall(c.hash, "crazyMap") +} + +// CrazyMapUnsigned creates a transaction invoking `crazyMap` method of the contract. +// This transaction is not signed, it's simply returned to the caller. +// Any fields of it that do not affect fees can be changed (ValidUntilBlock, +// Nonce), fee values (NetworkFee, SystemFee) can be increased as well. +func (c *Contract) CrazyMapUnsigned() (*transaction.Transaction, error) { + return c.actor.MakeUnsignedCall(c.hash, "crazyMap", nil) +} + +// Main creates a transaction invoking `main` method of the contract. +// This transaction is signed and immediately sent to the network. +// The values returned are its hash, ValidUntilBlock value and error if any. +func (c *Contract) Main() (util.Uint256, uint32, error) { + return c.actor.SendCall(c.hash, "main") +} + +// MainTransaction creates a transaction invoking `main` method of the contract. +// This transaction is signed, but not sent to the network, instead it's +// returned to the caller. +func (c *Contract) MainTransaction() (*transaction.Transaction, error) { + return c.actor.MakeCall(c.hash, "main") +} + +// MainUnsigned creates a transaction invoking `main` method of the contract. +// This transaction is not signed, it's simply returned to the caller. +// Any fields of it that do not affect fees can be changed (ValidUntilBlock, +// Nonce), fee values (NetworkFee, SystemFee) can be increased as well. +func (c *Contract) MainUnsigned() (*transaction.Transaction, error) { + return c.actor.MakeUnsignedCall(c.hash, "main", nil) +} + +// Struct creates a transaction invoking `struct` method of the contract. +// This transaction is signed and immediately sent to the network. +// The values returned are its hash, ValidUntilBlock value and error if any. +func (c *Contract) Struct() (util.Uint256, uint32, error) { + return c.actor.SendCall(c.hash, "struct") +} + +// StructTransaction creates a transaction invoking `struct` method of the contract. +// This transaction is signed, but not sent to the network, instead it's +// returned to the caller. +func (c *Contract) StructTransaction() (*transaction.Transaction, error) { + return c.actor.MakeCall(c.hash, "struct") +} + +// StructUnsigned creates a transaction invoking `struct` method of the contract. +// This transaction is not signed, it's simply returned to the caller. +// Any fields of it that do not affect fees can be changed (ValidUntilBlock, +// Nonce), fee values (NetworkFee, SystemFee) can be increased as well. +func (c *Contract) StructUnsigned() (*transaction.Transaction, error) { + return c.actor.MakeUnsignedCall(c.hash, "struct", nil) +} + +// UnexportedField creates a transaction invoking `unexportedField` method of the contract. +// This transaction is signed and immediately sent to the network. +// The values returned are its hash, ValidUntilBlock value and error if any. +func (c *Contract) UnexportedField() (util.Uint256, uint32, error) { + return c.actor.SendCall(c.hash, "unexportedField") +} + +// UnexportedFieldTransaction creates a transaction invoking `unexportedField` method of the contract. +// This transaction is signed, but not sent to the network, instead it's +// returned to the caller. +func (c *Contract) UnexportedFieldTransaction() (*transaction.Transaction, error) { + return c.actor.MakeCall(c.hash, "unexportedField") +} + +// UnexportedFieldUnsigned creates a transaction invoking `unexportedField` method of the contract. +// This transaction is not signed, it's simply returned to the caller. +// Any fields of it that do not affect fees can be changed (ValidUntilBlock, +// Nonce), fee values (NetworkFee, SystemFee) can be increased as well. +func (c *Contract) UnexportedFieldUnsigned() (*transaction.Transaction, error) { + return c.actor.MakeUnsignedCall(c.hash, "unexportedField", nil) +} + +// itemToUnnamed converts stack item into *Unnamed. +// NULL item is returned as nil pointer without error. +func itemToUnnamed(item stackitem.Item, err error) (*Unnamed, error) { + if err != nil { + return nil, err + } + _, null := item.(stackitem.Null) + if null { + return nil, nil + } + var res = new(Unnamed) + err = res.FromStackItem(item) + return res, err +} + +// Ensure *Unnamed is a proper [stackitem.Convertible]. +var _ = stackitem.Convertible(&Unnamed{}) + +// Ensure *Unnamed is a proper [smartcontract.Convertible]. +var _ = smartcontract.Convertible(&Unnamed{}) + +// FromStackItem retrieves fields of Unnamed from the given +// [stackitem.Item] or returns an error if it's not possible to do to so. +// It implements [stackitem.Convertible] interface. +func (res *Unnamed) FromStackItem(item stackitem.Item) error { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 2 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + res.I, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field I: %w", err) + } + + index++ + res.B, err = arr[index].TryBool() + if err != nil { + return fmt.Errorf("field B: %w", err) + } + + return nil +} + +// ToStackItem creates [stackitem.Item] representing Unnamed. +// It implements [stackitem.Convertible] interface. +func (res *Unnamed) ToStackItem() (stackitem.Item, error) { + if res == nil { + return stackitem.Null{}, nil + } + + var ( + err error + itm stackitem.Item + items = make([]stackitem.Item, 0, 2) + ) + itm, err = (*stackitem.BigInteger)(res.I), error(nil) + if err != nil { + return nil, fmt.Errorf("field I: %w", err) + } + items = append(items, itm) + + itm, err = stackitem.NewBool(res.B), error(nil) + if err != nil { + return nil, fmt.Errorf("field B: %w", err) + } + items = append(items, itm) + + return stackitem.NewStruct(items), nil +} + +// ToSCParameter creates [smartcontract.Parameter] representing Unnamed. +// It implements [smartcontract.Convertible] interface so that Unnamed +// could be used with invokers. +func (res *Unnamed) ToSCParameter() (smartcontract.Parameter, error) { + if res == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var ( + err error + prm smartcontract.Parameter + prms = make([]smartcontract.Parameter, 0, 2) + ) + prm, err = smartcontract.NewParameterFromValue(res.I) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field I: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.B) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field B: %w", err) + } + prms = append(prms, prm) + + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil +} + +// itemToUnnamedX converts stack item into *UnnamedX. +// NULL item is returned as nil pointer without error. +func itemToUnnamedX(item stackitem.Item, err error) (*UnnamedX, error) { + if err != nil { + return nil, err + } + _, null := item.(stackitem.Null) + if null { + return nil, nil + } + var res = new(UnnamedX) + err = res.FromStackItem(item) + return res, err +} + +// Ensure *UnnamedX is a proper [stackitem.Convertible]. +var _ = stackitem.Convertible(&UnnamedX{}) + +// Ensure *UnnamedX is a proper [smartcontract.Convertible]. +var _ = smartcontract.Convertible(&UnnamedX{}) + +// FromStackItem retrieves fields of UnnamedX from the given +// [stackitem.Item] or returns an error if it's not possible to do to so. +// It implements [stackitem.Convertible] interface. +func (res *UnnamedX) FromStackItem(item stackitem.Item) error { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 1 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + res.I, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field I: %w", err) + } + + return nil +} + +// ToStackItem creates [stackitem.Item] representing UnnamedX. +// It implements [stackitem.Convertible] interface. +func (res *UnnamedX) ToStackItem() (stackitem.Item, error) { + if res == nil { + return stackitem.Null{}, nil + } + + var ( + err error + itm stackitem.Item + items = make([]stackitem.Item, 0, 1) + ) + itm, err = (*stackitem.BigInteger)(res.I), error(nil) + if err != nil { + return nil, fmt.Errorf("field I: %w", err) + } + items = append(items, itm) + + return stackitem.NewStruct(items), nil +} + +// ToSCParameter creates [smartcontract.Parameter] representing UnnamedX. +// It implements [smartcontract.Convertible] interface so that UnnamedX +// could be used with invokers. +func (res *UnnamedX) ToSCParameter() (smartcontract.Parameter, error) { + if res == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var ( + err error + prm smartcontract.Parameter + prms = make([]smartcontract.Parameter, 0, 1) + ) + prm, err = smartcontract.NewParameterFromValue(res.I) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field I: %w", err) + } + prms = append(prms, prm) + + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil +} + +// ComplicatedNameEventsFromApplicationLog retrieves a set of all emitted events +// with "! complicated name %$#" name from the provided [result.ApplicationLog]. +func ComplicatedNameEventsFromApplicationLog(log *result.ApplicationLog) ([]*ComplicatedNameEvent, error) { + if log == nil { + return nil, errors.New("nil application log") + } + + var res []*ComplicatedNameEvent + for i, ex := range log.Executions { + for j, e := range ex.Events { + if e.Name != "! complicated name %$#" { + continue + } + event := new(ComplicatedNameEvent) + err := event.FromStackItem(e.Item) + if err != nil { + return nil, fmt.Errorf("failed to deserialize ComplicatedNameEvent from stackitem (execution #%d, event #%d): %w", i, j, err) + } + res = append(res, event) + } + } + + return res, nil +} + +// FromStackItem converts provided [stackitem.Array] to ComplicatedNameEvent or +// returns an error if it's not possible to do to so. +func (e *ComplicatedNameEvent) FromStackItem(item *stackitem.Array) error { + if item == nil { + return errors.New("nil item") + } + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 1 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + e.ComplicatedParam, err = func(item stackitem.Item) (string, error) { + b, err := item.TryBytes() + if err != nil { + return "", err + } + if !utf8.Valid(b) { + return "", errors.New("not a UTF-8 string") + } + return string(b), nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field ComplicatedParam: %w", err) + } + + return nil +} + +// SomeMapEventsFromApplicationLog retrieves a set of all emitted events +// with "SomeMap" name from the provided [result.ApplicationLog]. +func SomeMapEventsFromApplicationLog(log *result.ApplicationLog) ([]*SomeMapEvent, error) { + if log == nil { + return nil, errors.New("nil application log") + } + + var res []*SomeMapEvent + for i, ex := range log.Executions { + for j, e := range ex.Events { + if e.Name != "SomeMap" { + continue + } + event := new(SomeMapEvent) + err := event.FromStackItem(e.Item) + if err != nil { + return nil, fmt.Errorf("failed to deserialize SomeMapEvent from stackitem (execution #%d, event #%d): %w", i, j, err) + } + res = append(res, event) + } + } + + return res, nil +} + +// FromStackItem converts provided [stackitem.Array] to SomeMapEvent or +// returns an error if it's not possible to do to so. +func (e *SomeMapEvent) FromStackItem(item *stackitem.Array) error { + if item == nil { + return errors.New("nil item") + } + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 1 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + e.M, err = func(item stackitem.Item) (map[*big.Int][]map[string][]util.Uint160, error) { + m, ok := item.Value().([]stackitem.MapElement) + if !ok { + return nil, fmt.Errorf("%s is not a map", item.Type().String()) + } + res := make(map[*big.Int][]map[string][]util.Uint160) + for i := range m { + k, err := m[i].Key.TryInteger() + if err != nil { + return nil, fmt.Errorf("key %d: %w", i, err) + } + v, err := func(item stackitem.Item) ([]map[string][]util.Uint160, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([]map[string][]util.Uint160, len(arr)) + for i := range res { + res[i], err = func(item stackitem.Item) (map[string][]util.Uint160, error) { + m, ok := item.Value().([]stackitem.MapElement) + if !ok { + return nil, fmt.Errorf("%s is not a map", item.Type().String()) + } + res := make(map[string][]util.Uint160) + for i := range m { + k, err := func(item stackitem.Item) (string, error) { + b, err := item.TryBytes() + if err != nil { + return "", err + } + if !utf8.Valid(b) { + return "", errors.New("not a UTF-8 string") + } + return string(b), nil + }(m[i].Key) + if err != nil { + return nil, fmt.Errorf("key %d: %w", i, err) + } + v, err := func(item stackitem.Item) ([]util.Uint160, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([]util.Uint160, len(arr)) + for i := range res { + res[i], err = func(item stackitem.Item) (util.Uint160, error) { + b, err := item.TryBytes() + if err != nil { + return util.Uint160{}, err + } + u, err := util.Uint160DecodeBytesBE(b) + if err != nil { + return util.Uint160{}, err + } + return u, nil + }(arr[i]) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(m[i].Value) + if err != nil { + return nil, fmt.Errorf("value %d: %w", i, err) + } + res[k] = v + } + return res, nil + }(arr[i]) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(m[i].Value) + if err != nil { + return nil, fmt.Errorf("value %d: %w", i, err) + } + res[k] = v + } + return res, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field M: %w", err) + } + + return nil +} + +// SomeStructEventsFromApplicationLog retrieves a set of all emitted events +// with "SomeStruct" name from the provided [result.ApplicationLog]. +func SomeStructEventsFromApplicationLog(log *result.ApplicationLog) ([]*SomeStructEvent, error) { + if log == nil { + return nil, errors.New("nil application log") + } + + var res []*SomeStructEvent + for i, ex := range log.Executions { + for j, e := range ex.Events { + if e.Name != "SomeStruct" { + continue + } + event := new(SomeStructEvent) + err := event.FromStackItem(e.Item) + if err != nil { + return nil, fmt.Errorf("failed to deserialize SomeStructEvent from stackitem (execution #%d, event #%d): %w", i, j, err) + } + res = append(res, event) + } + } + + return res, nil +} + +// FromStackItem converts provided [stackitem.Array] to SomeStructEvent or +// returns an error if it's not possible to do to so. +func (e *SomeStructEvent) FromStackItem(item *stackitem.Array) error { + if item == nil { + return errors.New("nil item") + } + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 1 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + e.S, err = itemToUnnamed(arr[index], nil) + if err != nil { + return fmt.Errorf("field S: %w", err) + } + + return nil +} + +// SomeArrayEventsFromApplicationLog retrieves a set of all emitted events +// with "SomeArray" name from the provided [result.ApplicationLog]. +func SomeArrayEventsFromApplicationLog(log *result.ApplicationLog) ([]*SomeArrayEvent, error) { + if log == nil { + return nil, errors.New("nil application log") + } + + var res []*SomeArrayEvent + for i, ex := range log.Executions { + for j, e := range ex.Events { + if e.Name != "SomeArray" { + continue + } + event := new(SomeArrayEvent) + err := event.FromStackItem(e.Item) + if err != nil { + return nil, fmt.Errorf("failed to deserialize SomeArrayEvent from stackitem (execution #%d, event #%d): %w", i, j, err) + } + res = append(res, event) + } + } + + return res, nil +} + +// FromStackItem converts provided [stackitem.Array] to SomeArrayEvent or +// returns an error if it's not possible to do to so. +func (e *SomeArrayEvent) FromStackItem(item *stackitem.Array) error { + if item == nil { + return errors.New("nil item") + } + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 1 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + e.A, err = func(item stackitem.Item) ([][]*big.Int, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([][]*big.Int, len(arr)) + for i := range res { + res[i], err = func(item stackitem.Item) ([]*big.Int, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([]*big.Int, len(arr)) + for i := range res { + res[i], err = arr[i].TryInteger() + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(arr[i]) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field A: %w", err) + } + + return nil +} + +// SomeUnexportedFieldEventsFromApplicationLog retrieves a set of all emitted events +// with "SomeUnexportedField" name from the provided [result.ApplicationLog]. +func SomeUnexportedFieldEventsFromApplicationLog(log *result.ApplicationLog) ([]*SomeUnexportedFieldEvent, error) { + if log == nil { + return nil, errors.New("nil application log") + } + + var res []*SomeUnexportedFieldEvent + for i, ex := range log.Executions { + for j, e := range ex.Events { + if e.Name != "SomeUnexportedField" { + continue + } + event := new(SomeUnexportedFieldEvent) + err := event.FromStackItem(e.Item) + if err != nil { + return nil, fmt.Errorf("failed to deserialize SomeUnexportedFieldEvent from stackitem (execution #%d, event #%d): %w", i, j, err) + } + res = append(res, event) + } + } + + return res, nil +} + +// FromStackItem converts provided [stackitem.Array] to SomeUnexportedFieldEvent or +// returns an error if it's not possible to do to so. +func (e *SomeUnexportedFieldEvent) FromStackItem(item *stackitem.Array) error { + if item == nil { + return errors.New("nil item") + } + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 1 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + e.S, err = itemToUnnamedX(arr[index], nil) + if err != nil { + return fmt.Errorf("field S: %w", err) + } + + return nil +} diff --git a/cli/smartcontract/rpcbindings/notifications/rpcbindings/rpcbindings_test.go b/cli/smartcontract/rpcbindings/notifications/rpcbindings/rpcbindings_test.go index d838fc3..5eae3bb 100644 --- a/cli/smartcontract/rpcbindings/notifications/rpcbindings/rpcbindings_test.go +++ b/cli/smartcontract/rpcbindings/notifications/rpcbindings/rpcbindings_test.go @@ -7,7 +7,7 @@ import ( "errors" "fmt" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" "unicode/utf8" diff --git a/cli/smartcontract/rpcbindings/structs/rpcbindings/dynamic_hash/rpcbindings_test.go b/cli/smartcontract/rpcbindings/structs/rpcbindings/dynamic_hash/rpcbindings_test.go index 5d58b3d..e281bcf 100644 --- a/cli/smartcontract/rpcbindings/structs/rpcbindings/dynamic_hash/rpcbindings_test.go +++ b/cli/smartcontract/rpcbindings/structs/rpcbindings/dynamic_hash/rpcbindings_test.go @@ -1,2860 +1,2860 @@ -// Code generated by neo-go contract generate-rpcwrapper --manifest --out [--hash ] [--config ]; DO NOT EDIT. - -// Package structs contains RPC wrappers for Types contract. -package structs - -import ( - "crypto/elliptic" - "errors" - "fmt" - "github.com/tutus-one/tutus-chain/pkg/crypto/keys" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" - "github.com/tutus-one/tutus-chain/pkg/rpcclient/unwrap" - "github.com/tutus-one/tutus-chain/pkg/smartcontract" - "github.com/tutus-one/tutus-chain/pkg/util" - "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" - "math/big" - "unicode/utf8" -) - -// LedgerBlock is a contract-specific ledger.Block type used by its methods. -type LedgerBlock struct { - Hash util.Uint256 - Version *big.Int - PrevHash util.Uint256 - MerkleRoot util.Uint256 - Timestamp *big.Int - Nonce *big.Int - Index *big.Int - PrimaryIndex *big.Int - NextConsensus util.Uint160 - TransactionsLength *big.Int -} - -// LedgerTransaction is a contract-specific ledger.Transaction type used by its methods. -type LedgerTransaction struct { - Hash util.Uint256 - Version *big.Int - Nonce *big.Int - Sender util.Uint160 - SysFee *big.Int - NetFee *big.Int - ValidUntilBlock *big.Int - Script []byte -} - -// ManagementABI is a contract-specific management.ABI type used by its methods. -type ManagementABI struct { - Methods []*ManagementMethod - Events []*ManagementEvent -} - -// ManagementContract is a contract-specific management.Contract type used by its methods. -type ManagementContract struct { - ID *big.Int - UpdateCounter *big.Int - Hash util.Uint160 - NEF []byte - Manifest *ManagementManifest -} - -// ManagementEvent is a contract-specific management.Event type used by its methods. -type ManagementEvent struct { - Name string - Params []*ManagementParameter -} - -// ManagementGroup is a contract-specific management.Group type used by its methods. -type ManagementGroup struct { - PublicKey *keys.PublicKey - Signature []byte -} - -// ManagementManifest is a contract-specific management.Manifest type used by its methods. -type ManagementManifest struct { - Name string - Groups []*ManagementGroup - Features map[string]string - SupportedStandards []string - ABI *ManagementABI - Permissions []*ManagementPermission - Trusts []util.Uint160 - Extra any -} - -// ManagementMethod is a contract-specific management.Method type used by its methods. -type ManagementMethod struct { - Name string - Params []*ManagementParameter - ReturnType *big.Int - Offset *big.Int - Safe bool -} - -// ManagementParameter is a contract-specific management.Parameter type used by its methods. -type ManagementParameter struct { - Name string - Type *big.Int -} - -// ManagementPermission is a contract-specific management.Permission type used by its methods. -type ManagementPermission struct { - Contract util.Uint160 - Methods []string -} - -// StructsInternal is a contract-specific structs.Internal type used by its methods. -type StructsInternal struct { - Bool bool - Int *big.Int - Bytes []byte - String string - H160 util.Uint160 - H256 util.Uint256 - PK *keys.PublicKey - PubKey *keys.PublicKey - Sign []byte - ArrOfBytes [][]byte - ArrOfH160 []util.Uint160 - Map map[*big.Int]keys.PublicKeys - Struct *StructsInternal - UnexportedField *big.Int -} - -// Invoker is used by ContractReader to call various safe methods. -type Invoker interface { - Call(contract util.Uint160, operation string, params ...any) (*result.Invoke, error) -} - -// ContractReader implements safe contract methods. -type ContractReader struct { - invoker Invoker - hash util.Uint160 -} - -// NewReader creates an instance of ContractReader using provided contract hash and the given Invoker. -func NewReader(invoker Invoker, hash util.Uint160) *ContractReader { - return &ContractReader{invoker, hash} -} - -// Block invokes `block` method of contract. -func (c *ContractReader) Block(b *LedgerBlock) (*LedgerBlock, error) { - return itemToLedgerBlock(unwrap.Item(c.invoker.Call(c.hash, "block", b))) -} - -// Contract invokes `contract` method of contract. -func (c *ContractReader) Contract(mc *ManagementContract) (*ManagementContract, error) { - return itemToManagementContract(unwrap.Item(c.invoker.Call(c.hash, "contract", mc))) -} - -// Struct invokes `struct` method of contract. -func (c *ContractReader) Struct(s *StructsInternal) (*StructsInternal, error) { - return itemToStructsInternal(unwrap.Item(c.invoker.Call(c.hash, "struct", s))) -} - -// Transaction invokes `transaction` method of contract. -func (c *ContractReader) Transaction(t *LedgerTransaction) (*LedgerTransaction, error) { - return itemToLedgerTransaction(unwrap.Item(c.invoker.Call(c.hash, "transaction", t))) -} - -// itemToLedgerBlock converts stack item into *LedgerBlock. -// NULL item is returned as nil pointer without error. -func itemToLedgerBlock(item stackitem.Item, err error) (*LedgerBlock, error) { - if err != nil { - return nil, err - } - _, null := item.(stackitem.Null) - if null { - return nil, nil - } - var res = new(LedgerBlock) - err = res.FromStackItem(item) - return res, err -} - -// Ensure *LedgerBlock is a proper [stackitem.Convertible]. -var _ = stackitem.Convertible(&LedgerBlock{}) - -// Ensure *LedgerBlock is a proper [smartcontract.Convertible]. -var _ = smartcontract.Convertible(&LedgerBlock{}) - -// FromStackItem retrieves fields of LedgerBlock from the given -// [stackitem.Item] or returns an error if it's not possible to do to so. -// It implements [stackitem.Convertible] interface. -func (res *LedgerBlock) FromStackItem(item stackitem.Item) error { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 10 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - res.Hash, err = func(item stackitem.Item) (util.Uint256, error) { - b, err := item.TryBytes() - if err != nil { - return util.Uint256{}, err - } - u, err := util.Uint256DecodeBytesBE(b) - if err != nil { - return util.Uint256{}, err - } - return u, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field Hash: %w", err) - } - - index++ - res.Version, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field Version: %w", err) - } - - index++ - res.PrevHash, err = func(item stackitem.Item) (util.Uint256, error) { - b, err := item.TryBytes() - if err != nil { - return util.Uint256{}, err - } - u, err := util.Uint256DecodeBytesBE(b) - if err != nil { - return util.Uint256{}, err - } - return u, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field PrevHash: %w", err) - } - - index++ - res.MerkleRoot, err = func(item stackitem.Item) (util.Uint256, error) { - b, err := item.TryBytes() - if err != nil { - return util.Uint256{}, err - } - u, err := util.Uint256DecodeBytesBE(b) - if err != nil { - return util.Uint256{}, err - } - return u, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field MerkleRoot: %w", err) - } - - index++ - res.Timestamp, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field Timestamp: %w", err) - } - - index++ - res.Nonce, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field Nonce: %w", err) - } - - index++ - res.Index, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field Index: %w", err) - } - - index++ - res.PrimaryIndex, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field PrimaryIndex: %w", err) - } - - index++ - res.NextConsensus, err = func(item stackitem.Item) (util.Uint160, error) { - b, err := item.TryBytes() - if err != nil { - return util.Uint160{}, err - } - u, err := util.Uint160DecodeBytesBE(b) - if err != nil { - return util.Uint160{}, err - } - return u, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field NextConsensus: %w", err) - } - - index++ - res.TransactionsLength, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field TransactionsLength: %w", err) - } - - return nil -} - -// ToStackItem creates [stackitem.Item] representing LedgerBlock. -// It implements [stackitem.Convertible] interface. -func (res *LedgerBlock) ToStackItem() (stackitem.Item, error) { - if res == nil { - return stackitem.Null{}, nil - } - - var ( - err error - itm stackitem.Item - items = make([]stackitem.Item, 0, 10) - ) - itm, err = stackitem.NewByteArray(res.Hash.BytesBE()), error(nil) - if err != nil { - return nil, fmt.Errorf("field Hash: %w", err) - } - items = append(items, itm) - - itm, err = (*stackitem.BigInteger)(res.Version), error(nil) - if err != nil { - return nil, fmt.Errorf("field Version: %w", err) - } - items = append(items, itm) - - itm, err = stackitem.NewByteArray(res.PrevHash.BytesBE()), error(nil) - if err != nil { - return nil, fmt.Errorf("field PrevHash: %w", err) - } - items = append(items, itm) - - itm, err = stackitem.NewByteArray(res.MerkleRoot.BytesBE()), error(nil) - if err != nil { - return nil, fmt.Errorf("field MerkleRoot: %w", err) - } - items = append(items, itm) - - itm, err = (*stackitem.BigInteger)(res.Timestamp), error(nil) - if err != nil { - return nil, fmt.Errorf("field Timestamp: %w", err) - } - items = append(items, itm) - - itm, err = (*stackitem.BigInteger)(res.Nonce), error(nil) - if err != nil { - return nil, fmt.Errorf("field Nonce: %w", err) - } - items = append(items, itm) - - itm, err = (*stackitem.BigInteger)(res.Index), error(nil) - if err != nil { - return nil, fmt.Errorf("field Index: %w", err) - } - items = append(items, itm) - - itm, err = (*stackitem.BigInteger)(res.PrimaryIndex), error(nil) - if err != nil { - return nil, fmt.Errorf("field PrimaryIndex: %w", err) - } - items = append(items, itm) - - itm, err = stackitem.NewByteArray(res.NextConsensus.BytesBE()), error(nil) - if err != nil { - return nil, fmt.Errorf("field NextConsensus: %w", err) - } - items = append(items, itm) - - itm, err = (*stackitem.BigInteger)(res.TransactionsLength), error(nil) - if err != nil { - return nil, fmt.Errorf("field TransactionsLength: %w", err) - } - items = append(items, itm) - - return stackitem.NewStruct(items), nil -} - -// ToSCParameter creates [smartcontract.Parameter] representing LedgerBlock. -// It implements [smartcontract.Convertible] interface so that LedgerBlock -// could be used with invokers. -func (res *LedgerBlock) ToSCParameter() (smartcontract.Parameter, error) { - if res == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var ( - err error - prm smartcontract.Parameter - prms = make([]smartcontract.Parameter, 0, 10) - ) - prm, err = smartcontract.NewParameterFromValue(res.Hash) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Hash: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.Version) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Version: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.PrevHash) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field PrevHash: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.MerkleRoot) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field MerkleRoot: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.Timestamp) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Timestamp: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.Nonce) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Nonce: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.Index) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Index: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.PrimaryIndex) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field PrimaryIndex: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.NextConsensus) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field NextConsensus: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.TransactionsLength) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field TransactionsLength: %w", err) - } - prms = append(prms, prm) - - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil -} - -// itemToLedgerTransaction converts stack item into *LedgerTransaction. -// NULL item is returned as nil pointer without error. -func itemToLedgerTransaction(item stackitem.Item, err error) (*LedgerTransaction, error) { - if err != nil { - return nil, err - } - _, null := item.(stackitem.Null) - if null { - return nil, nil - } - var res = new(LedgerTransaction) - err = res.FromStackItem(item) - return res, err -} - -// Ensure *LedgerTransaction is a proper [stackitem.Convertible]. -var _ = stackitem.Convertible(&LedgerTransaction{}) - -// Ensure *LedgerTransaction is a proper [smartcontract.Convertible]. -var _ = smartcontract.Convertible(&LedgerTransaction{}) - -// FromStackItem retrieves fields of LedgerTransaction from the given -// [stackitem.Item] or returns an error if it's not possible to do to so. -// It implements [stackitem.Convertible] interface. -func (res *LedgerTransaction) FromStackItem(item stackitem.Item) error { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 8 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - res.Hash, err = func(item stackitem.Item) (util.Uint256, error) { - b, err := item.TryBytes() - if err != nil { - return util.Uint256{}, err - } - u, err := util.Uint256DecodeBytesBE(b) - if err != nil { - return util.Uint256{}, err - } - return u, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field Hash: %w", err) - } - - index++ - res.Version, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field Version: %w", err) - } - - index++ - res.Nonce, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field Nonce: %w", err) - } - - index++ - res.Sender, err = func(item stackitem.Item) (util.Uint160, error) { - b, err := item.TryBytes() - if err != nil { - return util.Uint160{}, err - } - u, err := util.Uint160DecodeBytesBE(b) - if err != nil { - return util.Uint160{}, err - } - return u, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field Sender: %w", err) - } - - index++ - res.SysFee, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field SysFee: %w", err) - } - - index++ - res.NetFee, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field NetFee: %w", err) - } - - index++ - res.ValidUntilBlock, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field ValidUntilBlock: %w", err) - } - - index++ - res.Script, err = arr[index].TryBytes() - if err != nil { - return fmt.Errorf("field Script: %w", err) - } - - return nil -} - -// ToStackItem creates [stackitem.Item] representing LedgerTransaction. -// It implements [stackitem.Convertible] interface. -func (res *LedgerTransaction) ToStackItem() (stackitem.Item, error) { - if res == nil { - return stackitem.Null{}, nil - } - - var ( - err error - itm stackitem.Item - items = make([]stackitem.Item, 0, 8) - ) - itm, err = stackitem.NewByteArray(res.Hash.BytesBE()), error(nil) - if err != nil { - return nil, fmt.Errorf("field Hash: %w", err) - } - items = append(items, itm) - - itm, err = (*stackitem.BigInteger)(res.Version), error(nil) - if err != nil { - return nil, fmt.Errorf("field Version: %w", err) - } - items = append(items, itm) - - itm, err = (*stackitem.BigInteger)(res.Nonce), error(nil) - if err != nil { - return nil, fmt.Errorf("field Nonce: %w", err) - } - items = append(items, itm) - - itm, err = stackitem.NewByteArray(res.Sender.BytesBE()), error(nil) - if err != nil { - return nil, fmt.Errorf("field Sender: %w", err) - } - items = append(items, itm) - - itm, err = (*stackitem.BigInteger)(res.SysFee), error(nil) - if err != nil { - return nil, fmt.Errorf("field SysFee: %w", err) - } - items = append(items, itm) - - itm, err = (*stackitem.BigInteger)(res.NetFee), error(nil) - if err != nil { - return nil, fmt.Errorf("field NetFee: %w", err) - } - items = append(items, itm) - - itm, err = (*stackitem.BigInteger)(res.ValidUntilBlock), error(nil) - if err != nil { - return nil, fmt.Errorf("field ValidUntilBlock: %w", err) - } - items = append(items, itm) - - itm, err = stackitem.NewByteArray(res.Script), error(nil) - if err != nil { - return nil, fmt.Errorf("field Script: %w", err) - } - items = append(items, itm) - - return stackitem.NewStruct(items), nil -} - -// ToSCParameter creates [smartcontract.Parameter] representing LedgerTransaction. -// It implements [smartcontract.Convertible] interface so that LedgerTransaction -// could be used with invokers. -func (res *LedgerTransaction) ToSCParameter() (smartcontract.Parameter, error) { - if res == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var ( - err error - prm smartcontract.Parameter - prms = make([]smartcontract.Parameter, 0, 8) - ) - prm, err = smartcontract.NewParameterFromValue(res.Hash) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Hash: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.Version) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Version: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.Nonce) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Nonce: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.Sender) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Sender: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.SysFee) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field SysFee: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.NetFee) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field NetFee: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.ValidUntilBlock) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field ValidUntilBlock: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.Script) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Script: %w", err) - } - prms = append(prms, prm) - - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil -} - -// itemToManagementABI converts stack item into *ManagementABI. -// NULL item is returned as nil pointer without error. -func itemToManagementABI(item stackitem.Item, err error) (*ManagementABI, error) { - if err != nil { - return nil, err - } - _, null := item.(stackitem.Null) - if null { - return nil, nil - } - var res = new(ManagementABI) - err = res.FromStackItem(item) - return res, err -} - -// Ensure *ManagementABI is a proper [stackitem.Convertible]. -var _ = stackitem.Convertible(&ManagementABI{}) - -// Ensure *ManagementABI is a proper [smartcontract.Convertible]. -var _ = smartcontract.Convertible(&ManagementABI{}) - -// FromStackItem retrieves fields of ManagementABI from the given -// [stackitem.Item] or returns an error if it's not possible to do to so. -// It implements [stackitem.Convertible] interface. -func (res *ManagementABI) FromStackItem(item stackitem.Item) error { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 2 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - res.Methods, err = func(item stackitem.Item) ([]*ManagementMethod, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([]*ManagementMethod, len(arr)) - for i := range res { - res[i], err = itemToManagementMethod(arr[i], nil) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field Methods: %w", err) - } - - index++ - res.Events, err = func(item stackitem.Item) ([]*ManagementEvent, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([]*ManagementEvent, len(arr)) - for i := range res { - res[i], err = itemToManagementEvent(arr[i], nil) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field Events: %w", err) - } - - return nil -} - -// ToStackItem creates [stackitem.Item] representing ManagementABI. -// It implements [stackitem.Convertible] interface. -func (res *ManagementABI) ToStackItem() (stackitem.Item, error) { - if res == nil { - return stackitem.Null{}, nil - } - - var ( - err error - itm stackitem.Item - items = make([]stackitem.Item, 0, 2) - ) - itm, err = func(in []*ManagementMethod) (stackitem.Item, error) { - if in == nil { - return stackitem.Null{}, nil - } - - var items = make([]stackitem.Item, 0, len(in)) - for i, v := range in { - itm, err := v.ToStackItem() - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - items = append(items, itm) - } - return stackitem.NewArray(items), nil - }(res.Methods) - if err != nil { - return nil, fmt.Errorf("field Methods: %w", err) - } - items = append(items, itm) - - itm, err = func(in []*ManagementEvent) (stackitem.Item, error) { - if in == nil { - return stackitem.Null{}, nil - } - - var items = make([]stackitem.Item, 0, len(in)) - for i, v := range in { - itm, err := v.ToStackItem() - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - items = append(items, itm) - } - return stackitem.NewArray(items), nil - }(res.Events) - if err != nil { - return nil, fmt.Errorf("field Events: %w", err) - } - items = append(items, itm) - - return stackitem.NewStruct(items), nil -} - -// ToSCParameter creates [smartcontract.Parameter] representing ManagementABI. -// It implements [smartcontract.Convertible] interface so that ManagementABI -// could be used with invokers. -func (res *ManagementABI) ToSCParameter() (smartcontract.Parameter, error) { - if res == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var ( - err error - prm smartcontract.Parameter - prms = make([]smartcontract.Parameter, 0, 2) - ) - prm, err = func(in []*ManagementMethod) (smartcontract.Parameter, error) { - if in == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var prms = make([]smartcontract.Parameter, 0, len(in)) - for i, v := range in { - prm, err := v.ToSCParameter() - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) - } - prms = append(prms, prm) - } - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil - }(res.Methods) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Methods: %w", err) - } - prms = append(prms, prm) - - prm, err = func(in []*ManagementEvent) (smartcontract.Parameter, error) { - if in == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var prms = make([]smartcontract.Parameter, 0, len(in)) - for i, v := range in { - prm, err := v.ToSCParameter() - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) - } - prms = append(prms, prm) - } - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil - }(res.Events) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Events: %w", err) - } - prms = append(prms, prm) - - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil -} - -// itemToManagementContract converts stack item into *ManagementContract. -// NULL item is returned as nil pointer without error. -func itemToManagementContract(item stackitem.Item, err error) (*ManagementContract, error) { - if err != nil { - return nil, err - } - _, null := item.(stackitem.Null) - if null { - return nil, nil - } - var res = new(ManagementContract) - err = res.FromStackItem(item) - return res, err -} - -// Ensure *ManagementContract is a proper [stackitem.Convertible]. -var _ = stackitem.Convertible(&ManagementContract{}) - -// Ensure *ManagementContract is a proper [smartcontract.Convertible]. -var _ = smartcontract.Convertible(&ManagementContract{}) - -// FromStackItem retrieves fields of ManagementContract from the given -// [stackitem.Item] or returns an error if it's not possible to do to so. -// It implements [stackitem.Convertible] interface. -func (res *ManagementContract) FromStackItem(item stackitem.Item) error { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 5 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - res.ID, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field ID: %w", err) - } - - index++ - res.UpdateCounter, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field UpdateCounter: %w", err) - } - - index++ - res.Hash, err = func(item stackitem.Item) (util.Uint160, error) { - b, err := item.TryBytes() - if err != nil { - return util.Uint160{}, err - } - u, err := util.Uint160DecodeBytesBE(b) - if err != nil { - return util.Uint160{}, err - } - return u, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field Hash: %w", err) - } - - index++ - res.NEF, err = arr[index].TryBytes() - if err != nil { - return fmt.Errorf("field NEF: %w", err) - } - - index++ - res.Manifest, err = itemToManagementManifest(arr[index], nil) - if err != nil { - return fmt.Errorf("field Manifest: %w", err) - } - - return nil -} - -// ToStackItem creates [stackitem.Item] representing ManagementContract. -// It implements [stackitem.Convertible] interface. -func (res *ManagementContract) ToStackItem() (stackitem.Item, error) { - if res == nil { - return stackitem.Null{}, nil - } - - var ( - err error - itm stackitem.Item - items = make([]stackitem.Item, 0, 5) - ) - itm, err = (*stackitem.BigInteger)(res.ID), error(nil) - if err != nil { - return nil, fmt.Errorf("field ID: %w", err) - } - items = append(items, itm) - - itm, err = (*stackitem.BigInteger)(res.UpdateCounter), error(nil) - if err != nil { - return nil, fmt.Errorf("field UpdateCounter: %w", err) - } - items = append(items, itm) - - itm, err = stackitem.NewByteArray(res.Hash.BytesBE()), error(nil) - if err != nil { - return nil, fmt.Errorf("field Hash: %w", err) - } - items = append(items, itm) - - itm, err = stackitem.NewByteArray(res.NEF), error(nil) - if err != nil { - return nil, fmt.Errorf("field NEF: %w", err) - } - items = append(items, itm) - - itm, err = res.Manifest.ToStackItem() - if err != nil { - return nil, fmt.Errorf("field Manifest: %w", err) - } - items = append(items, itm) - - return stackitem.NewStruct(items), nil -} - -// ToSCParameter creates [smartcontract.Parameter] representing ManagementContract. -// It implements [smartcontract.Convertible] interface so that ManagementContract -// could be used with invokers. -func (res *ManagementContract) ToSCParameter() (smartcontract.Parameter, error) { - if res == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var ( - err error - prm smartcontract.Parameter - prms = make([]smartcontract.Parameter, 0, 5) - ) - prm, err = smartcontract.NewParameterFromValue(res.ID) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field ID: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.UpdateCounter) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field UpdateCounter: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.Hash) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Hash: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.NEF) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field NEF: %w", err) - } - prms = append(prms, prm) - - prm, err = res.Manifest.ToSCParameter() - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Manifest: %w", err) - } - prms = append(prms, prm) - - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil -} - -// itemToManagementEvent converts stack item into *ManagementEvent. -// NULL item is returned as nil pointer without error. -func itemToManagementEvent(item stackitem.Item, err error) (*ManagementEvent, error) { - if err != nil { - return nil, err - } - _, null := item.(stackitem.Null) - if null { - return nil, nil - } - var res = new(ManagementEvent) - err = res.FromStackItem(item) - return res, err -} - -// Ensure *ManagementEvent is a proper [stackitem.Convertible]. -var _ = stackitem.Convertible(&ManagementEvent{}) - -// Ensure *ManagementEvent is a proper [smartcontract.Convertible]. -var _ = smartcontract.Convertible(&ManagementEvent{}) - -// FromStackItem retrieves fields of ManagementEvent from the given -// [stackitem.Item] or returns an error if it's not possible to do to so. -// It implements [stackitem.Convertible] interface. -func (res *ManagementEvent) FromStackItem(item stackitem.Item) error { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 2 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - res.Name, err = func(item stackitem.Item) (string, error) { - b, err := item.TryBytes() - if err != nil { - return "", err - } - if !utf8.Valid(b) { - return "", errors.New("not a UTF-8 string") - } - return string(b), nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field Name: %w", err) - } - - index++ - res.Params, err = func(item stackitem.Item) ([]*ManagementParameter, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([]*ManagementParameter, len(arr)) - for i := range res { - res[i], err = itemToManagementParameter(arr[i], nil) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field Params: %w", err) - } - - return nil -} - -// ToStackItem creates [stackitem.Item] representing ManagementEvent. -// It implements [stackitem.Convertible] interface. -func (res *ManagementEvent) ToStackItem() (stackitem.Item, error) { - if res == nil { - return stackitem.Null{}, nil - } - - var ( - err error - itm stackitem.Item - items = make([]stackitem.Item, 0, 2) - ) - itm, err = stackitem.NewByteArray([]byte(res.Name)), error(nil) - if err != nil { - return nil, fmt.Errorf("field Name: %w", err) - } - items = append(items, itm) - - itm, err = func(in []*ManagementParameter) (stackitem.Item, error) { - if in == nil { - return stackitem.Null{}, nil - } - - var items = make([]stackitem.Item, 0, len(in)) - for i, v := range in { - itm, err := v.ToStackItem() - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - items = append(items, itm) - } - return stackitem.NewArray(items), nil - }(res.Params) - if err != nil { - return nil, fmt.Errorf("field Params: %w", err) - } - items = append(items, itm) - - return stackitem.NewStruct(items), nil -} - -// ToSCParameter creates [smartcontract.Parameter] representing ManagementEvent. -// It implements [smartcontract.Convertible] interface so that ManagementEvent -// could be used with invokers. -func (res *ManagementEvent) ToSCParameter() (smartcontract.Parameter, error) { - if res == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var ( - err error - prm smartcontract.Parameter - prms = make([]smartcontract.Parameter, 0, 2) - ) - prm, err = smartcontract.NewParameterFromValue(res.Name) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Name: %w", err) - } - prms = append(prms, prm) - - prm, err = func(in []*ManagementParameter) (smartcontract.Parameter, error) { - if in == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var prms = make([]smartcontract.Parameter, 0, len(in)) - for i, v := range in { - prm, err := v.ToSCParameter() - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) - } - prms = append(prms, prm) - } - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil - }(res.Params) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Params: %w", err) - } - prms = append(prms, prm) - - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil -} - -// itemToManagementGroup converts stack item into *ManagementGroup. -// NULL item is returned as nil pointer without error. -func itemToManagementGroup(item stackitem.Item, err error) (*ManagementGroup, error) { - if err != nil { - return nil, err - } - _, null := item.(stackitem.Null) - if null { - return nil, nil - } - var res = new(ManagementGroup) - err = res.FromStackItem(item) - return res, err -} - -// Ensure *ManagementGroup is a proper [stackitem.Convertible]. -var _ = stackitem.Convertible(&ManagementGroup{}) - -// Ensure *ManagementGroup is a proper [smartcontract.Convertible]. -var _ = smartcontract.Convertible(&ManagementGroup{}) - -// FromStackItem retrieves fields of ManagementGroup from the given -// [stackitem.Item] or returns an error if it's not possible to do to so. -// It implements [stackitem.Convertible] interface. -func (res *ManagementGroup) FromStackItem(item stackitem.Item) error { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 2 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - res.PublicKey, err = func(item stackitem.Item) (*keys.PublicKey, error) { - b, err := item.TryBytes() - if err != nil { - return nil, err - } - k, err := keys.NewPublicKeyFromBytes(b, elliptic.P256()) - if err != nil { - return nil, err - } - return k, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field PublicKey: %w", err) - } - - index++ - res.Signature, err = arr[index].TryBytes() - if err != nil { - return fmt.Errorf("field Signature: %w", err) - } - - return nil -} - -// ToStackItem creates [stackitem.Item] representing ManagementGroup. -// It implements [stackitem.Convertible] interface. -func (res *ManagementGroup) ToStackItem() (stackitem.Item, error) { - if res == nil { - return stackitem.Null{}, nil - } - - var ( - err error - itm stackitem.Item - items = make([]stackitem.Item, 0, 2) - ) - itm, err = stackitem.NewByteArray(res.PublicKey.Bytes()), error(nil) - if err != nil { - return nil, fmt.Errorf("field PublicKey: %w", err) - } - items = append(items, itm) - - itm, err = stackitem.NewByteArray(res.Signature), error(nil) - if err != nil { - return nil, fmt.Errorf("field Signature: %w", err) - } - items = append(items, itm) - - return stackitem.NewStruct(items), nil -} - -// ToSCParameter creates [smartcontract.Parameter] representing ManagementGroup. -// It implements [smartcontract.Convertible] interface so that ManagementGroup -// could be used with invokers. -func (res *ManagementGroup) ToSCParameter() (smartcontract.Parameter, error) { - if res == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var ( - err error - prm smartcontract.Parameter - prms = make([]smartcontract.Parameter, 0, 2) - ) - prm, err = smartcontract.NewParameterFromValue(res.PublicKey) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field PublicKey: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.Signature) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Signature: %w", err) - } - prms = append(prms, prm) - - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil -} - -// itemToManagementManifest converts stack item into *ManagementManifest. -// NULL item is returned as nil pointer without error. -func itemToManagementManifest(item stackitem.Item, err error) (*ManagementManifest, error) { - if err != nil { - return nil, err - } - _, null := item.(stackitem.Null) - if null { - return nil, nil - } - var res = new(ManagementManifest) - err = res.FromStackItem(item) - return res, err -} - -// Ensure *ManagementManifest is a proper [stackitem.Convertible]. -var _ = stackitem.Convertible(&ManagementManifest{}) - -// Ensure *ManagementManifest is a proper [smartcontract.Convertible]. -var _ = smartcontract.Convertible(&ManagementManifest{}) - -// FromStackItem retrieves fields of ManagementManifest from the given -// [stackitem.Item] or returns an error if it's not possible to do to so. -// It implements [stackitem.Convertible] interface. -func (res *ManagementManifest) FromStackItem(item stackitem.Item) error { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 8 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - res.Name, err = func(item stackitem.Item) (string, error) { - b, err := item.TryBytes() - if err != nil { - return "", err - } - if !utf8.Valid(b) { - return "", errors.New("not a UTF-8 string") - } - return string(b), nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field Name: %w", err) - } - - index++ - res.Groups, err = func(item stackitem.Item) ([]*ManagementGroup, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([]*ManagementGroup, len(arr)) - for i := range res { - res[i], err = itemToManagementGroup(arr[i], nil) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field Groups: %w", err) - } - - index++ - res.Features, err = func(item stackitem.Item) (map[string]string, error) { - m, ok := item.Value().([]stackitem.MapElement) - if !ok { - return nil, fmt.Errorf("%s is not a map", item.Type().String()) - } - res := make(map[string]string) - for i := range m { - k, err := func(item stackitem.Item) (string, error) { - b, err := item.TryBytes() - if err != nil { - return "", err - } - if !utf8.Valid(b) { - return "", errors.New("not a UTF-8 string") - } - return string(b), nil - }(m[i].Key) - if err != nil { - return nil, fmt.Errorf("key %d: %w", i, err) - } - v, err := func(item stackitem.Item) (string, error) { - b, err := item.TryBytes() - if err != nil { - return "", err - } - if !utf8.Valid(b) { - return "", errors.New("not a UTF-8 string") - } - return string(b), nil - }(m[i].Value) - if err != nil { - return nil, fmt.Errorf("value %d: %w", i, err) - } - res[k] = v - } - return res, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field Features: %w", err) - } - - index++ - res.SupportedStandards, err = func(item stackitem.Item) ([]string, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([]string, len(arr)) - for i := range res { - res[i], err = func(item stackitem.Item) (string, error) { - b, err := item.TryBytes() - if err != nil { - return "", err - } - if !utf8.Valid(b) { - return "", errors.New("not a UTF-8 string") - } - return string(b), nil - }(arr[i]) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field SupportedStandards: %w", err) - } - - index++ - res.ABI, err = itemToManagementABI(arr[index], nil) - if err != nil { - return fmt.Errorf("field ABI: %w", err) - } - - index++ - res.Permissions, err = func(item stackitem.Item) ([]*ManagementPermission, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([]*ManagementPermission, len(arr)) - for i := range res { - res[i], err = itemToManagementPermission(arr[i], nil) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field Permissions: %w", err) - } - - index++ - res.Trusts, err = func(item stackitem.Item) ([]util.Uint160, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([]util.Uint160, len(arr)) - for i := range res { - res[i], err = func(item stackitem.Item) (util.Uint160, error) { - b, err := item.TryBytes() - if err != nil { - return util.Uint160{}, err - } - u, err := util.Uint160DecodeBytesBE(b) - if err != nil { - return util.Uint160{}, err - } - return u, nil - }(arr[i]) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field Trusts: %w", err) - } - - index++ - res.Extra, err = arr[index].Value(), error(nil) - if err != nil { - return fmt.Errorf("field Extra: %w", err) - } - - return nil -} - -// ToStackItem creates [stackitem.Item] representing ManagementManifest. -// It implements [stackitem.Convertible] interface. -func (res *ManagementManifest) ToStackItem() (stackitem.Item, error) { - if res == nil { - return stackitem.Null{}, nil - } - - var ( - err error - itm stackitem.Item - items = make([]stackitem.Item, 0, 8) - ) - itm, err = stackitem.NewByteArray([]byte(res.Name)), error(nil) - if err != nil { - return nil, fmt.Errorf("field Name: %w", err) - } - items = append(items, itm) - - itm, err = func(in []*ManagementGroup) (stackitem.Item, error) { - if in == nil { - return stackitem.Null{}, nil - } - - var items = make([]stackitem.Item, 0, len(in)) - for i, v := range in { - itm, err := v.ToStackItem() - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - items = append(items, itm) - } - return stackitem.NewArray(items), nil - }(res.Groups) - if err != nil { - return nil, fmt.Errorf("field Groups: %w", err) - } - items = append(items, itm) - - itm, err = func(in map[string]string) (stackitem.Item, error) { - if in == nil { - return stackitem.Null{}, nil - } - - var m = stackitem.NewMap() - for k, v := range in { - iKey, err := stackitem.NewByteArray([]byte(k)), error(nil) - if err != nil { - return nil, fmt.Errorf("key %v: %w", k, err) - } - iVal, err := stackitem.NewByteArray([]byte(v)), error(nil) - if err != nil { - return nil, fmt.Errorf("key %v, wrong value: %w", k, err) - } - m.Add(iKey, iVal) - } - return m, nil - }(res.Features) - if err != nil { - return nil, fmt.Errorf("field Features: %w", err) - } - items = append(items, itm) - - itm, err = func(in []string) (stackitem.Item, error) { - if in == nil { - return stackitem.Null{}, nil - } - - var items = make([]stackitem.Item, 0, len(in)) - for i, v := range in { - itm, err := stackitem.NewByteArray([]byte(v)), error(nil) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - items = append(items, itm) - } - return stackitem.NewArray(items), nil - }(res.SupportedStandards) - if err != nil { - return nil, fmt.Errorf("field SupportedStandards: %w", err) - } - items = append(items, itm) - - itm, err = res.ABI.ToStackItem() - if err != nil { - return nil, fmt.Errorf("field ABI: %w", err) - } - items = append(items, itm) - - itm, err = func(in []*ManagementPermission) (stackitem.Item, error) { - if in == nil { - return stackitem.Null{}, nil - } - - var items = make([]stackitem.Item, 0, len(in)) - for i, v := range in { - itm, err := v.ToStackItem() - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - items = append(items, itm) - } - return stackitem.NewArray(items), nil - }(res.Permissions) - if err != nil { - return nil, fmt.Errorf("field Permissions: %w", err) - } - items = append(items, itm) - - itm, err = func(in []util.Uint160) (stackitem.Item, error) { - if in == nil { - return stackitem.Null{}, nil - } - - var items = make([]stackitem.Item, 0, len(in)) - for i, v := range in { - itm, err := stackitem.NewByteArray(v.BytesBE()), error(nil) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - items = append(items, itm) - } - return stackitem.NewArray(items), nil - }(res.Trusts) - if err != nil { - return nil, fmt.Errorf("field Trusts: %w", err) - } - items = append(items, itm) - - itm, err = stackitem.TryMake(res.Extra) - if err != nil { - return nil, fmt.Errorf("field Extra: %w", err) - } - items = append(items, itm) - - return stackitem.NewStruct(items), nil -} - -// ToSCParameter creates [smartcontract.Parameter] representing ManagementManifest. -// It implements [smartcontract.Convertible] interface so that ManagementManifest -// could be used with invokers. -func (res *ManagementManifest) ToSCParameter() (smartcontract.Parameter, error) { - if res == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var ( - err error - prm smartcontract.Parameter - prms = make([]smartcontract.Parameter, 0, 8) - ) - prm, err = smartcontract.NewParameterFromValue(res.Name) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Name: %w", err) - } - prms = append(prms, prm) - - prm, err = func(in []*ManagementGroup) (smartcontract.Parameter, error) { - if in == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var prms = make([]smartcontract.Parameter, 0, len(in)) - for i, v := range in { - prm, err := v.ToSCParameter() - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) - } - prms = append(prms, prm) - } - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil - }(res.Groups) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Groups: %w", err) - } - prms = append(prms, prm) - - prm, err = func(in map[string]string) (smartcontract.Parameter, error) { - if in == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var prms = make([]smartcontract.ParameterPair, 0, len(in)) - for k, v := range in { - iKey, err := smartcontract.NewParameterFromValue(k) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("key %v: %w", k, err) - } - iVal, err := smartcontract.NewParameterFromValue(v) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("key %v, wrong value: %w", k, err) - } - prms = append(prms, smartcontract.ParameterPair{Key: iKey, Value: iVal}) - } - return smartcontract.Parameter{Type: smartcontract.MapType, Value: prms}, nil - }(res.Features) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Features: %w", err) - } - prms = append(prms, prm) - - prm, err = func(in []string) (smartcontract.Parameter, error) { - if in == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var prms = make([]smartcontract.Parameter, 0, len(in)) - for i, v := range in { - prm, err := smartcontract.NewParameterFromValue(v) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) - } - prms = append(prms, prm) - } - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil - }(res.SupportedStandards) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field SupportedStandards: %w", err) - } - prms = append(prms, prm) - - prm, err = res.ABI.ToSCParameter() - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field ABI: %w", err) - } - prms = append(prms, prm) - - prm, err = func(in []*ManagementPermission) (smartcontract.Parameter, error) { - if in == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var prms = make([]smartcontract.Parameter, 0, len(in)) - for i, v := range in { - prm, err := v.ToSCParameter() - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) - } - prms = append(prms, prm) - } - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil - }(res.Permissions) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Permissions: %w", err) - } - prms = append(prms, prm) - - prm, err = func(in []util.Uint160) (smartcontract.Parameter, error) { - if in == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var prms = make([]smartcontract.Parameter, 0, len(in)) - for i, v := range in { - prm, err := smartcontract.NewParameterFromValue(v) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) - } - prms = append(prms, prm) - } - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil - }(res.Trusts) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Trusts: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.Extra) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Extra: %w", err) - } - prms = append(prms, prm) - - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil -} - -// itemToManagementMethod converts stack item into *ManagementMethod. -// NULL item is returned as nil pointer without error. -func itemToManagementMethod(item stackitem.Item, err error) (*ManagementMethod, error) { - if err != nil { - return nil, err - } - _, null := item.(stackitem.Null) - if null { - return nil, nil - } - var res = new(ManagementMethod) - err = res.FromStackItem(item) - return res, err -} - -// Ensure *ManagementMethod is a proper [stackitem.Convertible]. -var _ = stackitem.Convertible(&ManagementMethod{}) - -// Ensure *ManagementMethod is a proper [smartcontract.Convertible]. -var _ = smartcontract.Convertible(&ManagementMethod{}) - -// FromStackItem retrieves fields of ManagementMethod from the given -// [stackitem.Item] or returns an error if it's not possible to do to so. -// It implements [stackitem.Convertible] interface. -func (res *ManagementMethod) FromStackItem(item stackitem.Item) error { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 5 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - res.Name, err = func(item stackitem.Item) (string, error) { - b, err := item.TryBytes() - if err != nil { - return "", err - } - if !utf8.Valid(b) { - return "", errors.New("not a UTF-8 string") - } - return string(b), nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field Name: %w", err) - } - - index++ - res.Params, err = func(item stackitem.Item) ([]*ManagementParameter, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([]*ManagementParameter, len(arr)) - for i := range res { - res[i], err = itemToManagementParameter(arr[i], nil) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field Params: %w", err) - } - - index++ - res.ReturnType, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field ReturnType: %w", err) - } - - index++ - res.Offset, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field Offset: %w", err) - } - - index++ - res.Safe, err = arr[index].TryBool() - if err != nil { - return fmt.Errorf("field Safe: %w", err) - } - - return nil -} - -// ToStackItem creates [stackitem.Item] representing ManagementMethod. -// It implements [stackitem.Convertible] interface. -func (res *ManagementMethod) ToStackItem() (stackitem.Item, error) { - if res == nil { - return stackitem.Null{}, nil - } - - var ( - err error - itm stackitem.Item - items = make([]stackitem.Item, 0, 5) - ) - itm, err = stackitem.NewByteArray([]byte(res.Name)), error(nil) - if err != nil { - return nil, fmt.Errorf("field Name: %w", err) - } - items = append(items, itm) - - itm, err = func(in []*ManagementParameter) (stackitem.Item, error) { - if in == nil { - return stackitem.Null{}, nil - } - - var items = make([]stackitem.Item, 0, len(in)) - for i, v := range in { - itm, err := v.ToStackItem() - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - items = append(items, itm) - } - return stackitem.NewArray(items), nil - }(res.Params) - if err != nil { - return nil, fmt.Errorf("field Params: %w", err) - } - items = append(items, itm) - - itm, err = (*stackitem.BigInteger)(res.ReturnType), error(nil) - if err != nil { - return nil, fmt.Errorf("field ReturnType: %w", err) - } - items = append(items, itm) - - itm, err = (*stackitem.BigInteger)(res.Offset), error(nil) - if err != nil { - return nil, fmt.Errorf("field Offset: %w", err) - } - items = append(items, itm) - - itm, err = stackitem.NewBool(res.Safe), error(nil) - if err != nil { - return nil, fmt.Errorf("field Safe: %w", err) - } - items = append(items, itm) - - return stackitem.NewStruct(items), nil -} - -// ToSCParameter creates [smartcontract.Parameter] representing ManagementMethod. -// It implements [smartcontract.Convertible] interface so that ManagementMethod -// could be used with invokers. -func (res *ManagementMethod) ToSCParameter() (smartcontract.Parameter, error) { - if res == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var ( - err error - prm smartcontract.Parameter - prms = make([]smartcontract.Parameter, 0, 5) - ) - prm, err = smartcontract.NewParameterFromValue(res.Name) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Name: %w", err) - } - prms = append(prms, prm) - - prm, err = func(in []*ManagementParameter) (smartcontract.Parameter, error) { - if in == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var prms = make([]smartcontract.Parameter, 0, len(in)) - for i, v := range in { - prm, err := v.ToSCParameter() - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) - } - prms = append(prms, prm) - } - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil - }(res.Params) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Params: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.ReturnType) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field ReturnType: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.Offset) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Offset: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.Safe) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Safe: %w", err) - } - prms = append(prms, prm) - - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil -} - -// itemToManagementParameter converts stack item into *ManagementParameter. -// NULL item is returned as nil pointer without error. -func itemToManagementParameter(item stackitem.Item, err error) (*ManagementParameter, error) { - if err != nil { - return nil, err - } - _, null := item.(stackitem.Null) - if null { - return nil, nil - } - var res = new(ManagementParameter) - err = res.FromStackItem(item) - return res, err -} - -// Ensure *ManagementParameter is a proper [stackitem.Convertible]. -var _ = stackitem.Convertible(&ManagementParameter{}) - -// Ensure *ManagementParameter is a proper [smartcontract.Convertible]. -var _ = smartcontract.Convertible(&ManagementParameter{}) - -// FromStackItem retrieves fields of ManagementParameter from the given -// [stackitem.Item] or returns an error if it's not possible to do to so. -// It implements [stackitem.Convertible] interface. -func (res *ManagementParameter) FromStackItem(item stackitem.Item) error { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 2 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - res.Name, err = func(item stackitem.Item) (string, error) { - b, err := item.TryBytes() - if err != nil { - return "", err - } - if !utf8.Valid(b) { - return "", errors.New("not a UTF-8 string") - } - return string(b), nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field Name: %w", err) - } - - index++ - res.Type, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field Type: %w", err) - } - - return nil -} - -// ToStackItem creates [stackitem.Item] representing ManagementParameter. -// It implements [stackitem.Convertible] interface. -func (res *ManagementParameter) ToStackItem() (stackitem.Item, error) { - if res == nil { - return stackitem.Null{}, nil - } - - var ( - err error - itm stackitem.Item - items = make([]stackitem.Item, 0, 2) - ) - itm, err = stackitem.NewByteArray([]byte(res.Name)), error(nil) - if err != nil { - return nil, fmt.Errorf("field Name: %w", err) - } - items = append(items, itm) - - itm, err = (*stackitem.BigInteger)(res.Type), error(nil) - if err != nil { - return nil, fmt.Errorf("field Type: %w", err) - } - items = append(items, itm) - - return stackitem.NewStruct(items), nil -} - -// ToSCParameter creates [smartcontract.Parameter] representing ManagementParameter. -// It implements [smartcontract.Convertible] interface so that ManagementParameter -// could be used with invokers. -func (res *ManagementParameter) ToSCParameter() (smartcontract.Parameter, error) { - if res == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var ( - err error - prm smartcontract.Parameter - prms = make([]smartcontract.Parameter, 0, 2) - ) - prm, err = smartcontract.NewParameterFromValue(res.Name) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Name: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.Type) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Type: %w", err) - } - prms = append(prms, prm) - - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil -} - -// itemToManagementPermission converts stack item into *ManagementPermission. -// NULL item is returned as nil pointer without error. -func itemToManagementPermission(item stackitem.Item, err error) (*ManagementPermission, error) { - if err != nil { - return nil, err - } - _, null := item.(stackitem.Null) - if null { - return nil, nil - } - var res = new(ManagementPermission) - err = res.FromStackItem(item) - return res, err -} - -// Ensure *ManagementPermission is a proper [stackitem.Convertible]. -var _ = stackitem.Convertible(&ManagementPermission{}) - -// Ensure *ManagementPermission is a proper [smartcontract.Convertible]. -var _ = smartcontract.Convertible(&ManagementPermission{}) - -// FromStackItem retrieves fields of ManagementPermission from the given -// [stackitem.Item] or returns an error if it's not possible to do to so. -// It implements [stackitem.Convertible] interface. -func (res *ManagementPermission) FromStackItem(item stackitem.Item) error { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 2 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - res.Contract, err = func(item stackitem.Item) (util.Uint160, error) { - b, err := item.TryBytes() - if err != nil { - return util.Uint160{}, err - } - u, err := util.Uint160DecodeBytesBE(b) - if err != nil { - return util.Uint160{}, err - } - return u, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field Contract: %w", err) - } - - index++ - res.Methods, err = func(item stackitem.Item) ([]string, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([]string, len(arr)) - for i := range res { - res[i], err = func(item stackitem.Item) (string, error) { - b, err := item.TryBytes() - if err != nil { - return "", err - } - if !utf8.Valid(b) { - return "", errors.New("not a UTF-8 string") - } - return string(b), nil - }(arr[i]) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field Methods: %w", err) - } - - return nil -} - -// ToStackItem creates [stackitem.Item] representing ManagementPermission. -// It implements [stackitem.Convertible] interface. -func (res *ManagementPermission) ToStackItem() (stackitem.Item, error) { - if res == nil { - return stackitem.Null{}, nil - } - - var ( - err error - itm stackitem.Item - items = make([]stackitem.Item, 0, 2) - ) - itm, err = stackitem.NewByteArray(res.Contract.BytesBE()), error(nil) - if err != nil { - return nil, fmt.Errorf("field Contract: %w", err) - } - items = append(items, itm) - - itm, err = func(in []string) (stackitem.Item, error) { - if in == nil { - return stackitem.Null{}, nil - } - - var items = make([]stackitem.Item, 0, len(in)) - for i, v := range in { - itm, err := stackitem.NewByteArray([]byte(v)), error(nil) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - items = append(items, itm) - } - return stackitem.NewArray(items), nil - }(res.Methods) - if err != nil { - return nil, fmt.Errorf("field Methods: %w", err) - } - items = append(items, itm) - - return stackitem.NewStruct(items), nil -} - -// ToSCParameter creates [smartcontract.Parameter] representing ManagementPermission. -// It implements [smartcontract.Convertible] interface so that ManagementPermission -// could be used with invokers. -func (res *ManagementPermission) ToSCParameter() (smartcontract.Parameter, error) { - if res == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var ( - err error - prm smartcontract.Parameter - prms = make([]smartcontract.Parameter, 0, 2) - ) - prm, err = smartcontract.NewParameterFromValue(res.Contract) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Contract: %w", err) - } - prms = append(prms, prm) - - prm, err = func(in []string) (smartcontract.Parameter, error) { - if in == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var prms = make([]smartcontract.Parameter, 0, len(in)) - for i, v := range in { - prm, err := smartcontract.NewParameterFromValue(v) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) - } - prms = append(prms, prm) - } - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil - }(res.Methods) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Methods: %w", err) - } - prms = append(prms, prm) - - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil -} - -// itemToStructsInternal converts stack item into *StructsInternal. -// NULL item is returned as nil pointer without error. -func itemToStructsInternal(item stackitem.Item, err error) (*StructsInternal, error) { - if err != nil { - return nil, err - } - _, null := item.(stackitem.Null) - if null { - return nil, nil - } - var res = new(StructsInternal) - err = res.FromStackItem(item) - return res, err -} - -// Ensure *StructsInternal is a proper [stackitem.Convertible]. -var _ = stackitem.Convertible(&StructsInternal{}) - -// Ensure *StructsInternal is a proper [smartcontract.Convertible]. -var _ = smartcontract.Convertible(&StructsInternal{}) - -// FromStackItem retrieves fields of StructsInternal from the given -// [stackitem.Item] or returns an error if it's not possible to do to so. -// It implements [stackitem.Convertible] interface. -func (res *StructsInternal) FromStackItem(item stackitem.Item) error { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 14 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - res.Bool, err = arr[index].TryBool() - if err != nil { - return fmt.Errorf("field Bool: %w", err) - } - - index++ - res.Int, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field Int: %w", err) - } - - index++ - res.Bytes, err = arr[index].TryBytes() - if err != nil { - return fmt.Errorf("field Bytes: %w", err) - } - - index++ - res.String, err = func(item stackitem.Item) (string, error) { - b, err := item.TryBytes() - if err != nil { - return "", err - } - if !utf8.Valid(b) { - return "", errors.New("not a UTF-8 string") - } - return string(b), nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field String: %w", err) - } - - index++ - res.H160, err = func(item stackitem.Item) (util.Uint160, error) { - b, err := item.TryBytes() - if err != nil { - return util.Uint160{}, err - } - u, err := util.Uint160DecodeBytesBE(b) - if err != nil { - return util.Uint160{}, err - } - return u, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field H160: %w", err) - } - - index++ - res.H256, err = func(item stackitem.Item) (util.Uint256, error) { - b, err := item.TryBytes() - if err != nil { - return util.Uint256{}, err - } - u, err := util.Uint256DecodeBytesBE(b) - if err != nil { - return util.Uint256{}, err - } - return u, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field H256: %w", err) - } - - index++ - res.PK, err = func(item stackitem.Item) (*keys.PublicKey, error) { - b, err := item.TryBytes() - if err != nil { - return nil, err - } - k, err := keys.NewPublicKeyFromBytes(b, elliptic.P256()) - if err != nil { - return nil, err - } - return k, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field PK: %w", err) - } - - index++ - res.PubKey, err = func(item stackitem.Item) (*keys.PublicKey, error) { - b, err := item.TryBytes() - if err != nil { - return nil, err - } - k, err := keys.NewPublicKeyFromBytes(b, elliptic.P256()) - if err != nil { - return nil, err - } - return k, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field PubKey: %w", err) - } - - index++ - res.Sign, err = arr[index].TryBytes() - if err != nil { - return fmt.Errorf("field Sign: %w", err) - } - - index++ - res.ArrOfBytes, err = func(item stackitem.Item) ([][]byte, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([][]byte, len(arr)) - for i := range res { - res[i], err = arr[i].TryBytes() - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field ArrOfBytes: %w", err) - } - - index++ - res.ArrOfH160, err = func(item stackitem.Item) ([]util.Uint160, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([]util.Uint160, len(arr)) - for i := range res { - res[i], err = func(item stackitem.Item) (util.Uint160, error) { - b, err := item.TryBytes() - if err != nil { - return util.Uint160{}, err - } - u, err := util.Uint160DecodeBytesBE(b) - if err != nil { - return util.Uint160{}, err - } - return u, nil - }(arr[i]) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field ArrOfH160: %w", err) - } - - index++ - res.Map, err = func(item stackitem.Item) (map[*big.Int]keys.PublicKeys, error) { - m, ok := item.Value().([]stackitem.MapElement) - if !ok { - return nil, fmt.Errorf("%s is not a map", item.Type().String()) - } - res := make(map[*big.Int]keys.PublicKeys) - for i := range m { - k, err := m[i].Key.TryInteger() - if err != nil { - return nil, fmt.Errorf("key %d: %w", i, err) - } - v, err := func(item stackitem.Item) (keys.PublicKeys, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make(keys.PublicKeys, len(arr)) - for i := range res { - res[i], err = func(item stackitem.Item) (*keys.PublicKey, error) { - b, err := item.TryBytes() - if err != nil { - return nil, err - } - k, err := keys.NewPublicKeyFromBytes(b, elliptic.P256()) - if err != nil { - return nil, err - } - return k, nil - }(arr[i]) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(m[i].Value) - if err != nil { - return nil, fmt.Errorf("value %d: %w", i, err) - } - res[k] = v - } - return res, nil - }(arr[index]) - if err != nil { - return fmt.Errorf("field Map: %w", err) - } - - index++ - res.Struct, err = itemToStructsInternal(arr[index], nil) - if err != nil { - return fmt.Errorf("field Struct: %w", err) - } - - index++ - res.UnexportedField, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field UnexportedField: %w", err) - } - - return nil -} - -// ToStackItem creates [stackitem.Item] representing StructsInternal. -// It implements [stackitem.Convertible] interface. -func (res *StructsInternal) ToStackItem() (stackitem.Item, error) { - if res == nil { - return stackitem.Null{}, nil - } - - var ( - err error - itm stackitem.Item - items = make([]stackitem.Item, 0, 14) - ) - itm, err = stackitem.NewBool(res.Bool), error(nil) - if err != nil { - return nil, fmt.Errorf("field Bool: %w", err) - } - items = append(items, itm) - - itm, err = (*stackitem.BigInteger)(res.Int), error(nil) - if err != nil { - return nil, fmt.Errorf("field Int: %w", err) - } - items = append(items, itm) - - itm, err = stackitem.NewByteArray(res.Bytes), error(nil) - if err != nil { - return nil, fmt.Errorf("field Bytes: %w", err) - } - items = append(items, itm) - - itm, err = stackitem.NewByteArray([]byte(res.String)), error(nil) - if err != nil { - return nil, fmt.Errorf("field String: %w", err) - } - items = append(items, itm) - - itm, err = stackitem.NewByteArray(res.H160.BytesBE()), error(nil) - if err != nil { - return nil, fmt.Errorf("field H160: %w", err) - } - items = append(items, itm) - - itm, err = stackitem.NewByteArray(res.H256.BytesBE()), error(nil) - if err != nil { - return nil, fmt.Errorf("field H256: %w", err) - } - items = append(items, itm) - - itm, err = stackitem.NewByteArray(res.PK.Bytes()), error(nil) - if err != nil { - return nil, fmt.Errorf("field PK: %w", err) - } - items = append(items, itm) - - itm, err = stackitem.NewByteArray(res.PubKey.Bytes()), error(nil) - if err != nil { - return nil, fmt.Errorf("field PubKey: %w", err) - } - items = append(items, itm) - - itm, err = stackitem.NewByteArray(res.Sign), error(nil) - if err != nil { - return nil, fmt.Errorf("field Sign: %w", err) - } - items = append(items, itm) - - itm, err = func(in [][]byte) (stackitem.Item, error) { - if in == nil { - return stackitem.Null{}, nil - } - - var items = make([]stackitem.Item, 0, len(in)) - for i, v := range in { - itm, err := stackitem.NewByteArray(v), error(nil) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - items = append(items, itm) - } - return stackitem.NewArray(items), nil - }(res.ArrOfBytes) - if err != nil { - return nil, fmt.Errorf("field ArrOfBytes: %w", err) - } - items = append(items, itm) - - itm, err = func(in []util.Uint160) (stackitem.Item, error) { - if in == nil { - return stackitem.Null{}, nil - } - - var items = make([]stackitem.Item, 0, len(in)) - for i, v := range in { - itm, err := stackitem.NewByteArray(v.BytesBE()), error(nil) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - items = append(items, itm) - } - return stackitem.NewArray(items), nil - }(res.ArrOfH160) - if err != nil { - return nil, fmt.Errorf("field ArrOfH160: %w", err) - } - items = append(items, itm) - - itm, err = func(in map[*big.Int]keys.PublicKeys) (stackitem.Item, error) { - if in == nil { - return stackitem.Null{}, nil - } - - var m = stackitem.NewMap() - for k, v := range in { - iKey, err := (*stackitem.BigInteger)(k), error(nil) - if err != nil { - return nil, fmt.Errorf("key %v: %w", k, err) - } - iVal, err := func(in keys.PublicKeys) (stackitem.Item, error) { - if in == nil { - return stackitem.Null{}, nil - } - - var items = make([]stackitem.Item, 0, len(in)) - for i, v := range in { - itm, err := stackitem.NewByteArray(v.Bytes()), error(nil) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - items = append(items, itm) - } - return stackitem.NewArray(items), nil - }(v) - if err != nil { - return nil, fmt.Errorf("key %v, wrong value: %w", k, err) - } - m.Add(iKey, iVal) - } - return m, nil - }(res.Map) - if err != nil { - return nil, fmt.Errorf("field Map: %w", err) - } - items = append(items, itm) - - itm, err = res.Struct.ToStackItem() - if err != nil { - return nil, fmt.Errorf("field Struct: %w", err) - } - items = append(items, itm) - - itm, err = (*stackitem.BigInteger)(res.UnexportedField), error(nil) - if err != nil { - return nil, fmt.Errorf("field UnexportedField: %w", err) - } - items = append(items, itm) - - return stackitem.NewStruct(items), nil -} - -// ToSCParameter creates [smartcontract.Parameter] representing StructsInternal. -// It implements [smartcontract.Convertible] interface so that StructsInternal -// could be used with invokers. -func (res *StructsInternal) ToSCParameter() (smartcontract.Parameter, error) { - if res == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var ( - err error - prm smartcontract.Parameter - prms = make([]smartcontract.Parameter, 0, 14) - ) - prm, err = smartcontract.NewParameterFromValue(res.Bool) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Bool: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.Int) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Int: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.Bytes) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Bytes: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.String) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field String: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.H160) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field H160: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.H256) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field H256: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.PK) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field PK: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.PubKey) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field PubKey: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.Sign) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Sign: %w", err) - } - prms = append(prms, prm) - - prm, err = func(in [][]byte) (smartcontract.Parameter, error) { - if in == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var prms = make([]smartcontract.Parameter, 0, len(in)) - for i, v := range in { - prm, err := smartcontract.NewParameterFromValue(v) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) - } - prms = append(prms, prm) - } - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil - }(res.ArrOfBytes) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field ArrOfBytes: %w", err) - } - prms = append(prms, prm) - - prm, err = func(in []util.Uint160) (smartcontract.Parameter, error) { - if in == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var prms = make([]smartcontract.Parameter, 0, len(in)) - for i, v := range in { - prm, err := smartcontract.NewParameterFromValue(v) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) - } - prms = append(prms, prm) - } - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil - }(res.ArrOfH160) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field ArrOfH160: %w", err) - } - prms = append(prms, prm) - - prm, err = func(in map[*big.Int]keys.PublicKeys) (smartcontract.Parameter, error) { - if in == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var prms = make([]smartcontract.ParameterPair, 0, len(in)) - for k, v := range in { - iKey, err := smartcontract.NewParameterFromValue(k) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("key %v: %w", k, err) - } - iVal, err := func(in keys.PublicKeys) (smartcontract.Parameter, error) { - if in == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var prms = make([]smartcontract.Parameter, 0, len(in)) - for i, v := range in { - prm, err := smartcontract.NewParameterFromValue(v) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) - } - prms = append(prms, prm) - } - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil - }(v) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("key %v, wrong value: %w", k, err) - } - prms = append(prms, smartcontract.ParameterPair{Key: iKey, Value: iVal}) - } - return smartcontract.Parameter{Type: smartcontract.MapType, Value: prms}, nil - }(res.Map) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Map: %w", err) - } - prms = append(prms, prm) - - prm, err = res.Struct.ToSCParameter() - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field Struct: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.UnexportedField) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field UnexportedField: %w", err) - } - prms = append(prms, prm) - - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil -} +// Code generated by neo-go contract generate-rpcwrapper --manifest --out [--hash ] [--config ]; DO NOT EDIT. + +// Package structs contains RPC wrappers for Types contract. +package structs + +import ( + "crypto/elliptic" + "errors" + "fmt" + "github.com/tutus-one/tutus-chain/pkg/crypto/keys" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" + "github.com/tutus-one/tutus-chain/pkg/rpcclient/unwrap" + "github.com/tutus-one/tutus-chain/pkg/smartcontract" + "github.com/tutus-one/tutus-chain/pkg/util" + "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" + "math/big" + "unicode/utf8" +) + +// LedgerBlock is a contract-specific ledger.Block type used by its methods. +type LedgerBlock struct { + Hash util.Uint256 + Version *big.Int + PrevHash util.Uint256 + MerkleRoot util.Uint256 + Timestamp *big.Int + Nonce *big.Int + Index *big.Int + PrimaryIndex *big.Int + NextConsensus util.Uint160 + TransactionsLength *big.Int +} + +// LedgerTransaction is a contract-specific ledger.Transaction type used by its methods. +type LedgerTransaction struct { + Hash util.Uint256 + Version *big.Int + Nonce *big.Int + Sender util.Uint160 + SysFee *big.Int + NetFee *big.Int + ValidUntilBlock *big.Int + Script []byte +} + +// ManagementABI is a contract-specific management.ABI type used by its methods. +type ManagementABI struct { + Methods []*ManagementMethod + Events []*ManagementEvent +} + +// ManagementContract is a contract-specific management.Contract type used by its methods. +type ManagementContract struct { + ID *big.Int + UpdateCounter *big.Int + Hash util.Uint160 + NEF []byte + Manifest *ManagementManifest +} + +// ManagementEvent is a contract-specific management.Event type used by its methods. +type ManagementEvent struct { + Name string + Params []*ManagementParameter +} + +// ManagementGroup is a contract-specific management.Group type used by its methods. +type ManagementGroup struct { + PublicKey *keys.PublicKey + Signature []byte +} + +// ManagementManifest is a contract-specific management.Manifest type used by its methods. +type ManagementManifest struct { + Name string + Groups []*ManagementGroup + Features map[string]string + SupportedStandards []string + ABI *ManagementABI + Permissions []*ManagementPermission + Trusts []util.Uint160 + Extra any +} + +// ManagementMethod is a contract-specific management.Method type used by its methods. +type ManagementMethod struct { + Name string + Params []*ManagementParameter + ReturnType *big.Int + Offset *big.Int + Safe bool +} + +// ManagementParameter is a contract-specific management.Parameter type used by its methods. +type ManagementParameter struct { + Name string + Type *big.Int +} + +// ManagementPermission is a contract-specific management.Permission type used by its methods. +type ManagementPermission struct { + Contract util.Uint160 + Methods []string +} + +// StructsInternal is a contract-specific structs.Internal type used by its methods. +type StructsInternal struct { + Bool bool + Int *big.Int + Bytes []byte + String string + H160 util.Uint160 + H256 util.Uint256 + PK *keys.PublicKey + PubKey *keys.PublicKey + Sign []byte + ArrOfBytes [][]byte + ArrOfH160 []util.Uint160 + Map map[*big.Int]keys.PublicKeys + Struct *StructsInternal + UnexportedField *big.Int +} + +// Invoker is used by ContractReader to call various safe methods. +type Invoker interface { + Call(contract util.Uint160, operation string, params ...any) (*result.Invoke, error) +} + +// ContractReader implements safe contract methods. +type ContractReader struct { + invoker Invoker + hash util.Uint160 +} + +// NewReader creates an instance of ContractReader using provided contract hash and the given Invoker. +func NewReader(invoker Invoker, hash util.Uint160) *ContractReader { + return &ContractReader{invoker, hash} +} + +// Block invokes `block` method of contract. +func (c *ContractReader) Block(b *LedgerBlock) (*LedgerBlock, error) { + return itemToLedgerBlock(unwrap.Item(c.invoker.Call(c.hash, "block", b))) +} + +// Contract invokes `contract` method of contract. +func (c *ContractReader) Contract(mc *ManagementContract) (*ManagementContract, error) { + return itemToManagementContract(unwrap.Item(c.invoker.Call(c.hash, "contract", mc))) +} + +// Struct invokes `struct` method of contract. +func (c *ContractReader) Struct(s *StructsInternal) (*StructsInternal, error) { + return itemToStructsInternal(unwrap.Item(c.invoker.Call(c.hash, "struct", s))) +} + +// Transaction invokes `transaction` method of contract. +func (c *ContractReader) Transaction(t *LedgerTransaction) (*LedgerTransaction, error) { + return itemToLedgerTransaction(unwrap.Item(c.invoker.Call(c.hash, "transaction", t))) +} + +// itemToLedgerBlock converts stack item into *LedgerBlock. +// NULL item is returned as nil pointer without error. +func itemToLedgerBlock(item stackitem.Item, err error) (*LedgerBlock, error) { + if err != nil { + return nil, err + } + _, null := item.(stackitem.Null) + if null { + return nil, nil + } + var res = new(LedgerBlock) + err = res.FromStackItem(item) + return res, err +} + +// Ensure *LedgerBlock is a proper [stackitem.Convertible]. +var _ = stackitem.Convertible(&LedgerBlock{}) + +// Ensure *LedgerBlock is a proper [smartcontract.Convertible]. +var _ = smartcontract.Convertible(&LedgerBlock{}) + +// FromStackItem retrieves fields of LedgerBlock from the given +// [stackitem.Item] or returns an error if it's not possible to do to so. +// It implements [stackitem.Convertible] interface. +func (res *LedgerBlock) FromStackItem(item stackitem.Item) error { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 10 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + res.Hash, err = func(item stackitem.Item) (util.Uint256, error) { + b, err := item.TryBytes() + if err != nil { + return util.Uint256{}, err + } + u, err := util.Uint256DecodeBytesBE(b) + if err != nil { + return util.Uint256{}, err + } + return u, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field Hash: %w", err) + } + + index++ + res.Version, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field Version: %w", err) + } + + index++ + res.PrevHash, err = func(item stackitem.Item) (util.Uint256, error) { + b, err := item.TryBytes() + if err != nil { + return util.Uint256{}, err + } + u, err := util.Uint256DecodeBytesBE(b) + if err != nil { + return util.Uint256{}, err + } + return u, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field PrevHash: %w", err) + } + + index++ + res.MerkleRoot, err = func(item stackitem.Item) (util.Uint256, error) { + b, err := item.TryBytes() + if err != nil { + return util.Uint256{}, err + } + u, err := util.Uint256DecodeBytesBE(b) + if err != nil { + return util.Uint256{}, err + } + return u, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field MerkleRoot: %w", err) + } + + index++ + res.Timestamp, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field Timestamp: %w", err) + } + + index++ + res.Nonce, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field Nonce: %w", err) + } + + index++ + res.Index, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field Index: %w", err) + } + + index++ + res.PrimaryIndex, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field PrimaryIndex: %w", err) + } + + index++ + res.NextConsensus, err = func(item stackitem.Item) (util.Uint160, error) { + b, err := item.TryBytes() + if err != nil { + return util.Uint160{}, err + } + u, err := util.Uint160DecodeBytesBE(b) + if err != nil { + return util.Uint160{}, err + } + return u, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field NextConsensus: %w", err) + } + + index++ + res.TransactionsLength, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field TransactionsLength: %w", err) + } + + return nil +} + +// ToStackItem creates [stackitem.Item] representing LedgerBlock. +// It implements [stackitem.Convertible] interface. +func (res *LedgerBlock) ToStackItem() (stackitem.Item, error) { + if res == nil { + return stackitem.Null{}, nil + } + + var ( + err error + itm stackitem.Item + items = make([]stackitem.Item, 0, 10) + ) + itm, err = stackitem.NewByteArray(res.Hash.BytesBE()), error(nil) + if err != nil { + return nil, fmt.Errorf("field Hash: %w", err) + } + items = append(items, itm) + + itm, err = (*stackitem.BigInteger)(res.Version), error(nil) + if err != nil { + return nil, fmt.Errorf("field Version: %w", err) + } + items = append(items, itm) + + itm, err = stackitem.NewByteArray(res.PrevHash.BytesBE()), error(nil) + if err != nil { + return nil, fmt.Errorf("field PrevHash: %w", err) + } + items = append(items, itm) + + itm, err = stackitem.NewByteArray(res.MerkleRoot.BytesBE()), error(nil) + if err != nil { + return nil, fmt.Errorf("field MerkleRoot: %w", err) + } + items = append(items, itm) + + itm, err = (*stackitem.BigInteger)(res.Timestamp), error(nil) + if err != nil { + return nil, fmt.Errorf("field Timestamp: %w", err) + } + items = append(items, itm) + + itm, err = (*stackitem.BigInteger)(res.Nonce), error(nil) + if err != nil { + return nil, fmt.Errorf("field Nonce: %w", err) + } + items = append(items, itm) + + itm, err = (*stackitem.BigInteger)(res.Index), error(nil) + if err != nil { + return nil, fmt.Errorf("field Index: %w", err) + } + items = append(items, itm) + + itm, err = (*stackitem.BigInteger)(res.PrimaryIndex), error(nil) + if err != nil { + return nil, fmt.Errorf("field PrimaryIndex: %w", err) + } + items = append(items, itm) + + itm, err = stackitem.NewByteArray(res.NextConsensus.BytesBE()), error(nil) + if err != nil { + return nil, fmt.Errorf("field NextConsensus: %w", err) + } + items = append(items, itm) + + itm, err = (*stackitem.BigInteger)(res.TransactionsLength), error(nil) + if err != nil { + return nil, fmt.Errorf("field TransactionsLength: %w", err) + } + items = append(items, itm) + + return stackitem.NewStruct(items), nil +} + +// ToSCParameter creates [smartcontract.Parameter] representing LedgerBlock. +// It implements [smartcontract.Convertible] interface so that LedgerBlock +// could be used with invokers. +func (res *LedgerBlock) ToSCParameter() (smartcontract.Parameter, error) { + if res == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var ( + err error + prm smartcontract.Parameter + prms = make([]smartcontract.Parameter, 0, 10) + ) + prm, err = smartcontract.NewParameterFromValue(res.Hash) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Hash: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.Version) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Version: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.PrevHash) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field PrevHash: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.MerkleRoot) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field MerkleRoot: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.Timestamp) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Timestamp: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.Nonce) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Nonce: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.Index) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Index: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.PrimaryIndex) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field PrimaryIndex: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.NextConsensus) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field NextConsensus: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.TransactionsLength) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field TransactionsLength: %w", err) + } + prms = append(prms, prm) + + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil +} + +// itemToLedgerTransaction converts stack item into *LedgerTransaction. +// NULL item is returned as nil pointer without error. +func itemToLedgerTransaction(item stackitem.Item, err error) (*LedgerTransaction, error) { + if err != nil { + return nil, err + } + _, null := item.(stackitem.Null) + if null { + return nil, nil + } + var res = new(LedgerTransaction) + err = res.FromStackItem(item) + return res, err +} + +// Ensure *LedgerTransaction is a proper [stackitem.Convertible]. +var _ = stackitem.Convertible(&LedgerTransaction{}) + +// Ensure *LedgerTransaction is a proper [smartcontract.Convertible]. +var _ = smartcontract.Convertible(&LedgerTransaction{}) + +// FromStackItem retrieves fields of LedgerTransaction from the given +// [stackitem.Item] or returns an error if it's not possible to do to so. +// It implements [stackitem.Convertible] interface. +func (res *LedgerTransaction) FromStackItem(item stackitem.Item) error { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 8 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + res.Hash, err = func(item stackitem.Item) (util.Uint256, error) { + b, err := item.TryBytes() + if err != nil { + return util.Uint256{}, err + } + u, err := util.Uint256DecodeBytesBE(b) + if err != nil { + return util.Uint256{}, err + } + return u, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field Hash: %w", err) + } + + index++ + res.Version, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field Version: %w", err) + } + + index++ + res.Nonce, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field Nonce: %w", err) + } + + index++ + res.Sender, err = func(item stackitem.Item) (util.Uint160, error) { + b, err := item.TryBytes() + if err != nil { + return util.Uint160{}, err + } + u, err := util.Uint160DecodeBytesBE(b) + if err != nil { + return util.Uint160{}, err + } + return u, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field Sender: %w", err) + } + + index++ + res.SysFee, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field SysFee: %w", err) + } + + index++ + res.NetFee, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field NetFee: %w", err) + } + + index++ + res.ValidUntilBlock, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field ValidUntilBlock: %w", err) + } + + index++ + res.Script, err = arr[index].TryBytes() + if err != nil { + return fmt.Errorf("field Script: %w", err) + } + + return nil +} + +// ToStackItem creates [stackitem.Item] representing LedgerTransaction. +// It implements [stackitem.Convertible] interface. +func (res *LedgerTransaction) ToStackItem() (stackitem.Item, error) { + if res == nil { + return stackitem.Null{}, nil + } + + var ( + err error + itm stackitem.Item + items = make([]stackitem.Item, 0, 8) + ) + itm, err = stackitem.NewByteArray(res.Hash.BytesBE()), error(nil) + if err != nil { + return nil, fmt.Errorf("field Hash: %w", err) + } + items = append(items, itm) + + itm, err = (*stackitem.BigInteger)(res.Version), error(nil) + if err != nil { + return nil, fmt.Errorf("field Version: %w", err) + } + items = append(items, itm) + + itm, err = (*stackitem.BigInteger)(res.Nonce), error(nil) + if err != nil { + return nil, fmt.Errorf("field Nonce: %w", err) + } + items = append(items, itm) + + itm, err = stackitem.NewByteArray(res.Sender.BytesBE()), error(nil) + if err != nil { + return nil, fmt.Errorf("field Sender: %w", err) + } + items = append(items, itm) + + itm, err = (*stackitem.BigInteger)(res.SysFee), error(nil) + if err != nil { + return nil, fmt.Errorf("field SysFee: %w", err) + } + items = append(items, itm) + + itm, err = (*stackitem.BigInteger)(res.NetFee), error(nil) + if err != nil { + return nil, fmt.Errorf("field NetFee: %w", err) + } + items = append(items, itm) + + itm, err = (*stackitem.BigInteger)(res.ValidUntilBlock), error(nil) + if err != nil { + return nil, fmt.Errorf("field ValidUntilBlock: %w", err) + } + items = append(items, itm) + + itm, err = stackitem.NewByteArray(res.Script), error(nil) + if err != nil { + return nil, fmt.Errorf("field Script: %w", err) + } + items = append(items, itm) + + return stackitem.NewStruct(items), nil +} + +// ToSCParameter creates [smartcontract.Parameter] representing LedgerTransaction. +// It implements [smartcontract.Convertible] interface so that LedgerTransaction +// could be used with invokers. +func (res *LedgerTransaction) ToSCParameter() (smartcontract.Parameter, error) { + if res == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var ( + err error + prm smartcontract.Parameter + prms = make([]smartcontract.Parameter, 0, 8) + ) + prm, err = smartcontract.NewParameterFromValue(res.Hash) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Hash: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.Version) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Version: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.Nonce) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Nonce: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.Sender) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Sender: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.SysFee) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field SysFee: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.NetFee) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field NetFee: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.ValidUntilBlock) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field ValidUntilBlock: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.Script) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Script: %w", err) + } + prms = append(prms, prm) + + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil +} + +// itemToManagementABI converts stack item into *ManagementABI. +// NULL item is returned as nil pointer without error. +func itemToManagementABI(item stackitem.Item, err error) (*ManagementABI, error) { + if err != nil { + return nil, err + } + _, null := item.(stackitem.Null) + if null { + return nil, nil + } + var res = new(ManagementABI) + err = res.FromStackItem(item) + return res, err +} + +// Ensure *ManagementABI is a proper [stackitem.Convertible]. +var _ = stackitem.Convertible(&ManagementABI{}) + +// Ensure *ManagementABI is a proper [smartcontract.Convertible]. +var _ = smartcontract.Convertible(&ManagementABI{}) + +// FromStackItem retrieves fields of ManagementABI from the given +// [stackitem.Item] or returns an error if it's not possible to do to so. +// It implements [stackitem.Convertible] interface. +func (res *ManagementABI) FromStackItem(item stackitem.Item) error { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 2 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + res.Methods, err = func(item stackitem.Item) ([]*ManagementMethod, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([]*ManagementMethod, len(arr)) + for i := range res { + res[i], err = itemToManagementMethod(arr[i], nil) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field Methods: %w", err) + } + + index++ + res.Events, err = func(item stackitem.Item) ([]*ManagementEvent, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([]*ManagementEvent, len(arr)) + for i := range res { + res[i], err = itemToManagementEvent(arr[i], nil) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field Events: %w", err) + } + + return nil +} + +// ToStackItem creates [stackitem.Item] representing ManagementABI. +// It implements [stackitem.Convertible] interface. +func (res *ManagementABI) ToStackItem() (stackitem.Item, error) { + if res == nil { + return stackitem.Null{}, nil + } + + var ( + err error + itm stackitem.Item + items = make([]stackitem.Item, 0, 2) + ) + itm, err = func(in []*ManagementMethod) (stackitem.Item, error) { + if in == nil { + return stackitem.Null{}, nil + } + + var items = make([]stackitem.Item, 0, len(in)) + for i, v := range in { + itm, err := v.ToStackItem() + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + items = append(items, itm) + } + return stackitem.NewArray(items), nil + }(res.Methods) + if err != nil { + return nil, fmt.Errorf("field Methods: %w", err) + } + items = append(items, itm) + + itm, err = func(in []*ManagementEvent) (stackitem.Item, error) { + if in == nil { + return stackitem.Null{}, nil + } + + var items = make([]stackitem.Item, 0, len(in)) + for i, v := range in { + itm, err := v.ToStackItem() + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + items = append(items, itm) + } + return stackitem.NewArray(items), nil + }(res.Events) + if err != nil { + return nil, fmt.Errorf("field Events: %w", err) + } + items = append(items, itm) + + return stackitem.NewStruct(items), nil +} + +// ToSCParameter creates [smartcontract.Parameter] representing ManagementABI. +// It implements [smartcontract.Convertible] interface so that ManagementABI +// could be used with invokers. +func (res *ManagementABI) ToSCParameter() (smartcontract.Parameter, error) { + if res == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var ( + err error + prm smartcontract.Parameter + prms = make([]smartcontract.Parameter, 0, 2) + ) + prm, err = func(in []*ManagementMethod) (smartcontract.Parameter, error) { + if in == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var prms = make([]smartcontract.Parameter, 0, len(in)) + for i, v := range in { + prm, err := v.ToSCParameter() + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) + } + prms = append(prms, prm) + } + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil + }(res.Methods) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Methods: %w", err) + } + prms = append(prms, prm) + + prm, err = func(in []*ManagementEvent) (smartcontract.Parameter, error) { + if in == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var prms = make([]smartcontract.Parameter, 0, len(in)) + for i, v := range in { + prm, err := v.ToSCParameter() + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) + } + prms = append(prms, prm) + } + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil + }(res.Events) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Events: %w", err) + } + prms = append(prms, prm) + + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil +} + +// itemToManagementContract converts stack item into *ManagementContract. +// NULL item is returned as nil pointer without error. +func itemToManagementContract(item stackitem.Item, err error) (*ManagementContract, error) { + if err != nil { + return nil, err + } + _, null := item.(stackitem.Null) + if null { + return nil, nil + } + var res = new(ManagementContract) + err = res.FromStackItem(item) + return res, err +} + +// Ensure *ManagementContract is a proper [stackitem.Convertible]. +var _ = stackitem.Convertible(&ManagementContract{}) + +// Ensure *ManagementContract is a proper [smartcontract.Convertible]. +var _ = smartcontract.Convertible(&ManagementContract{}) + +// FromStackItem retrieves fields of ManagementContract from the given +// [stackitem.Item] or returns an error if it's not possible to do to so. +// It implements [stackitem.Convertible] interface. +func (res *ManagementContract) FromStackItem(item stackitem.Item) error { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 5 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + res.ID, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field ID: %w", err) + } + + index++ + res.UpdateCounter, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field UpdateCounter: %w", err) + } + + index++ + res.Hash, err = func(item stackitem.Item) (util.Uint160, error) { + b, err := item.TryBytes() + if err != nil { + return util.Uint160{}, err + } + u, err := util.Uint160DecodeBytesBE(b) + if err != nil { + return util.Uint160{}, err + } + return u, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field Hash: %w", err) + } + + index++ + res.NEF, err = arr[index].TryBytes() + if err != nil { + return fmt.Errorf("field NEF: %w", err) + } + + index++ + res.Manifest, err = itemToManagementManifest(arr[index], nil) + if err != nil { + return fmt.Errorf("field Manifest: %w", err) + } + + return nil +} + +// ToStackItem creates [stackitem.Item] representing ManagementContract. +// It implements [stackitem.Convertible] interface. +func (res *ManagementContract) ToStackItem() (stackitem.Item, error) { + if res == nil { + return stackitem.Null{}, nil + } + + var ( + err error + itm stackitem.Item + items = make([]stackitem.Item, 0, 5) + ) + itm, err = (*stackitem.BigInteger)(res.ID), error(nil) + if err != nil { + return nil, fmt.Errorf("field ID: %w", err) + } + items = append(items, itm) + + itm, err = (*stackitem.BigInteger)(res.UpdateCounter), error(nil) + if err != nil { + return nil, fmt.Errorf("field UpdateCounter: %w", err) + } + items = append(items, itm) + + itm, err = stackitem.NewByteArray(res.Hash.BytesBE()), error(nil) + if err != nil { + return nil, fmt.Errorf("field Hash: %w", err) + } + items = append(items, itm) + + itm, err = stackitem.NewByteArray(res.NEF), error(nil) + if err != nil { + return nil, fmt.Errorf("field NEF: %w", err) + } + items = append(items, itm) + + itm, err = res.Manifest.ToStackItem() + if err != nil { + return nil, fmt.Errorf("field Manifest: %w", err) + } + items = append(items, itm) + + return stackitem.NewStruct(items), nil +} + +// ToSCParameter creates [smartcontract.Parameter] representing ManagementContract. +// It implements [smartcontract.Convertible] interface so that ManagementContract +// could be used with invokers. +func (res *ManagementContract) ToSCParameter() (smartcontract.Parameter, error) { + if res == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var ( + err error + prm smartcontract.Parameter + prms = make([]smartcontract.Parameter, 0, 5) + ) + prm, err = smartcontract.NewParameterFromValue(res.ID) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field ID: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.UpdateCounter) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field UpdateCounter: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.Hash) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Hash: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.NEF) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field NEF: %w", err) + } + prms = append(prms, prm) + + prm, err = res.Manifest.ToSCParameter() + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Manifest: %w", err) + } + prms = append(prms, prm) + + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil +} + +// itemToManagementEvent converts stack item into *ManagementEvent. +// NULL item is returned as nil pointer without error. +func itemToManagementEvent(item stackitem.Item, err error) (*ManagementEvent, error) { + if err != nil { + return nil, err + } + _, null := item.(stackitem.Null) + if null { + return nil, nil + } + var res = new(ManagementEvent) + err = res.FromStackItem(item) + return res, err +} + +// Ensure *ManagementEvent is a proper [stackitem.Convertible]. +var _ = stackitem.Convertible(&ManagementEvent{}) + +// Ensure *ManagementEvent is a proper [smartcontract.Convertible]. +var _ = smartcontract.Convertible(&ManagementEvent{}) + +// FromStackItem retrieves fields of ManagementEvent from the given +// [stackitem.Item] or returns an error if it's not possible to do to so. +// It implements [stackitem.Convertible] interface. +func (res *ManagementEvent) FromStackItem(item stackitem.Item) error { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 2 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + res.Name, err = func(item stackitem.Item) (string, error) { + b, err := item.TryBytes() + if err != nil { + return "", err + } + if !utf8.Valid(b) { + return "", errors.New("not a UTF-8 string") + } + return string(b), nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field Name: %w", err) + } + + index++ + res.Params, err = func(item stackitem.Item) ([]*ManagementParameter, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([]*ManagementParameter, len(arr)) + for i := range res { + res[i], err = itemToManagementParameter(arr[i], nil) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field Params: %w", err) + } + + return nil +} + +// ToStackItem creates [stackitem.Item] representing ManagementEvent. +// It implements [stackitem.Convertible] interface. +func (res *ManagementEvent) ToStackItem() (stackitem.Item, error) { + if res == nil { + return stackitem.Null{}, nil + } + + var ( + err error + itm stackitem.Item + items = make([]stackitem.Item, 0, 2) + ) + itm, err = stackitem.NewByteArray([]byte(res.Name)), error(nil) + if err != nil { + return nil, fmt.Errorf("field Name: %w", err) + } + items = append(items, itm) + + itm, err = func(in []*ManagementParameter) (stackitem.Item, error) { + if in == nil { + return stackitem.Null{}, nil + } + + var items = make([]stackitem.Item, 0, len(in)) + for i, v := range in { + itm, err := v.ToStackItem() + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + items = append(items, itm) + } + return stackitem.NewArray(items), nil + }(res.Params) + if err != nil { + return nil, fmt.Errorf("field Params: %w", err) + } + items = append(items, itm) + + return stackitem.NewStruct(items), nil +} + +// ToSCParameter creates [smartcontract.Parameter] representing ManagementEvent. +// It implements [smartcontract.Convertible] interface so that ManagementEvent +// could be used with invokers. +func (res *ManagementEvent) ToSCParameter() (smartcontract.Parameter, error) { + if res == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var ( + err error + prm smartcontract.Parameter + prms = make([]smartcontract.Parameter, 0, 2) + ) + prm, err = smartcontract.NewParameterFromValue(res.Name) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Name: %w", err) + } + prms = append(prms, prm) + + prm, err = func(in []*ManagementParameter) (smartcontract.Parameter, error) { + if in == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var prms = make([]smartcontract.Parameter, 0, len(in)) + for i, v := range in { + prm, err := v.ToSCParameter() + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) + } + prms = append(prms, prm) + } + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil + }(res.Params) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Params: %w", err) + } + prms = append(prms, prm) + + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil +} + +// itemToManagementGroup converts stack item into *ManagementGroup. +// NULL item is returned as nil pointer without error. +func itemToManagementGroup(item stackitem.Item, err error) (*ManagementGroup, error) { + if err != nil { + return nil, err + } + _, null := item.(stackitem.Null) + if null { + return nil, nil + } + var res = new(ManagementGroup) + err = res.FromStackItem(item) + return res, err +} + +// Ensure *ManagementGroup is a proper [stackitem.Convertible]. +var _ = stackitem.Convertible(&ManagementGroup{}) + +// Ensure *ManagementGroup is a proper [smartcontract.Convertible]. +var _ = smartcontract.Convertible(&ManagementGroup{}) + +// FromStackItem retrieves fields of ManagementGroup from the given +// [stackitem.Item] or returns an error if it's not possible to do to so. +// It implements [stackitem.Convertible] interface. +func (res *ManagementGroup) FromStackItem(item stackitem.Item) error { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 2 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + res.PublicKey, err = func(item stackitem.Item) (*keys.PublicKey, error) { + b, err := item.TryBytes() + if err != nil { + return nil, err + } + k, err := keys.NewPublicKeyFromBytes(b, elliptic.P256()) + if err != nil { + return nil, err + } + return k, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field PublicKey: %w", err) + } + + index++ + res.Signature, err = arr[index].TryBytes() + if err != nil { + return fmt.Errorf("field Signature: %w", err) + } + + return nil +} + +// ToStackItem creates [stackitem.Item] representing ManagementGroup. +// It implements [stackitem.Convertible] interface. +func (res *ManagementGroup) ToStackItem() (stackitem.Item, error) { + if res == nil { + return stackitem.Null{}, nil + } + + var ( + err error + itm stackitem.Item + items = make([]stackitem.Item, 0, 2) + ) + itm, err = stackitem.NewByteArray(res.PublicKey.Bytes()), error(nil) + if err != nil { + return nil, fmt.Errorf("field PublicKey: %w", err) + } + items = append(items, itm) + + itm, err = stackitem.NewByteArray(res.Signature), error(nil) + if err != nil { + return nil, fmt.Errorf("field Signature: %w", err) + } + items = append(items, itm) + + return stackitem.NewStruct(items), nil +} + +// ToSCParameter creates [smartcontract.Parameter] representing ManagementGroup. +// It implements [smartcontract.Convertible] interface so that ManagementGroup +// could be used with invokers. +func (res *ManagementGroup) ToSCParameter() (smartcontract.Parameter, error) { + if res == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var ( + err error + prm smartcontract.Parameter + prms = make([]smartcontract.Parameter, 0, 2) + ) + prm, err = smartcontract.NewParameterFromValue(res.PublicKey) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field PublicKey: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.Signature) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Signature: %w", err) + } + prms = append(prms, prm) + + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil +} + +// itemToManagementManifest converts stack item into *ManagementManifest. +// NULL item is returned as nil pointer without error. +func itemToManagementManifest(item stackitem.Item, err error) (*ManagementManifest, error) { + if err != nil { + return nil, err + } + _, null := item.(stackitem.Null) + if null { + return nil, nil + } + var res = new(ManagementManifest) + err = res.FromStackItem(item) + return res, err +} + +// Ensure *ManagementManifest is a proper [stackitem.Convertible]. +var _ = stackitem.Convertible(&ManagementManifest{}) + +// Ensure *ManagementManifest is a proper [smartcontract.Convertible]. +var _ = smartcontract.Convertible(&ManagementManifest{}) + +// FromStackItem retrieves fields of ManagementManifest from the given +// [stackitem.Item] or returns an error if it's not possible to do to so. +// It implements [stackitem.Convertible] interface. +func (res *ManagementManifest) FromStackItem(item stackitem.Item) error { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 8 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + res.Name, err = func(item stackitem.Item) (string, error) { + b, err := item.TryBytes() + if err != nil { + return "", err + } + if !utf8.Valid(b) { + return "", errors.New("not a UTF-8 string") + } + return string(b), nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field Name: %w", err) + } + + index++ + res.Groups, err = func(item stackitem.Item) ([]*ManagementGroup, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([]*ManagementGroup, len(arr)) + for i := range res { + res[i], err = itemToManagementGroup(arr[i], nil) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field Groups: %w", err) + } + + index++ + res.Features, err = func(item stackitem.Item) (map[string]string, error) { + m, ok := item.Value().([]stackitem.MapElement) + if !ok { + return nil, fmt.Errorf("%s is not a map", item.Type().String()) + } + res := make(map[string]string) + for i := range m { + k, err := func(item stackitem.Item) (string, error) { + b, err := item.TryBytes() + if err != nil { + return "", err + } + if !utf8.Valid(b) { + return "", errors.New("not a UTF-8 string") + } + return string(b), nil + }(m[i].Key) + if err != nil { + return nil, fmt.Errorf("key %d: %w", i, err) + } + v, err := func(item stackitem.Item) (string, error) { + b, err := item.TryBytes() + if err != nil { + return "", err + } + if !utf8.Valid(b) { + return "", errors.New("not a UTF-8 string") + } + return string(b), nil + }(m[i].Value) + if err != nil { + return nil, fmt.Errorf("value %d: %w", i, err) + } + res[k] = v + } + return res, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field Features: %w", err) + } + + index++ + res.SupportedStandards, err = func(item stackitem.Item) ([]string, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([]string, len(arr)) + for i := range res { + res[i], err = func(item stackitem.Item) (string, error) { + b, err := item.TryBytes() + if err != nil { + return "", err + } + if !utf8.Valid(b) { + return "", errors.New("not a UTF-8 string") + } + return string(b), nil + }(arr[i]) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field SupportedStandards: %w", err) + } + + index++ + res.ABI, err = itemToManagementABI(arr[index], nil) + if err != nil { + return fmt.Errorf("field ABI: %w", err) + } + + index++ + res.Permissions, err = func(item stackitem.Item) ([]*ManagementPermission, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([]*ManagementPermission, len(arr)) + for i := range res { + res[i], err = itemToManagementPermission(arr[i], nil) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field Permissions: %w", err) + } + + index++ + res.Trusts, err = func(item stackitem.Item) ([]util.Uint160, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([]util.Uint160, len(arr)) + for i := range res { + res[i], err = func(item stackitem.Item) (util.Uint160, error) { + b, err := item.TryBytes() + if err != nil { + return util.Uint160{}, err + } + u, err := util.Uint160DecodeBytesBE(b) + if err != nil { + return util.Uint160{}, err + } + return u, nil + }(arr[i]) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field Trusts: %w", err) + } + + index++ + res.Extra, err = arr[index].Value(), error(nil) + if err != nil { + return fmt.Errorf("field Extra: %w", err) + } + + return nil +} + +// ToStackItem creates [stackitem.Item] representing ManagementManifest. +// It implements [stackitem.Convertible] interface. +func (res *ManagementManifest) ToStackItem() (stackitem.Item, error) { + if res == nil { + return stackitem.Null{}, nil + } + + var ( + err error + itm stackitem.Item + items = make([]stackitem.Item, 0, 8) + ) + itm, err = stackitem.NewByteArray([]byte(res.Name)), error(nil) + if err != nil { + return nil, fmt.Errorf("field Name: %w", err) + } + items = append(items, itm) + + itm, err = func(in []*ManagementGroup) (stackitem.Item, error) { + if in == nil { + return stackitem.Null{}, nil + } + + var items = make([]stackitem.Item, 0, len(in)) + for i, v := range in { + itm, err := v.ToStackItem() + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + items = append(items, itm) + } + return stackitem.NewArray(items), nil + }(res.Groups) + if err != nil { + return nil, fmt.Errorf("field Groups: %w", err) + } + items = append(items, itm) + + itm, err = func(in map[string]string) (stackitem.Item, error) { + if in == nil { + return stackitem.Null{}, nil + } + + var m = stackitem.NewMap() + for k, v := range in { + iKey, err := stackitem.NewByteArray([]byte(k)), error(nil) + if err != nil { + return nil, fmt.Errorf("key %v: %w", k, err) + } + iVal, err := stackitem.NewByteArray([]byte(v)), error(nil) + if err != nil { + return nil, fmt.Errorf("key %v, wrong value: %w", k, err) + } + m.Add(iKey, iVal) + } + return m, nil + }(res.Features) + if err != nil { + return nil, fmt.Errorf("field Features: %w", err) + } + items = append(items, itm) + + itm, err = func(in []string) (stackitem.Item, error) { + if in == nil { + return stackitem.Null{}, nil + } + + var items = make([]stackitem.Item, 0, len(in)) + for i, v := range in { + itm, err := stackitem.NewByteArray([]byte(v)), error(nil) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + items = append(items, itm) + } + return stackitem.NewArray(items), nil + }(res.SupportedStandards) + if err != nil { + return nil, fmt.Errorf("field SupportedStandards: %w", err) + } + items = append(items, itm) + + itm, err = res.ABI.ToStackItem() + if err != nil { + return nil, fmt.Errorf("field ABI: %w", err) + } + items = append(items, itm) + + itm, err = func(in []*ManagementPermission) (stackitem.Item, error) { + if in == nil { + return stackitem.Null{}, nil + } + + var items = make([]stackitem.Item, 0, len(in)) + for i, v := range in { + itm, err := v.ToStackItem() + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + items = append(items, itm) + } + return stackitem.NewArray(items), nil + }(res.Permissions) + if err != nil { + return nil, fmt.Errorf("field Permissions: %w", err) + } + items = append(items, itm) + + itm, err = func(in []util.Uint160) (stackitem.Item, error) { + if in == nil { + return stackitem.Null{}, nil + } + + var items = make([]stackitem.Item, 0, len(in)) + for i, v := range in { + itm, err := stackitem.NewByteArray(v.BytesBE()), error(nil) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + items = append(items, itm) + } + return stackitem.NewArray(items), nil + }(res.Trusts) + if err != nil { + return nil, fmt.Errorf("field Trusts: %w", err) + } + items = append(items, itm) + + itm, err = stackitem.TryMake(res.Extra) + if err != nil { + return nil, fmt.Errorf("field Extra: %w", err) + } + items = append(items, itm) + + return stackitem.NewStruct(items), nil +} + +// ToSCParameter creates [smartcontract.Parameter] representing ManagementManifest. +// It implements [smartcontract.Convertible] interface so that ManagementManifest +// could be used with invokers. +func (res *ManagementManifest) ToSCParameter() (smartcontract.Parameter, error) { + if res == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var ( + err error + prm smartcontract.Parameter + prms = make([]smartcontract.Parameter, 0, 8) + ) + prm, err = smartcontract.NewParameterFromValue(res.Name) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Name: %w", err) + } + prms = append(prms, prm) + + prm, err = func(in []*ManagementGroup) (smartcontract.Parameter, error) { + if in == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var prms = make([]smartcontract.Parameter, 0, len(in)) + for i, v := range in { + prm, err := v.ToSCParameter() + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) + } + prms = append(prms, prm) + } + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil + }(res.Groups) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Groups: %w", err) + } + prms = append(prms, prm) + + prm, err = func(in map[string]string) (smartcontract.Parameter, error) { + if in == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var prms = make([]smartcontract.ParameterPair, 0, len(in)) + for k, v := range in { + iKey, err := smartcontract.NewParameterFromValue(k) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("key %v: %w", k, err) + } + iVal, err := smartcontract.NewParameterFromValue(v) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("key %v, wrong value: %w", k, err) + } + prms = append(prms, smartcontract.ParameterPair{Key: iKey, Value: iVal}) + } + return smartcontract.Parameter{Type: smartcontract.MapType, Value: prms}, nil + }(res.Features) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Features: %w", err) + } + prms = append(prms, prm) + + prm, err = func(in []string) (smartcontract.Parameter, error) { + if in == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var prms = make([]smartcontract.Parameter, 0, len(in)) + for i, v := range in { + prm, err := smartcontract.NewParameterFromValue(v) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) + } + prms = append(prms, prm) + } + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil + }(res.SupportedStandards) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field SupportedStandards: %w", err) + } + prms = append(prms, prm) + + prm, err = res.ABI.ToSCParameter() + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field ABI: %w", err) + } + prms = append(prms, prm) + + prm, err = func(in []*ManagementPermission) (smartcontract.Parameter, error) { + if in == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var prms = make([]smartcontract.Parameter, 0, len(in)) + for i, v := range in { + prm, err := v.ToSCParameter() + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) + } + prms = append(prms, prm) + } + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil + }(res.Permissions) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Permissions: %w", err) + } + prms = append(prms, prm) + + prm, err = func(in []util.Uint160) (smartcontract.Parameter, error) { + if in == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var prms = make([]smartcontract.Parameter, 0, len(in)) + for i, v := range in { + prm, err := smartcontract.NewParameterFromValue(v) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) + } + prms = append(prms, prm) + } + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil + }(res.Trusts) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Trusts: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.Extra) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Extra: %w", err) + } + prms = append(prms, prm) + + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil +} + +// itemToManagementMethod converts stack item into *ManagementMethod. +// NULL item is returned as nil pointer without error. +func itemToManagementMethod(item stackitem.Item, err error) (*ManagementMethod, error) { + if err != nil { + return nil, err + } + _, null := item.(stackitem.Null) + if null { + return nil, nil + } + var res = new(ManagementMethod) + err = res.FromStackItem(item) + return res, err +} + +// Ensure *ManagementMethod is a proper [stackitem.Convertible]. +var _ = stackitem.Convertible(&ManagementMethod{}) + +// Ensure *ManagementMethod is a proper [smartcontract.Convertible]. +var _ = smartcontract.Convertible(&ManagementMethod{}) + +// FromStackItem retrieves fields of ManagementMethod from the given +// [stackitem.Item] or returns an error if it's not possible to do to so. +// It implements [stackitem.Convertible] interface. +func (res *ManagementMethod) FromStackItem(item stackitem.Item) error { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 5 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + res.Name, err = func(item stackitem.Item) (string, error) { + b, err := item.TryBytes() + if err != nil { + return "", err + } + if !utf8.Valid(b) { + return "", errors.New("not a UTF-8 string") + } + return string(b), nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field Name: %w", err) + } + + index++ + res.Params, err = func(item stackitem.Item) ([]*ManagementParameter, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([]*ManagementParameter, len(arr)) + for i := range res { + res[i], err = itemToManagementParameter(arr[i], nil) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field Params: %w", err) + } + + index++ + res.ReturnType, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field ReturnType: %w", err) + } + + index++ + res.Offset, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field Offset: %w", err) + } + + index++ + res.Safe, err = arr[index].TryBool() + if err != nil { + return fmt.Errorf("field Safe: %w", err) + } + + return nil +} + +// ToStackItem creates [stackitem.Item] representing ManagementMethod. +// It implements [stackitem.Convertible] interface. +func (res *ManagementMethod) ToStackItem() (stackitem.Item, error) { + if res == nil { + return stackitem.Null{}, nil + } + + var ( + err error + itm stackitem.Item + items = make([]stackitem.Item, 0, 5) + ) + itm, err = stackitem.NewByteArray([]byte(res.Name)), error(nil) + if err != nil { + return nil, fmt.Errorf("field Name: %w", err) + } + items = append(items, itm) + + itm, err = func(in []*ManagementParameter) (stackitem.Item, error) { + if in == nil { + return stackitem.Null{}, nil + } + + var items = make([]stackitem.Item, 0, len(in)) + for i, v := range in { + itm, err := v.ToStackItem() + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + items = append(items, itm) + } + return stackitem.NewArray(items), nil + }(res.Params) + if err != nil { + return nil, fmt.Errorf("field Params: %w", err) + } + items = append(items, itm) + + itm, err = (*stackitem.BigInteger)(res.ReturnType), error(nil) + if err != nil { + return nil, fmt.Errorf("field ReturnType: %w", err) + } + items = append(items, itm) + + itm, err = (*stackitem.BigInteger)(res.Offset), error(nil) + if err != nil { + return nil, fmt.Errorf("field Offset: %w", err) + } + items = append(items, itm) + + itm, err = stackitem.NewBool(res.Safe), error(nil) + if err != nil { + return nil, fmt.Errorf("field Safe: %w", err) + } + items = append(items, itm) + + return stackitem.NewStruct(items), nil +} + +// ToSCParameter creates [smartcontract.Parameter] representing ManagementMethod. +// It implements [smartcontract.Convertible] interface so that ManagementMethod +// could be used with invokers. +func (res *ManagementMethod) ToSCParameter() (smartcontract.Parameter, error) { + if res == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var ( + err error + prm smartcontract.Parameter + prms = make([]smartcontract.Parameter, 0, 5) + ) + prm, err = smartcontract.NewParameterFromValue(res.Name) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Name: %w", err) + } + prms = append(prms, prm) + + prm, err = func(in []*ManagementParameter) (smartcontract.Parameter, error) { + if in == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var prms = make([]smartcontract.Parameter, 0, len(in)) + for i, v := range in { + prm, err := v.ToSCParameter() + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) + } + prms = append(prms, prm) + } + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil + }(res.Params) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Params: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.ReturnType) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field ReturnType: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.Offset) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Offset: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.Safe) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Safe: %w", err) + } + prms = append(prms, prm) + + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil +} + +// itemToManagementParameter converts stack item into *ManagementParameter. +// NULL item is returned as nil pointer without error. +func itemToManagementParameter(item stackitem.Item, err error) (*ManagementParameter, error) { + if err != nil { + return nil, err + } + _, null := item.(stackitem.Null) + if null { + return nil, nil + } + var res = new(ManagementParameter) + err = res.FromStackItem(item) + return res, err +} + +// Ensure *ManagementParameter is a proper [stackitem.Convertible]. +var _ = stackitem.Convertible(&ManagementParameter{}) + +// Ensure *ManagementParameter is a proper [smartcontract.Convertible]. +var _ = smartcontract.Convertible(&ManagementParameter{}) + +// FromStackItem retrieves fields of ManagementParameter from the given +// [stackitem.Item] or returns an error if it's not possible to do to so. +// It implements [stackitem.Convertible] interface. +func (res *ManagementParameter) FromStackItem(item stackitem.Item) error { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 2 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + res.Name, err = func(item stackitem.Item) (string, error) { + b, err := item.TryBytes() + if err != nil { + return "", err + } + if !utf8.Valid(b) { + return "", errors.New("not a UTF-8 string") + } + return string(b), nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field Name: %w", err) + } + + index++ + res.Type, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field Type: %w", err) + } + + return nil +} + +// ToStackItem creates [stackitem.Item] representing ManagementParameter. +// It implements [stackitem.Convertible] interface. +func (res *ManagementParameter) ToStackItem() (stackitem.Item, error) { + if res == nil { + return stackitem.Null{}, nil + } + + var ( + err error + itm stackitem.Item + items = make([]stackitem.Item, 0, 2) + ) + itm, err = stackitem.NewByteArray([]byte(res.Name)), error(nil) + if err != nil { + return nil, fmt.Errorf("field Name: %w", err) + } + items = append(items, itm) + + itm, err = (*stackitem.BigInteger)(res.Type), error(nil) + if err != nil { + return nil, fmt.Errorf("field Type: %w", err) + } + items = append(items, itm) + + return stackitem.NewStruct(items), nil +} + +// ToSCParameter creates [smartcontract.Parameter] representing ManagementParameter. +// It implements [smartcontract.Convertible] interface so that ManagementParameter +// could be used with invokers. +func (res *ManagementParameter) ToSCParameter() (smartcontract.Parameter, error) { + if res == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var ( + err error + prm smartcontract.Parameter + prms = make([]smartcontract.Parameter, 0, 2) + ) + prm, err = smartcontract.NewParameterFromValue(res.Name) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Name: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.Type) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Type: %w", err) + } + prms = append(prms, prm) + + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil +} + +// itemToManagementPermission converts stack item into *ManagementPermission. +// NULL item is returned as nil pointer without error. +func itemToManagementPermission(item stackitem.Item, err error) (*ManagementPermission, error) { + if err != nil { + return nil, err + } + _, null := item.(stackitem.Null) + if null { + return nil, nil + } + var res = new(ManagementPermission) + err = res.FromStackItem(item) + return res, err +} + +// Ensure *ManagementPermission is a proper [stackitem.Convertible]. +var _ = stackitem.Convertible(&ManagementPermission{}) + +// Ensure *ManagementPermission is a proper [smartcontract.Convertible]. +var _ = smartcontract.Convertible(&ManagementPermission{}) + +// FromStackItem retrieves fields of ManagementPermission from the given +// [stackitem.Item] or returns an error if it's not possible to do to so. +// It implements [stackitem.Convertible] interface. +func (res *ManagementPermission) FromStackItem(item stackitem.Item) error { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 2 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + res.Contract, err = func(item stackitem.Item) (util.Uint160, error) { + b, err := item.TryBytes() + if err != nil { + return util.Uint160{}, err + } + u, err := util.Uint160DecodeBytesBE(b) + if err != nil { + return util.Uint160{}, err + } + return u, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field Contract: %w", err) + } + + index++ + res.Methods, err = func(item stackitem.Item) ([]string, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([]string, len(arr)) + for i := range res { + res[i], err = func(item stackitem.Item) (string, error) { + b, err := item.TryBytes() + if err != nil { + return "", err + } + if !utf8.Valid(b) { + return "", errors.New("not a UTF-8 string") + } + return string(b), nil + }(arr[i]) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field Methods: %w", err) + } + + return nil +} + +// ToStackItem creates [stackitem.Item] representing ManagementPermission. +// It implements [stackitem.Convertible] interface. +func (res *ManagementPermission) ToStackItem() (stackitem.Item, error) { + if res == nil { + return stackitem.Null{}, nil + } + + var ( + err error + itm stackitem.Item + items = make([]stackitem.Item, 0, 2) + ) + itm, err = stackitem.NewByteArray(res.Contract.BytesBE()), error(nil) + if err != nil { + return nil, fmt.Errorf("field Contract: %w", err) + } + items = append(items, itm) + + itm, err = func(in []string) (stackitem.Item, error) { + if in == nil { + return stackitem.Null{}, nil + } + + var items = make([]stackitem.Item, 0, len(in)) + for i, v := range in { + itm, err := stackitem.NewByteArray([]byte(v)), error(nil) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + items = append(items, itm) + } + return stackitem.NewArray(items), nil + }(res.Methods) + if err != nil { + return nil, fmt.Errorf("field Methods: %w", err) + } + items = append(items, itm) + + return stackitem.NewStruct(items), nil +} + +// ToSCParameter creates [smartcontract.Parameter] representing ManagementPermission. +// It implements [smartcontract.Convertible] interface so that ManagementPermission +// could be used with invokers. +func (res *ManagementPermission) ToSCParameter() (smartcontract.Parameter, error) { + if res == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var ( + err error + prm smartcontract.Parameter + prms = make([]smartcontract.Parameter, 0, 2) + ) + prm, err = smartcontract.NewParameterFromValue(res.Contract) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Contract: %w", err) + } + prms = append(prms, prm) + + prm, err = func(in []string) (smartcontract.Parameter, error) { + if in == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var prms = make([]smartcontract.Parameter, 0, len(in)) + for i, v := range in { + prm, err := smartcontract.NewParameterFromValue(v) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) + } + prms = append(prms, prm) + } + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil + }(res.Methods) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Methods: %w", err) + } + prms = append(prms, prm) + + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil +} + +// itemToStructsInternal converts stack item into *StructsInternal. +// NULL item is returned as nil pointer without error. +func itemToStructsInternal(item stackitem.Item, err error) (*StructsInternal, error) { + if err != nil { + return nil, err + } + _, null := item.(stackitem.Null) + if null { + return nil, nil + } + var res = new(StructsInternal) + err = res.FromStackItem(item) + return res, err +} + +// Ensure *StructsInternal is a proper [stackitem.Convertible]. +var _ = stackitem.Convertible(&StructsInternal{}) + +// Ensure *StructsInternal is a proper [smartcontract.Convertible]. +var _ = smartcontract.Convertible(&StructsInternal{}) + +// FromStackItem retrieves fields of StructsInternal from the given +// [stackitem.Item] or returns an error if it's not possible to do to so. +// It implements [stackitem.Convertible] interface. +func (res *StructsInternal) FromStackItem(item stackitem.Item) error { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 14 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + res.Bool, err = arr[index].TryBool() + if err != nil { + return fmt.Errorf("field Bool: %w", err) + } + + index++ + res.Int, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field Int: %w", err) + } + + index++ + res.Bytes, err = arr[index].TryBytes() + if err != nil { + return fmt.Errorf("field Bytes: %w", err) + } + + index++ + res.String, err = func(item stackitem.Item) (string, error) { + b, err := item.TryBytes() + if err != nil { + return "", err + } + if !utf8.Valid(b) { + return "", errors.New("not a UTF-8 string") + } + return string(b), nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field String: %w", err) + } + + index++ + res.H160, err = func(item stackitem.Item) (util.Uint160, error) { + b, err := item.TryBytes() + if err != nil { + return util.Uint160{}, err + } + u, err := util.Uint160DecodeBytesBE(b) + if err != nil { + return util.Uint160{}, err + } + return u, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field H160: %w", err) + } + + index++ + res.H256, err = func(item stackitem.Item) (util.Uint256, error) { + b, err := item.TryBytes() + if err != nil { + return util.Uint256{}, err + } + u, err := util.Uint256DecodeBytesBE(b) + if err != nil { + return util.Uint256{}, err + } + return u, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field H256: %w", err) + } + + index++ + res.PK, err = func(item stackitem.Item) (*keys.PublicKey, error) { + b, err := item.TryBytes() + if err != nil { + return nil, err + } + k, err := keys.NewPublicKeyFromBytes(b, elliptic.P256()) + if err != nil { + return nil, err + } + return k, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field PK: %w", err) + } + + index++ + res.PubKey, err = func(item stackitem.Item) (*keys.PublicKey, error) { + b, err := item.TryBytes() + if err != nil { + return nil, err + } + k, err := keys.NewPublicKeyFromBytes(b, elliptic.P256()) + if err != nil { + return nil, err + } + return k, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field PubKey: %w", err) + } + + index++ + res.Sign, err = arr[index].TryBytes() + if err != nil { + return fmt.Errorf("field Sign: %w", err) + } + + index++ + res.ArrOfBytes, err = func(item stackitem.Item) ([][]byte, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([][]byte, len(arr)) + for i := range res { + res[i], err = arr[i].TryBytes() + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field ArrOfBytes: %w", err) + } + + index++ + res.ArrOfH160, err = func(item stackitem.Item) ([]util.Uint160, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([]util.Uint160, len(arr)) + for i := range res { + res[i], err = func(item stackitem.Item) (util.Uint160, error) { + b, err := item.TryBytes() + if err != nil { + return util.Uint160{}, err + } + u, err := util.Uint160DecodeBytesBE(b) + if err != nil { + return util.Uint160{}, err + } + return u, nil + }(arr[i]) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field ArrOfH160: %w", err) + } + + index++ + res.Map, err = func(item stackitem.Item) (map[*big.Int]keys.PublicKeys, error) { + m, ok := item.Value().([]stackitem.MapElement) + if !ok { + return nil, fmt.Errorf("%s is not a map", item.Type().String()) + } + res := make(map[*big.Int]keys.PublicKeys) + for i := range m { + k, err := m[i].Key.TryInteger() + if err != nil { + return nil, fmt.Errorf("key %d: %w", i, err) + } + v, err := func(item stackitem.Item) (keys.PublicKeys, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make(keys.PublicKeys, len(arr)) + for i := range res { + res[i], err = func(item stackitem.Item) (*keys.PublicKey, error) { + b, err := item.TryBytes() + if err != nil { + return nil, err + } + k, err := keys.NewPublicKeyFromBytes(b, elliptic.P256()) + if err != nil { + return nil, err + } + return k, nil + }(arr[i]) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(m[i].Value) + if err != nil { + return nil, fmt.Errorf("value %d: %w", i, err) + } + res[k] = v + } + return res, nil + }(arr[index]) + if err != nil { + return fmt.Errorf("field Map: %w", err) + } + + index++ + res.Struct, err = itemToStructsInternal(arr[index], nil) + if err != nil { + return fmt.Errorf("field Struct: %w", err) + } + + index++ + res.UnexportedField, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field UnexportedField: %w", err) + } + + return nil +} + +// ToStackItem creates [stackitem.Item] representing StructsInternal. +// It implements [stackitem.Convertible] interface. +func (res *StructsInternal) ToStackItem() (stackitem.Item, error) { + if res == nil { + return stackitem.Null{}, nil + } + + var ( + err error + itm stackitem.Item + items = make([]stackitem.Item, 0, 14) + ) + itm, err = stackitem.NewBool(res.Bool), error(nil) + if err != nil { + return nil, fmt.Errorf("field Bool: %w", err) + } + items = append(items, itm) + + itm, err = (*stackitem.BigInteger)(res.Int), error(nil) + if err != nil { + return nil, fmt.Errorf("field Int: %w", err) + } + items = append(items, itm) + + itm, err = stackitem.NewByteArray(res.Bytes), error(nil) + if err != nil { + return nil, fmt.Errorf("field Bytes: %w", err) + } + items = append(items, itm) + + itm, err = stackitem.NewByteArray([]byte(res.String)), error(nil) + if err != nil { + return nil, fmt.Errorf("field String: %w", err) + } + items = append(items, itm) + + itm, err = stackitem.NewByteArray(res.H160.BytesBE()), error(nil) + if err != nil { + return nil, fmt.Errorf("field H160: %w", err) + } + items = append(items, itm) + + itm, err = stackitem.NewByteArray(res.H256.BytesBE()), error(nil) + if err != nil { + return nil, fmt.Errorf("field H256: %w", err) + } + items = append(items, itm) + + itm, err = stackitem.NewByteArray(res.PK.Bytes()), error(nil) + if err != nil { + return nil, fmt.Errorf("field PK: %w", err) + } + items = append(items, itm) + + itm, err = stackitem.NewByteArray(res.PubKey.Bytes()), error(nil) + if err != nil { + return nil, fmt.Errorf("field PubKey: %w", err) + } + items = append(items, itm) + + itm, err = stackitem.NewByteArray(res.Sign), error(nil) + if err != nil { + return nil, fmt.Errorf("field Sign: %w", err) + } + items = append(items, itm) + + itm, err = func(in [][]byte) (stackitem.Item, error) { + if in == nil { + return stackitem.Null{}, nil + } + + var items = make([]stackitem.Item, 0, len(in)) + for i, v := range in { + itm, err := stackitem.NewByteArray(v), error(nil) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + items = append(items, itm) + } + return stackitem.NewArray(items), nil + }(res.ArrOfBytes) + if err != nil { + return nil, fmt.Errorf("field ArrOfBytes: %w", err) + } + items = append(items, itm) + + itm, err = func(in []util.Uint160) (stackitem.Item, error) { + if in == nil { + return stackitem.Null{}, nil + } + + var items = make([]stackitem.Item, 0, len(in)) + for i, v := range in { + itm, err := stackitem.NewByteArray(v.BytesBE()), error(nil) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + items = append(items, itm) + } + return stackitem.NewArray(items), nil + }(res.ArrOfH160) + if err != nil { + return nil, fmt.Errorf("field ArrOfH160: %w", err) + } + items = append(items, itm) + + itm, err = func(in map[*big.Int]keys.PublicKeys) (stackitem.Item, error) { + if in == nil { + return stackitem.Null{}, nil + } + + var m = stackitem.NewMap() + for k, v := range in { + iKey, err := (*stackitem.BigInteger)(k), error(nil) + if err != nil { + return nil, fmt.Errorf("key %v: %w", k, err) + } + iVal, err := func(in keys.PublicKeys) (stackitem.Item, error) { + if in == nil { + return stackitem.Null{}, nil + } + + var items = make([]stackitem.Item, 0, len(in)) + for i, v := range in { + itm, err := stackitem.NewByteArray(v.Bytes()), error(nil) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + items = append(items, itm) + } + return stackitem.NewArray(items), nil + }(v) + if err != nil { + return nil, fmt.Errorf("key %v, wrong value: %w", k, err) + } + m.Add(iKey, iVal) + } + return m, nil + }(res.Map) + if err != nil { + return nil, fmt.Errorf("field Map: %w", err) + } + items = append(items, itm) + + itm, err = res.Struct.ToStackItem() + if err != nil { + return nil, fmt.Errorf("field Struct: %w", err) + } + items = append(items, itm) + + itm, err = (*stackitem.BigInteger)(res.UnexportedField), error(nil) + if err != nil { + return nil, fmt.Errorf("field UnexportedField: %w", err) + } + items = append(items, itm) + + return stackitem.NewStruct(items), nil +} + +// ToSCParameter creates [smartcontract.Parameter] representing StructsInternal. +// It implements [smartcontract.Convertible] interface so that StructsInternal +// could be used with invokers. +func (res *StructsInternal) ToSCParameter() (smartcontract.Parameter, error) { + if res == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var ( + err error + prm smartcontract.Parameter + prms = make([]smartcontract.Parameter, 0, 14) + ) + prm, err = smartcontract.NewParameterFromValue(res.Bool) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Bool: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.Int) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Int: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.Bytes) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Bytes: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.String) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field String: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.H160) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field H160: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.H256) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field H256: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.PK) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field PK: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.PubKey) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field PubKey: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.Sign) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Sign: %w", err) + } + prms = append(prms, prm) + + prm, err = func(in [][]byte) (smartcontract.Parameter, error) { + if in == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var prms = make([]smartcontract.Parameter, 0, len(in)) + for i, v := range in { + prm, err := smartcontract.NewParameterFromValue(v) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) + } + prms = append(prms, prm) + } + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil + }(res.ArrOfBytes) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field ArrOfBytes: %w", err) + } + prms = append(prms, prm) + + prm, err = func(in []util.Uint160) (smartcontract.Parameter, error) { + if in == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var prms = make([]smartcontract.Parameter, 0, len(in)) + for i, v := range in { + prm, err := smartcontract.NewParameterFromValue(v) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) + } + prms = append(prms, prm) + } + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil + }(res.ArrOfH160) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field ArrOfH160: %w", err) + } + prms = append(prms, prm) + + prm, err = func(in map[*big.Int]keys.PublicKeys) (smartcontract.Parameter, error) { + if in == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var prms = make([]smartcontract.ParameterPair, 0, len(in)) + for k, v := range in { + iKey, err := smartcontract.NewParameterFromValue(k) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("key %v: %w", k, err) + } + iVal, err := func(in keys.PublicKeys) (smartcontract.Parameter, error) { + if in == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var prms = make([]smartcontract.Parameter, 0, len(in)) + for i, v := range in { + prm, err := smartcontract.NewParameterFromValue(v) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("item %d: %w", i, err) + } + prms = append(prms, prm) + } + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil + }(v) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("key %v, wrong value: %w", k, err) + } + prms = append(prms, smartcontract.ParameterPair{Key: iKey, Value: iVal}) + } + return smartcontract.Parameter{Type: smartcontract.MapType, Value: prms}, nil + }(res.Map) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Map: %w", err) + } + prms = append(prms, prm) + + prm, err = res.Struct.ToSCParameter() + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field Struct: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.UnexportedField) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field UnexportedField: %w", err) + } + prms = append(prms, prm) + + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil +} diff --git a/cli/smartcontract/rpcbindings/structs/rpcbindings/rpcbindings_test.go b/cli/smartcontract/rpcbindings/structs/rpcbindings/rpcbindings_test.go index 0f8c02f..fef0021 100644 --- a/cli/smartcontract/rpcbindings/structs/rpcbindings/rpcbindings_test.go +++ b/cli/smartcontract/rpcbindings/structs/rpcbindings/rpcbindings_test.go @@ -8,7 +8,7 @@ import ( "errors" "fmt" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient/unwrap" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/util" diff --git a/cli/smartcontract/rpcbindings/types/rpcbindings/dynamic_hash/rpcbindings_test.go b/cli/smartcontract/rpcbindings/types/rpcbindings/dynamic_hash/rpcbindings_test.go index 80261e9..9695484 100644 --- a/cli/smartcontract/rpcbindings/types/rpcbindings/dynamic_hash/rpcbindings_test.go +++ b/cli/smartcontract/rpcbindings/types/rpcbindings/dynamic_hash/rpcbindings_test.go @@ -1,563 +1,563 @@ -// Code generated by neo-go contract generate-rpcwrapper --manifest --out [--hash ] [--config ]; DO NOT EDIT. - -// Package types contains RPC wrappers for Types contract. -package types - -import ( - "errors" - "fmt" - "github.com/tutus-one/tutus-chain/pkg/crypto/keys" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" - "github.com/tutus-one/tutus-chain/pkg/rpcclient/unwrap" - "github.com/tutus-one/tutus-chain/pkg/smartcontract" - "github.com/tutus-one/tutus-chain/pkg/util" - "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" - "math/big" - "unicode/utf8" -) - -// Unnamed is a contract-specific unnamed type used by its methods. -type Unnamed struct { - I *big.Int -} - -// UnnamedX is a contract-specific unnamedX type used by its methods. -type UnnamedX struct { - I *big.Int - B bool -} - -// Invoker is used by ContractReader to call various safe methods. -type Invoker interface { - Call(contract util.Uint160, operation string, params ...any) (*result.Invoke, error) -} - -// ContractReader implements safe contract methods. -type ContractReader struct { - invoker Invoker - hash util.Uint160 -} - -// NewReader creates an instance of ContractReader using provided contract hash and the given Invoker. -func NewReader(invoker Invoker, hash util.Uint160) *ContractReader { - return &ContractReader{invoker, hash} -} - -// AAAStrings invokes `aAAStrings` method of contract. -func (c *ContractReader) AAAStrings(s [][][]string) ([][][]string, error) { - return func(item stackitem.Item, err error) ([][][]string, error) { - if err != nil { - return nil, err - } - return func(item stackitem.Item) ([][][]string, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([][][]string, len(arr)) - for i := range res { - res[i], err = func(item stackitem.Item) ([][]string, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([][]string, len(arr)) - for i := range res { - res[i], err = func(item stackitem.Item) ([]string, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([]string, len(arr)) - for i := range res { - res[i], err = func(item stackitem.Item) (string, error) { - b, err := item.TryBytes() - if err != nil { - return "", err - } - if !utf8.Valid(b) { - return "", errors.New("not a UTF-8 string") - } - return string(b), nil - }(arr[i]) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(arr[i]) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(arr[i]) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(item) - }(unwrap.Item(c.invoker.Call(c.hash, "aAAStrings", s))) -} - -// Any invokes `any` method of contract. -func (c *ContractReader) Any(a any) (any, error) { - return func(item stackitem.Item, err error) (any, error) { - if err != nil { - return nil, err - } - return item.Value(), error(nil) - }(unwrap.Item(c.invoker.Call(c.hash, "any", a))) -} - -// AnyMaps invokes `anyMaps` method of contract. -func (c *ContractReader) AnyMaps(m map[*big.Int]any) (map[*big.Int]any, error) { - return func(item stackitem.Item, err error) (map[*big.Int]any, error) { - if err != nil { - return nil, err - } - return func(item stackitem.Item) (map[*big.Int]any, error) { - m, ok := item.Value().([]stackitem.MapElement) - if !ok { - return nil, fmt.Errorf("%s is not a map", item.Type().String()) - } - res := make(map[*big.Int]any) - for i := range m { - k, err := m[i].Key.TryInteger() - if err != nil { - return nil, fmt.Errorf("key %d: %w", i, err) - } - v, err := m[i].Value.Value(), error(nil) - if err != nil { - return nil, fmt.Errorf("value %d: %w", i, err) - } - res[k] = v - } - return res, nil - }(item) - }(unwrap.Item(c.invoker.Call(c.hash, "anyMaps", m))) -} - -// Bool invokes `bool` method of contract. -func (c *ContractReader) Bool(b bool) (bool, error) { - return unwrap.Bool(c.invoker.Call(c.hash, "bool", b)) -} - -// Bools invokes `bools` method of contract. -func (c *ContractReader) Bools(b []bool) ([]bool, error) { - return unwrap.ArrayOfBools(c.invoker.Call(c.hash, "bools", b)) -} - -// Bytes invokes `bytes` method of contract. -func (c *ContractReader) Bytes(b []byte) ([]byte, error) { - return unwrap.Bytes(c.invoker.Call(c.hash, "bytes", b)) -} - -// Bytess invokes `bytess` method of contract. -func (c *ContractReader) Bytess(b [][]byte) ([][]byte, error) { - return unwrap.ArrayOfBytes(c.invoker.Call(c.hash, "bytess", b)) -} - -// CrazyMaps invokes `crazyMaps` method of contract. -func (c *ContractReader) CrazyMaps(m map[*big.Int][]map[string][]util.Uint160) (map[*big.Int][]map[string][]util.Uint160, error) { - return func(item stackitem.Item, err error) (map[*big.Int][]map[string][]util.Uint160, error) { - if err != nil { - return nil, err - } - return func(item stackitem.Item) (map[*big.Int][]map[string][]util.Uint160, error) { - m, ok := item.Value().([]stackitem.MapElement) - if !ok { - return nil, fmt.Errorf("%s is not a map", item.Type().String()) - } - res := make(map[*big.Int][]map[string][]util.Uint160) - for i := range m { - k, err := m[i].Key.TryInteger() - if err != nil { - return nil, fmt.Errorf("key %d: %w", i, err) - } - v, err := func(item stackitem.Item) ([]map[string][]util.Uint160, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([]map[string][]util.Uint160, len(arr)) - for i := range res { - res[i], err = func(item stackitem.Item) (map[string][]util.Uint160, error) { - m, ok := item.Value().([]stackitem.MapElement) - if !ok { - return nil, fmt.Errorf("%s is not a map", item.Type().String()) - } - res := make(map[string][]util.Uint160) - for i := range m { - k, err := func(item stackitem.Item) (string, error) { - b, err := item.TryBytes() - if err != nil { - return "", err - } - if !utf8.Valid(b) { - return "", errors.New("not a UTF-8 string") - } - return string(b), nil - }(m[i].Key) - if err != nil { - return nil, fmt.Errorf("key %d: %w", i, err) - } - v, err := func(item stackitem.Item) ([]util.Uint160, error) { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return nil, errors.New("not an array") - } - res := make([]util.Uint160, len(arr)) - for i := range res { - res[i], err = func(item stackitem.Item) (util.Uint160, error) { - b, err := item.TryBytes() - if err != nil { - return util.Uint160{}, err - } - u, err := util.Uint160DecodeBytesBE(b) - if err != nil { - return util.Uint160{}, err - } - return u, nil - }(arr[i]) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(m[i].Value) - if err != nil { - return nil, fmt.Errorf("value %d: %w", i, err) - } - res[k] = v - } - return res, nil - }(arr[i]) - if err != nil { - return nil, fmt.Errorf("item %d: %w", i, err) - } - } - return res, nil - }(m[i].Value) - if err != nil { - return nil, fmt.Errorf("value %d: %w", i, err) - } - res[k] = v - } - return res, nil - }(item) - }(unwrap.Item(c.invoker.Call(c.hash, "crazyMaps", m))) -} - -// Hash160 invokes `hash160` method of contract. -func (c *ContractReader) Hash160(h util.Uint160) (util.Uint160, error) { - return unwrap.Uint160(c.invoker.Call(c.hash, "hash160", h)) -} - -// Hash160s invokes `hash160s` method of contract. -func (c *ContractReader) Hash160s(h []util.Uint160) ([]util.Uint160, error) { - return unwrap.ArrayOfUint160(c.invoker.Call(c.hash, "hash160s", h)) -} - -// Hash256 invokes `hash256` method of contract. -func (c *ContractReader) Hash256(h util.Uint256) (util.Uint256, error) { - return unwrap.Uint256(c.invoker.Call(c.hash, "hash256", h)) -} - -// Hash256s invokes `hash256s` method of contract. -func (c *ContractReader) Hash256s(h []util.Uint256) ([]util.Uint256, error) { - return unwrap.ArrayOfUint256(c.invoker.Call(c.hash, "hash256s", h)) -} - -// Int invokes `int` method of contract. -func (c *ContractReader) Int(i *big.Int) (*big.Int, error) { - return unwrap.BigInt(c.invoker.Call(c.hash, "int", i)) -} - -// Ints invokes `ints` method of contract. -func (c *ContractReader) Ints(i []*big.Int) ([]*big.Int, error) { - return unwrap.ArrayOfBigInts(c.invoker.Call(c.hash, "ints", i)) -} - -// Maps invokes `maps` method of contract. -func (c *ContractReader) Maps(m map[string]string) (map[string]string, error) { - return func(item stackitem.Item, err error) (map[string]string, error) { - if err != nil { - return nil, err - } - return func(item stackitem.Item) (map[string]string, error) { - m, ok := item.Value().([]stackitem.MapElement) - if !ok { - return nil, fmt.Errorf("%s is not a map", item.Type().String()) - } - res := make(map[string]string) - for i := range m { - k, err := func(item stackitem.Item) (string, error) { - b, err := item.TryBytes() - if err != nil { - return "", err - } - if !utf8.Valid(b) { - return "", errors.New("not a UTF-8 string") - } - return string(b), nil - }(m[i].Key) - if err != nil { - return nil, fmt.Errorf("key %d: %w", i, err) - } - v, err := func(item stackitem.Item) (string, error) { - b, err := item.TryBytes() - if err != nil { - return "", err - } - if !utf8.Valid(b) { - return "", errors.New("not a UTF-8 string") - } - return string(b), nil - }(m[i].Value) - if err != nil { - return nil, fmt.Errorf("value %d: %w", i, err) - } - res[k] = v - } - return res, nil - }(item) - }(unwrap.Item(c.invoker.Call(c.hash, "maps", m))) -} - -// PublicKey invokes `publicKey` method of contract. -func (c *ContractReader) PublicKey(k *keys.PublicKey) (*keys.PublicKey, error) { - return unwrap.PublicKey(c.invoker.Call(c.hash, "publicKey", k)) -} - -// PublicKeys invokes `publicKeys` method of contract. -func (c *ContractReader) PublicKeys(k keys.PublicKeys) (keys.PublicKeys, error) { - return unwrap.ArrayOfPublicKeys(c.invoker.Call(c.hash, "publicKeys", k)) -} - -// Signature invokes `signature` method of contract. -func (c *ContractReader) Signature(s []byte) ([]byte, error) { - return unwrap.Bytes(c.invoker.Call(c.hash, "signature", s)) -} - -// Signatures invokes `signatures` method of contract. -func (c *ContractReader) Signatures(s [][]byte) ([][]byte, error) { - return unwrap.ArrayOfBytes(c.invoker.Call(c.hash, "signatures", s)) -} - -// String invokes `string` method of contract. -func (c *ContractReader) String(s string) (string, error) { - return unwrap.UTF8String(c.invoker.Call(c.hash, "string", s)) -} - -// Strings invokes `strings` method of contract. -func (c *ContractReader) Strings(s []string) ([]string, error) { - return unwrap.ArrayOfUTF8Strings(c.invoker.Call(c.hash, "strings", s)) -} - -// UnnamedStructs invokes `unnamedStructs` method of contract. -func (c *ContractReader) UnnamedStructs() (*Unnamed, error) { - return itemToUnnamed(unwrap.Item(c.invoker.Call(c.hash, "unnamedStructs"))) -} - -// UnnamedStructsX invokes `unnamedStructsX` method of contract. -func (c *ContractReader) UnnamedStructsX() (*UnnamedX, error) { - return itemToUnnamedX(unwrap.Item(c.invoker.Call(c.hash, "unnamedStructsX"))) -} - -// itemToUnnamed converts stack item into *Unnamed. -// NULL item is returned as nil pointer without error. -func itemToUnnamed(item stackitem.Item, err error) (*Unnamed, error) { - if err != nil { - return nil, err - } - _, null := item.(stackitem.Null) - if null { - return nil, nil - } - var res = new(Unnamed) - err = res.FromStackItem(item) - return res, err -} - -// Ensure *Unnamed is a proper [stackitem.Convertible]. -var _ = stackitem.Convertible(&Unnamed{}) - -// Ensure *Unnamed is a proper [smartcontract.Convertible]. -var _ = smartcontract.Convertible(&Unnamed{}) - -// FromStackItem retrieves fields of Unnamed from the given -// [stackitem.Item] or returns an error if it's not possible to do to so. -// It implements [stackitem.Convertible] interface. -func (res *Unnamed) FromStackItem(item stackitem.Item) error { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 1 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - res.I, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field I: %w", err) - } - - return nil -} - -// ToStackItem creates [stackitem.Item] representing Unnamed. -// It implements [stackitem.Convertible] interface. -func (res *Unnamed) ToStackItem() (stackitem.Item, error) { - if res == nil { - return stackitem.Null{}, nil - } - - var ( - err error - itm stackitem.Item - items = make([]stackitem.Item, 0, 1) - ) - itm, err = (*stackitem.BigInteger)(res.I), error(nil) - if err != nil { - return nil, fmt.Errorf("field I: %w", err) - } - items = append(items, itm) - - return stackitem.NewStruct(items), nil -} - -// ToSCParameter creates [smartcontract.Parameter] representing Unnamed. -// It implements [smartcontract.Convertible] interface so that Unnamed -// could be used with invokers. -func (res *Unnamed) ToSCParameter() (smartcontract.Parameter, error) { - if res == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var ( - err error - prm smartcontract.Parameter - prms = make([]smartcontract.Parameter, 0, 1) - ) - prm, err = smartcontract.NewParameterFromValue(res.I) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field I: %w", err) - } - prms = append(prms, prm) - - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil -} - -// itemToUnnamedX converts stack item into *UnnamedX. -// NULL item is returned as nil pointer without error. -func itemToUnnamedX(item stackitem.Item, err error) (*UnnamedX, error) { - if err != nil { - return nil, err - } - _, null := item.(stackitem.Null) - if null { - return nil, nil - } - var res = new(UnnamedX) - err = res.FromStackItem(item) - return res, err -} - -// Ensure *UnnamedX is a proper [stackitem.Convertible]. -var _ = stackitem.Convertible(&UnnamedX{}) - -// Ensure *UnnamedX is a proper [smartcontract.Convertible]. -var _ = smartcontract.Convertible(&UnnamedX{}) - -// FromStackItem retrieves fields of UnnamedX from the given -// [stackitem.Item] or returns an error if it's not possible to do to so. -// It implements [stackitem.Convertible] interface. -func (res *UnnamedX) FromStackItem(item stackitem.Item) error { - arr, ok := item.Value().([]stackitem.Item) - if !ok { - return errors.New("not an array") - } - if len(arr) != 2 { - return errors.New("wrong number of structure elements") - } - - var ( - index = -1 - err error - ) - index++ - res.I, err = arr[index].TryInteger() - if err != nil { - return fmt.Errorf("field I: %w", err) - } - - index++ - res.B, err = arr[index].TryBool() - if err != nil { - return fmt.Errorf("field B: %w", err) - } - - return nil -} - -// ToStackItem creates [stackitem.Item] representing UnnamedX. -// It implements [stackitem.Convertible] interface. -func (res *UnnamedX) ToStackItem() (stackitem.Item, error) { - if res == nil { - return stackitem.Null{}, nil - } - - var ( - err error - itm stackitem.Item - items = make([]stackitem.Item, 0, 2) - ) - itm, err = (*stackitem.BigInteger)(res.I), error(nil) - if err != nil { - return nil, fmt.Errorf("field I: %w", err) - } - items = append(items, itm) - - itm, err = stackitem.NewBool(res.B), error(nil) - if err != nil { - return nil, fmt.Errorf("field B: %w", err) - } - items = append(items, itm) - - return stackitem.NewStruct(items), nil -} - -// ToSCParameter creates [smartcontract.Parameter] representing UnnamedX. -// It implements [smartcontract.Convertible] interface so that UnnamedX -// could be used with invokers. -func (res *UnnamedX) ToSCParameter() (smartcontract.Parameter, error) { - if res == nil { - return smartcontract.Parameter{Type: smartcontract.AnyType}, nil - } - - var ( - err error - prm smartcontract.Parameter - prms = make([]smartcontract.Parameter, 0, 2) - ) - prm, err = smartcontract.NewParameterFromValue(res.I) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field I: %w", err) - } - prms = append(prms, prm) - - prm, err = smartcontract.NewParameterFromValue(res.B) - if err != nil { - return smartcontract.Parameter{}, fmt.Errorf("field B: %w", err) - } - prms = append(prms, prm) - - return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil -} +// Code generated by neo-go contract generate-rpcwrapper --manifest --out [--hash ] [--config ]; DO NOT EDIT. + +// Package types contains RPC wrappers for Types contract. +package types + +import ( + "errors" + "fmt" + "github.com/tutus-one/tutus-chain/pkg/crypto/keys" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" + "github.com/tutus-one/tutus-chain/pkg/rpcclient/unwrap" + "github.com/tutus-one/tutus-chain/pkg/smartcontract" + "github.com/tutus-one/tutus-chain/pkg/util" + "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" + "math/big" + "unicode/utf8" +) + +// Unnamed is a contract-specific unnamed type used by its methods. +type Unnamed struct { + I *big.Int +} + +// UnnamedX is a contract-specific unnamedX type used by its methods. +type UnnamedX struct { + I *big.Int + B bool +} + +// Invoker is used by ContractReader to call various safe methods. +type Invoker interface { + Call(contract util.Uint160, operation string, params ...any) (*result.Invoke, error) +} + +// ContractReader implements safe contract methods. +type ContractReader struct { + invoker Invoker + hash util.Uint160 +} + +// NewReader creates an instance of ContractReader using provided contract hash and the given Invoker. +func NewReader(invoker Invoker, hash util.Uint160) *ContractReader { + return &ContractReader{invoker, hash} +} + +// AAAStrings invokes `aAAStrings` method of contract. +func (c *ContractReader) AAAStrings(s [][][]string) ([][][]string, error) { + return func(item stackitem.Item, err error) ([][][]string, error) { + if err != nil { + return nil, err + } + return func(item stackitem.Item) ([][][]string, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([][][]string, len(arr)) + for i := range res { + res[i], err = func(item stackitem.Item) ([][]string, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([][]string, len(arr)) + for i := range res { + res[i], err = func(item stackitem.Item) ([]string, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([]string, len(arr)) + for i := range res { + res[i], err = func(item stackitem.Item) (string, error) { + b, err := item.TryBytes() + if err != nil { + return "", err + } + if !utf8.Valid(b) { + return "", errors.New("not a UTF-8 string") + } + return string(b), nil + }(arr[i]) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(arr[i]) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(arr[i]) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(item) + }(unwrap.Item(c.invoker.Call(c.hash, "aAAStrings", s))) +} + +// Any invokes `any` method of contract. +func (c *ContractReader) Any(a any) (any, error) { + return func(item stackitem.Item, err error) (any, error) { + if err != nil { + return nil, err + } + return item.Value(), error(nil) + }(unwrap.Item(c.invoker.Call(c.hash, "any", a))) +} + +// AnyMaps invokes `anyMaps` method of contract. +func (c *ContractReader) AnyMaps(m map[*big.Int]any) (map[*big.Int]any, error) { + return func(item stackitem.Item, err error) (map[*big.Int]any, error) { + if err != nil { + return nil, err + } + return func(item stackitem.Item) (map[*big.Int]any, error) { + m, ok := item.Value().([]stackitem.MapElement) + if !ok { + return nil, fmt.Errorf("%s is not a map", item.Type().String()) + } + res := make(map[*big.Int]any) + for i := range m { + k, err := m[i].Key.TryInteger() + if err != nil { + return nil, fmt.Errorf("key %d: %w", i, err) + } + v, err := m[i].Value.Value(), error(nil) + if err != nil { + return nil, fmt.Errorf("value %d: %w", i, err) + } + res[k] = v + } + return res, nil + }(item) + }(unwrap.Item(c.invoker.Call(c.hash, "anyMaps", m))) +} + +// Bool invokes `bool` method of contract. +func (c *ContractReader) Bool(b bool) (bool, error) { + return unwrap.Bool(c.invoker.Call(c.hash, "bool", b)) +} + +// Bools invokes `bools` method of contract. +func (c *ContractReader) Bools(b []bool) ([]bool, error) { + return unwrap.ArrayOfBools(c.invoker.Call(c.hash, "bools", b)) +} + +// Bytes invokes `bytes` method of contract. +func (c *ContractReader) Bytes(b []byte) ([]byte, error) { + return unwrap.Bytes(c.invoker.Call(c.hash, "bytes", b)) +} + +// Bytess invokes `bytess` method of contract. +func (c *ContractReader) Bytess(b [][]byte) ([][]byte, error) { + return unwrap.ArrayOfBytes(c.invoker.Call(c.hash, "bytess", b)) +} + +// CrazyMaps invokes `crazyMaps` method of contract. +func (c *ContractReader) CrazyMaps(m map[*big.Int][]map[string][]util.Uint160) (map[*big.Int][]map[string][]util.Uint160, error) { + return func(item stackitem.Item, err error) (map[*big.Int][]map[string][]util.Uint160, error) { + if err != nil { + return nil, err + } + return func(item stackitem.Item) (map[*big.Int][]map[string][]util.Uint160, error) { + m, ok := item.Value().([]stackitem.MapElement) + if !ok { + return nil, fmt.Errorf("%s is not a map", item.Type().String()) + } + res := make(map[*big.Int][]map[string][]util.Uint160) + for i := range m { + k, err := m[i].Key.TryInteger() + if err != nil { + return nil, fmt.Errorf("key %d: %w", i, err) + } + v, err := func(item stackitem.Item) ([]map[string][]util.Uint160, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([]map[string][]util.Uint160, len(arr)) + for i := range res { + res[i], err = func(item stackitem.Item) (map[string][]util.Uint160, error) { + m, ok := item.Value().([]stackitem.MapElement) + if !ok { + return nil, fmt.Errorf("%s is not a map", item.Type().String()) + } + res := make(map[string][]util.Uint160) + for i := range m { + k, err := func(item stackitem.Item) (string, error) { + b, err := item.TryBytes() + if err != nil { + return "", err + } + if !utf8.Valid(b) { + return "", errors.New("not a UTF-8 string") + } + return string(b), nil + }(m[i].Key) + if err != nil { + return nil, fmt.Errorf("key %d: %w", i, err) + } + v, err := func(item stackitem.Item) ([]util.Uint160, error) { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return nil, errors.New("not an array") + } + res := make([]util.Uint160, len(arr)) + for i := range res { + res[i], err = func(item stackitem.Item) (util.Uint160, error) { + b, err := item.TryBytes() + if err != nil { + return util.Uint160{}, err + } + u, err := util.Uint160DecodeBytesBE(b) + if err != nil { + return util.Uint160{}, err + } + return u, nil + }(arr[i]) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(m[i].Value) + if err != nil { + return nil, fmt.Errorf("value %d: %w", i, err) + } + res[k] = v + } + return res, nil + }(arr[i]) + if err != nil { + return nil, fmt.Errorf("item %d: %w", i, err) + } + } + return res, nil + }(m[i].Value) + if err != nil { + return nil, fmt.Errorf("value %d: %w", i, err) + } + res[k] = v + } + return res, nil + }(item) + }(unwrap.Item(c.invoker.Call(c.hash, "crazyMaps", m))) +} + +// Hash160 invokes `hash160` method of contract. +func (c *ContractReader) Hash160(h util.Uint160) (util.Uint160, error) { + return unwrap.Uint160(c.invoker.Call(c.hash, "hash160", h)) +} + +// Hash160s invokes `hash160s` method of contract. +func (c *ContractReader) Hash160s(h []util.Uint160) ([]util.Uint160, error) { + return unwrap.ArrayOfUint160(c.invoker.Call(c.hash, "hash160s", h)) +} + +// Hash256 invokes `hash256` method of contract. +func (c *ContractReader) Hash256(h util.Uint256) (util.Uint256, error) { + return unwrap.Uint256(c.invoker.Call(c.hash, "hash256", h)) +} + +// Hash256s invokes `hash256s` method of contract. +func (c *ContractReader) Hash256s(h []util.Uint256) ([]util.Uint256, error) { + return unwrap.ArrayOfUint256(c.invoker.Call(c.hash, "hash256s", h)) +} + +// Int invokes `int` method of contract. +func (c *ContractReader) Int(i *big.Int) (*big.Int, error) { + return unwrap.BigInt(c.invoker.Call(c.hash, "int", i)) +} + +// Ints invokes `ints` method of contract. +func (c *ContractReader) Ints(i []*big.Int) ([]*big.Int, error) { + return unwrap.ArrayOfBigInts(c.invoker.Call(c.hash, "ints", i)) +} + +// Maps invokes `maps` method of contract. +func (c *ContractReader) Maps(m map[string]string) (map[string]string, error) { + return func(item stackitem.Item, err error) (map[string]string, error) { + if err != nil { + return nil, err + } + return func(item stackitem.Item) (map[string]string, error) { + m, ok := item.Value().([]stackitem.MapElement) + if !ok { + return nil, fmt.Errorf("%s is not a map", item.Type().String()) + } + res := make(map[string]string) + for i := range m { + k, err := func(item stackitem.Item) (string, error) { + b, err := item.TryBytes() + if err != nil { + return "", err + } + if !utf8.Valid(b) { + return "", errors.New("not a UTF-8 string") + } + return string(b), nil + }(m[i].Key) + if err != nil { + return nil, fmt.Errorf("key %d: %w", i, err) + } + v, err := func(item stackitem.Item) (string, error) { + b, err := item.TryBytes() + if err != nil { + return "", err + } + if !utf8.Valid(b) { + return "", errors.New("not a UTF-8 string") + } + return string(b), nil + }(m[i].Value) + if err != nil { + return nil, fmt.Errorf("value %d: %w", i, err) + } + res[k] = v + } + return res, nil + }(item) + }(unwrap.Item(c.invoker.Call(c.hash, "maps", m))) +} + +// PublicKey invokes `publicKey` method of contract. +func (c *ContractReader) PublicKey(k *keys.PublicKey) (*keys.PublicKey, error) { + return unwrap.PublicKey(c.invoker.Call(c.hash, "publicKey", k)) +} + +// PublicKeys invokes `publicKeys` method of contract. +func (c *ContractReader) PublicKeys(k keys.PublicKeys) (keys.PublicKeys, error) { + return unwrap.ArrayOfPublicKeys(c.invoker.Call(c.hash, "publicKeys", k)) +} + +// Signature invokes `signature` method of contract. +func (c *ContractReader) Signature(s []byte) ([]byte, error) { + return unwrap.Bytes(c.invoker.Call(c.hash, "signature", s)) +} + +// Signatures invokes `signatures` method of contract. +func (c *ContractReader) Signatures(s [][]byte) ([][]byte, error) { + return unwrap.ArrayOfBytes(c.invoker.Call(c.hash, "signatures", s)) +} + +// String invokes `string` method of contract. +func (c *ContractReader) String(s string) (string, error) { + return unwrap.UTF8String(c.invoker.Call(c.hash, "string", s)) +} + +// Strings invokes `strings` method of contract. +func (c *ContractReader) Strings(s []string) ([]string, error) { + return unwrap.ArrayOfUTF8Strings(c.invoker.Call(c.hash, "strings", s)) +} + +// UnnamedStructs invokes `unnamedStructs` method of contract. +func (c *ContractReader) UnnamedStructs() (*Unnamed, error) { + return itemToUnnamed(unwrap.Item(c.invoker.Call(c.hash, "unnamedStructs"))) +} + +// UnnamedStructsX invokes `unnamedStructsX` method of contract. +func (c *ContractReader) UnnamedStructsX() (*UnnamedX, error) { + return itemToUnnamedX(unwrap.Item(c.invoker.Call(c.hash, "unnamedStructsX"))) +} + +// itemToUnnamed converts stack item into *Unnamed. +// NULL item is returned as nil pointer without error. +func itemToUnnamed(item stackitem.Item, err error) (*Unnamed, error) { + if err != nil { + return nil, err + } + _, null := item.(stackitem.Null) + if null { + return nil, nil + } + var res = new(Unnamed) + err = res.FromStackItem(item) + return res, err +} + +// Ensure *Unnamed is a proper [stackitem.Convertible]. +var _ = stackitem.Convertible(&Unnamed{}) + +// Ensure *Unnamed is a proper [smartcontract.Convertible]. +var _ = smartcontract.Convertible(&Unnamed{}) + +// FromStackItem retrieves fields of Unnamed from the given +// [stackitem.Item] or returns an error if it's not possible to do to so. +// It implements [stackitem.Convertible] interface. +func (res *Unnamed) FromStackItem(item stackitem.Item) error { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 1 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + res.I, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field I: %w", err) + } + + return nil +} + +// ToStackItem creates [stackitem.Item] representing Unnamed. +// It implements [stackitem.Convertible] interface. +func (res *Unnamed) ToStackItem() (stackitem.Item, error) { + if res == nil { + return stackitem.Null{}, nil + } + + var ( + err error + itm stackitem.Item + items = make([]stackitem.Item, 0, 1) + ) + itm, err = (*stackitem.BigInteger)(res.I), error(nil) + if err != nil { + return nil, fmt.Errorf("field I: %w", err) + } + items = append(items, itm) + + return stackitem.NewStruct(items), nil +} + +// ToSCParameter creates [smartcontract.Parameter] representing Unnamed. +// It implements [smartcontract.Convertible] interface so that Unnamed +// could be used with invokers. +func (res *Unnamed) ToSCParameter() (smartcontract.Parameter, error) { + if res == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var ( + err error + prm smartcontract.Parameter + prms = make([]smartcontract.Parameter, 0, 1) + ) + prm, err = smartcontract.NewParameterFromValue(res.I) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field I: %w", err) + } + prms = append(prms, prm) + + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil +} + +// itemToUnnamedX converts stack item into *UnnamedX. +// NULL item is returned as nil pointer without error. +func itemToUnnamedX(item stackitem.Item, err error) (*UnnamedX, error) { + if err != nil { + return nil, err + } + _, null := item.(stackitem.Null) + if null { + return nil, nil + } + var res = new(UnnamedX) + err = res.FromStackItem(item) + return res, err +} + +// Ensure *UnnamedX is a proper [stackitem.Convertible]. +var _ = stackitem.Convertible(&UnnamedX{}) + +// Ensure *UnnamedX is a proper [smartcontract.Convertible]. +var _ = smartcontract.Convertible(&UnnamedX{}) + +// FromStackItem retrieves fields of UnnamedX from the given +// [stackitem.Item] or returns an error if it's not possible to do to so. +// It implements [stackitem.Convertible] interface. +func (res *UnnamedX) FromStackItem(item stackitem.Item) error { + arr, ok := item.Value().([]stackitem.Item) + if !ok { + return errors.New("not an array") + } + if len(arr) != 2 { + return errors.New("wrong number of structure elements") + } + + var ( + index = -1 + err error + ) + index++ + res.I, err = arr[index].TryInteger() + if err != nil { + return fmt.Errorf("field I: %w", err) + } + + index++ + res.B, err = arr[index].TryBool() + if err != nil { + return fmt.Errorf("field B: %w", err) + } + + return nil +} + +// ToStackItem creates [stackitem.Item] representing UnnamedX. +// It implements [stackitem.Convertible] interface. +func (res *UnnamedX) ToStackItem() (stackitem.Item, error) { + if res == nil { + return stackitem.Null{}, nil + } + + var ( + err error + itm stackitem.Item + items = make([]stackitem.Item, 0, 2) + ) + itm, err = (*stackitem.BigInteger)(res.I), error(nil) + if err != nil { + return nil, fmt.Errorf("field I: %w", err) + } + items = append(items, itm) + + itm, err = stackitem.NewBool(res.B), error(nil) + if err != nil { + return nil, fmt.Errorf("field B: %w", err) + } + items = append(items, itm) + + return stackitem.NewStruct(items), nil +} + +// ToSCParameter creates [smartcontract.Parameter] representing UnnamedX. +// It implements [smartcontract.Convertible] interface so that UnnamedX +// could be used with invokers. +func (res *UnnamedX) ToSCParameter() (smartcontract.Parameter, error) { + if res == nil { + return smartcontract.Parameter{Type: smartcontract.AnyType}, nil + } + + var ( + err error + prm smartcontract.Parameter + prms = make([]smartcontract.Parameter, 0, 2) + ) + prm, err = smartcontract.NewParameterFromValue(res.I) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field I: %w", err) + } + prms = append(prms, prm) + + prm, err = smartcontract.NewParameterFromValue(res.B) + if err != nil { + return smartcontract.Parameter{}, fmt.Errorf("field B: %w", err) + } + prms = append(prms, prm) + + return smartcontract.Parameter{Type: smartcontract.ArrayType, Value: prms}, nil +} diff --git a/cli/smartcontract/rpcbindings/types/rpcbindings/rpcbindings_test.go b/cli/smartcontract/rpcbindings/types/rpcbindings/rpcbindings_test.go index 5e6261e..6a9f5c0 100644 --- a/cli/smartcontract/rpcbindings/types/rpcbindings/rpcbindings_test.go +++ b/cli/smartcontract/rpcbindings/types/rpcbindings/rpcbindings_test.go @@ -7,7 +7,7 @@ import ( "errors" "fmt" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient/unwrap" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/util" diff --git a/cli/smartcontract/rpcbindings/verify/rpcbindings_test.go b/cli/smartcontract/rpcbindings/verify/rpcbindings_test.go index 56fcd65..82af48e 100644 --- a/cli/smartcontract/rpcbindings/verify/rpcbindings_test.go +++ b/cli/smartcontract/rpcbindings/verify/rpcbindings_test.go @@ -7,7 +7,7 @@ import ( "errors" "fmt" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" diff --git a/cli/smartcontract/smart_contract.go b/cli/smartcontract/smart_contract.go index 650120e..78baac5 100644 --- a/cli/smartcontract/smart_contract.go +++ b/cli/smartcontract/smart_contract.go @@ -16,7 +16,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/compiler" "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient/actor" "github.com/tutus-one/tutus-chain/pkg/rpcclient/invoker" "github.com/tutus-one/tutus-chain/pkg/rpcclient/management" diff --git a/cli/smartcontract/testdata/nameservice/nns.go b/cli/smartcontract/testdata/nameservice/nns.go index 47ff3eb..06f589b 100644 --- a/cli/smartcontract/testdata/nameservice/nns.go +++ b/cli/smartcontract/testdata/nameservice/nns.go @@ -8,7 +8,7 @@ import ( "fmt" "github.com/google/uuid" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient/nep11" "github.com/tutus-one/tutus-chain/pkg/rpcclient/unwrap" "github.com/tutus-one/tutus-chain/pkg/smartcontract" diff --git a/cli/smartcontract/testdata/nex/nex.go b/cli/smartcontract/testdata/nex/nex.go index 28f2bce..f61c726 100644 --- a/cli/smartcontract/testdata/nex/nex.go +++ b/cli/smartcontract/testdata/nex/nex.go @@ -8,7 +8,7 @@ import ( "fmt" "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient/nep17" "github.com/tutus-one/tutus-chain/pkg/rpcclient/unwrap" "github.com/tutus-one/tutus-chain/pkg/util" diff --git a/cli/smartcontract/testdata/nonepiter/iter.go b/cli/smartcontract/testdata/nonepiter/iter.go index b0aaadb..7161e74 100644 --- a/cli/smartcontract/testdata/nonepiter/iter.go +++ b/cli/smartcontract/testdata/nonepiter/iter.go @@ -5,7 +5,7 @@ package nonnepxxcontractwithiterators import ( "github.com/google/uuid" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient/unwrap" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" diff --git a/cli/util/cancel.go b/cli/util/cancel.go index a3c6e6d..d246d30 100644 --- a/cli/util/cancel.go +++ b/cli/util/cancel.go @@ -11,7 +11,7 @@ import ( "github.com/tutus-one/tutus-chain/cli/txctx" "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient/actor" "github.com/tutus-one/tutus-chain/pkg/rpcclient/waiter" "github.com/tutus-one/tutus-chain/pkg/util" diff --git a/cli/vm/cli.go b/cli/vm/cli.go index a35d3ec..6ec5106 100644 --- a/cli/vm/cli.go +++ b/cli/vm/cli.go @@ -466,7 +466,7 @@ func NewWithConfig(printLogotype bool, onExit func(int), c *readline.Config, cfg ctl.Writer = l.Stdout() ctl.ErrWriter = l.Stderr() ctl.Version = config.Version - ctl.Usage = "Official VM CLI for NeoGo" + ctl.Usage = "Official VM CLI for Tutus" // Override default error handler in order not to exit on error. ctl.ExitErrHandler = func(context *cli.Context, err error) {} diff --git a/cli/vm/cli_test.go b/cli/vm/cli_test.go index 2bd8069..8c4d990 100644 --- a/cli/vm/cli_test.go +++ b/cli/vm/cli_test.go @@ -34,8 +34,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/storage/dboper" "github.com/tutus-one/tutus-chain/pkg/encoding/address" "github.com/tutus-one/tutus-chain/pkg/io" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/smartcontract/callflag" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm" diff --git a/cli/wallet/multisig_test.go b/cli/wallet/multisig_test.go index 5fc418b..ede0129 100644 --- a/cli/wallet/multisig_test.go +++ b/cli/wallet/multisig_test.go @@ -12,7 +12,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/crypto/hash" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" "github.com/tutus-one/tutus-chain/pkg/encoding/address" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/smartcontract/context" "github.com/tutus-one/tutus-chain/pkg/util" diff --git a/cli/wallet/nep11.go b/cli/wallet/nep11.go index 72e2032..60a2b68 100644 --- a/cli/wallet/nep11.go +++ b/cli/wallet/nep11.go @@ -13,7 +13,7 @@ import ( "github.com/tutus-one/tutus-chain/cli/txctx" "github.com/tutus-one/tutus-chain/pkg/config" "github.com/tutus-one/tutus-chain/pkg/encoding/address" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient" "github.com/tutus-one/tutus-chain/pkg/rpcclient/nep11" "github.com/tutus-one/tutus-chain/pkg/smartcontract/manifest" diff --git a/cli/wallet/nep17.go b/cli/wallet/nep17.go index 54d078d..d01136c 100644 --- a/cli/wallet/nep17.go +++ b/cli/wallet/nep17.go @@ -16,11 +16,11 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/encoding/address" "github.com/tutus-one/tutus-chain/pkg/encoding/fixedn" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient" "github.com/tutus-one/tutus-chain/pkg/rpcclient/actor" "github.com/tutus-one/tutus-chain/pkg/rpcclient/gas" - "github.com/tutus-one/tutus-chain/pkg/rpcclient/neo" + "github.com/tutus-one/tutus-chain/pkg/rpcclient/tutus" "github.com/tutus-one/tutus-chain/pkg/rpcclient/nep11" "github.com/tutus-one/tutus-chain/pkg/rpcclient/nep17" "github.com/tutus-one/tutus-chain/pkg/rpcclient/neptoken" @@ -273,7 +273,7 @@ func getNEPBalance(ctx *cli.Context, standard string, accHandler func(*cli.Conte // Well-known hardcoded names/symbols. if standard == manifest.NEP17StandardName && (name == nativenames.Tutus || name == "NEO") { - h = neo.Hash + h = tutus.Hash } else if standard == manifest.NEP17StandardName && (name == nativenames.Lub || name == "GAS") { h = gas.Hash } else { diff --git a/cli/wallet/validator.go b/cli/wallet/validator.go index f4d90c4..944d915 100644 --- a/cli/wallet/validator.go +++ b/cli/wallet/validator.go @@ -12,7 +12,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" "github.com/tutus-one/tutus-chain/pkg/rpcclient/gas" - "github.com/tutus-one/tutus-chain/pkg/rpcclient/neo" + "github.com/tutus-one/tutus-chain/pkg/rpcclient/tutus" "github.com/tutus-one/tutus-chain/pkg/rpcclient/nep17" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/wallet" @@ -102,11 +102,11 @@ func newValidatorCommands() []*cli.Command { func handleRegister(ctx *cli.Context) error { if ctx.Bool("useRegisterCall") { - return handleNeoAction(ctx, func(contract *neo.Contract, _ util.Uint160, acc *wallet.Account) (*transaction.Transaction, error) { + return handleNeoAction(ctx, func(contract *tutus.Contract, _ util.Uint160, acc *wallet.Account) (*transaction.Transaction, error) { return contract.RegisterCandidateUnsigned(acc.PublicKey()) }) } - return handleGasAction(ctx, func(nc *neo.Contract, gasT *nep17.Token, _ util.Uint160, acc *wallet.Account) (*transaction.Transaction, error) { + return handleGasAction(ctx, func(nc *tutus.Contract, gasT *nep17.Token, _ util.Uint160, acc *wallet.Account) (*transaction.Transaction, error) { regPrice, err := nc.GetRegisterPrice() if err != nil { return nil, err @@ -121,24 +121,24 @@ func handleRegister(ctx *cli.Context) error { } func handleUnregister(ctx *cli.Context) error { - return handleNeoAction(ctx, func(contract *neo.Contract, _ util.Uint160, acc *wallet.Account) (*transaction.Transaction, error) { + return handleNeoAction(ctx, func(contract *tutus.Contract, _ util.Uint160, acc *wallet.Account) (*transaction.Transaction, error) { return contract.UnregisterCandidateUnsigned(acc.PublicKey()) }) } -func handleNeoAction(ctx *cli.Context, mkTx func(*neo.Contract, util.Uint160, *wallet.Account) (*transaction.Transaction, error)) error { - return handleTokenAction(ctx, func(nc *neo.Contract, _ *nep17.Token, addr util.Uint160, acc *wallet.Account) (*transaction.Transaction, error) { +func handleNeoAction(ctx *cli.Context, mkTx func(*tutus.Contract, util.Uint160, *wallet.Account) (*transaction.Transaction, error)) error { + return handleTokenAction(ctx, func(nc *tutus.Contract, _ *nep17.Token, addr util.Uint160, acc *wallet.Account) (*transaction.Transaction, error) { return mkTx(nc, addr, acc) }, transaction.CalledByEntry) } -func handleGasAction(ctx *cli.Context, mkTx func(*neo.Contract, *nep17.Token, util.Uint160, *wallet.Account) (*transaction.Transaction, error)) error { +func handleGasAction(ctx *cli.Context, mkTx func(*tutus.Contract, *nep17.Token, util.Uint160, *wallet.Account) (*transaction.Transaction, error)) error { return handleTokenAction(ctx, mkTx, transaction.Global) } func handleTokenAction( ctx *cli.Context, - mkTx func(nc *neo.Contract, gasT *nep17.Token, addr util.Uint160, acc *wallet.Account) (*transaction.Transaction, error), + mkTx func(nc *tutus.Contract, gasT *nep17.Token, addr util.Uint160, acc *wallet.Account) (*transaction.Transaction, error), scope transaction.WitnessScope, ) error { if err := cmdargs.EnsureNone(ctx); err != nil { @@ -169,7 +169,7 @@ func handleTokenAction( return exitErr } - neoT := neo.New(act) + neoT := tutus.New(act) gasT := gas.New(act) tx, err := mkTx(neoT, gasT, addr, acc) if err != nil { @@ -179,7 +179,7 @@ func handleTokenAction( } func handleVote(ctx *cli.Context) error { - return handleNeoAction(ctx, func(contract *neo.Contract, addr util.Uint160, acc *wallet.Account) (*transaction.Transaction, error) { + return handleNeoAction(ctx, func(contract *tutus.Contract, addr util.Uint160, acc *wallet.Account) (*transaction.Transaction, error) { var ( err error pub *keys.PublicKey diff --git a/cli/wallet/wallet.go b/cli/wallet/wallet.go index 818259e..a322278 100644 --- a/cli/wallet/wallet.go +++ b/cli/wallet/wallet.go @@ -19,7 +19,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" "github.com/tutus-one/tutus-chain/pkg/encoding/address" - "github.com/tutus-one/tutus-chain/pkg/rpcclient/neo" + "github.com/tutus-one/tutus-chain/pkg/rpcclient/tutus" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/smartcontract/manifest" "github.com/tutus-one/tutus-chain/pkg/smartcontract/scparser" @@ -121,7 +121,7 @@ func NewCommands() []*cli.Command { signFlags = append(signFlags, options.RPC[1:]...) return []*cli.Command{{ Name: "wallet", - Usage: "Create, open and manage a Neo wallet", + Usage: "Create, open and manage a Tutus wallet", Subcommands: []*cli.Command{ { Name: "claim", @@ -188,7 +188,7 @@ func NewCommands() []*cli.Command { }, { Name: "dump", - Usage: "Check and dump an existing Neo wallet", + Usage: "Check and dump an existing Tutus wallet", UsageText: "neo-go wallet dump -w wallet [--wallet-config path] [-d]", Description: `Prints the given wallet (via -w option or via wallet configuration file) in JSON format to the standard output. If -d is given, private keys are unencrypted and @@ -375,7 +375,7 @@ func NewCommands() []*cli.Command { } func claimGas(ctx *cli.Context) error { - return handleNeoAction(ctx, func(contract *neo.Contract, shash util.Uint160, _ *wallet.Account) (*transaction.Transaction, error) { + return handleNeoAction(ctx, func(contract *tutus.Contract, shash util.Uint160, _ *wallet.Account) (*transaction.Transaction, error) { return contract.TransferUnsigned(shash, shash, big.NewInt(0), nil) }) } diff --git a/examples/nft-nd-nns/nns_test.go b/examples/nft-nd-nns/nns_test.go index 4592bf4..dc2a427 100644 --- a/examples/nft-nd-nns/nns_test.go +++ b/examples/nft-nd-nns/nns_test.go @@ -7,8 +7,8 @@ import ( nns "github.com/tutus-one/tutus-chain/examples/nft-nd-nns" "github.com/tutus-one/tutus-chain/pkg/compiler" "github.com/tutus-one/tutus-chain/pkg/core/interop/storage" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" "github.com/stretchr/testify/require" diff --git a/examples/zkp/cubic_circuit/main_test.go b/examples/zkp/cubic_circuit/main_test.go index 737afda..9bdfec5 100644 --- a/examples/zkp/cubic_circuit/main_test.go +++ b/examples/zkp/cubic_circuit/main_test.go @@ -16,8 +16,8 @@ import ( "github.com/consensys/gnark/frontend" "github.com/consensys/gnark/frontend/cs/r1cs" "github.com/consensys/gnark/test" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/smartcontract/zkpbinding" "github.com/stretchr/testify/require" ) diff --git a/go.mod b/go.mod index 9f0a178..7ba531d 100644 --- a/go.mod +++ b/go.mod @@ -14,17 +14,17 @@ require ( github.com/holiman/uint256 v1.3.2 github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 github.com/mr-tron/base58 v1.2.0 - github.com/nspcc-dev/bbolt v0.0.0-20250911202005-807225ebb0c8 - github.com/nspcc-dev/go-ordered-json v0.0.0-20250911084817-6fb4472993d1 github.com/nspcc-dev/neo-go v0.113.0 github.com/nspcc-dev/neofs-sdk-go v1.0.0-rc.16 - github.com/nspcc-dev/rfc6979 v0.2.4 github.com/pierrec/lz4 v2.6.1+incompatible github.com/prometheus/client_golang v1.23.2 github.com/stretchr/testify v1.11.1 github.com/syndtr/goleveldb v1.0.1-0.20210305035536-64b5b1c73954 + github.com/tutus-one/tutus-bolt v1.0.0 github.com/tutus-one/tutus-chain/pkg/interop v0.0.0-20251217090505-857f951d81a9 github.com/tutus-one/tutus-consensus v1.0.0 + github.com/tutus-one/tutus-ordered-json v1.0.0 + github.com/tutus-one/tutus-rfc6979 v1.0.0 github.com/twmb/murmur3 v1.1.8 github.com/urfave/cli/v2 v2.27.7 go.uber.org/zap v1.27.0 @@ -51,6 +51,7 @@ require ( github.com/mattn/go-isatty v0.0.20 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/nspcc-dev/hrw/v2 v2.0.4 // indirect + github.com/nspcc-dev/rfc6979 v0.2.4 // indirect github.com/nspcc-dev/tzhash v1.8.3 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/prometheus/client_model v0.6.2 // indirect diff --git a/go.sum b/go.sum index 2b951a6..c64df0f 100644 --- a/go.sum +++ b/go.sum @@ -145,8 +145,6 @@ github.com/mr-tron/base58 v1.2.0 h1:T/HDJBh4ZCPbU39/+c3rRvE0uKBQlU27+QI8LJ4t64o= github.com/mr-tron/base58 v1.2.0/go.mod h1:BinMc/sQntlIE1frQmRFPUoPA1Zkr8VRgBdjWI2mNwc= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= -github.com/nspcc-dev/bbolt v0.0.0-20250911202005-807225ebb0c8 h1:lYMHisGPtL70vqCe/M+cU27HMZcV2PTYTaRmO7qxhMQ= -github.com/nspcc-dev/bbolt v0.0.0-20250911202005-807225ebb0c8/go.mod h1:iYl+DCkSLXgVCeQWyC+kqS9V1fAQCA74JZtptwjNYpc= github.com/nspcc-dev/go-ordered-json v0.0.0-20250911084817-6fb4472993d1 h1:U3wvYzJi07NzN4I0fwt1Uznp92xKkfkTcAyC+TsxP9E= github.com/nspcc-dev/go-ordered-json v0.0.0-20250911084817-6fb4472993d1/go.mod h1:CHwf1nwquA6ecSfxmNF0YuemOPHAnRGoLuZUv/WPjeY= github.com/nspcc-dev/hrw/v2 v2.0.4 h1:o3Zh/2aF+IgGpvt414f46Ya20WG9u9vWxVd16ErFI8w= @@ -211,8 +209,14 @@ github.com/tklauser/go-sysconf v0.3.15 h1:VE89k0criAymJ/Os65CSn1IXaol+1wrsFHEB8O github.com/tklauser/go-sysconf v0.3.15/go.mod h1:Dmjwr6tYFIseJw7a3dRLJfsHAMXZ3nEnL/aZY+0IuI4= github.com/tklauser/numcpus v0.10.0 h1:18njr6LDBk1zuna922MgdjQuJFjrdppsZG60sHGfjso= github.com/tklauser/numcpus v0.10.0/go.mod h1:BiTKazU708GQTYF4mB+cmlpT2Is1gLk7XVuEeem8LsQ= +github.com/tutus-one/tutus-bolt v1.0.0 h1:+O167MPPixi8254zWs1lYwsZ6QBhJCaIJQf9Qc4u4q0= +github.com/tutus-one/tutus-bolt v1.0.0/go.mod h1:v5z98B9Ao/zkKsG8S9cwTovD1UsdN8mmdQTXiaBbPVo= github.com/tutus-one/tutus-consensus v1.0.0 h1:PFMXSSSYjTnbymoIjU2L30ckf92j2kVwrmtRnkuGlnY= github.com/tutus-one/tutus-consensus v1.0.0/go.mod h1:hpA/0rPM0Frdh9cowAp//vQTMN8j6Q0GYq1BFlpCLVM= +github.com/tutus-one/tutus-ordered-json v1.0.0 h1:/wPlNUwyqs+SUO2+Ra2sGJ2FrvQjIrh2McFDQ6moR7Y= +github.com/tutus-one/tutus-ordered-json v1.0.0/go.mod h1:M58J4PCtf7JauNaz2jgi8yKUygKMSqqG6YEa2rhRfuU= +github.com/tutus-one/tutus-rfc6979 v1.0.0 h1:eFPDOMle4Wv2RmC9DLTO4R6vjQjx5c6H9+RrdoFNeLM= +github.com/tutus-one/tutus-rfc6979 v1.0.0/go.mod h1:qary3d/z/0Zwb06/wqXv1/FHuP8rBJHrP66/8wDFaTA= github.com/twmb/murmur3 v1.1.8 h1:8Yt9taO/WN3l08xErzjeschgZU2QSrwm1kclYq+0aRg= github.com/twmb/murmur3 v1.1.8/go.mod h1:Qq/R7NUyOfr65zD+6Q5IHKsJLwP7exErjN6lyyq3OSQ= github.com/urfave/cli/v2 v2.27.7 h1:bH59vdhbjLv3LAvIu6gd0usJHgoTTPhCFib8qqOwXYU= diff --git a/internal/basicchain/basic.go b/internal/basicchain/basic.go index 599dda2..08ea765 100644 --- a/internal/basicchain/basic.go +++ b/internal/basicchain/basic.go @@ -14,7 +14,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/native/noderoles" "github.com/tutus-one/tutus-chain/pkg/encoding/fixedn" "github.com/tutus-one/tutus-chain/pkg/io" - "github.com/tutus-one/tutus-chain/pkg/neotest" + "github.com/tutus-one/tutus-chain/pkg/tutustest" "github.com/tutus-one/tutus-chain/pkg/rpcclient/nns" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/opcode" diff --git a/internal/contracts/contracts_test.go b/internal/contracts/contracts_test.go index f3358a7..ef17d3f 100644 --- a/internal/contracts/contracts_test.go +++ b/internal/contracts/contracts_test.go @@ -10,8 +10,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" "github.com/tutus-one/tutus-chain/pkg/io" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/smartcontract/callflag" "github.com/tutus-one/tutus-chain/pkg/smartcontract/manifest" diff --git a/pkg/compiler/interop_test.go b/pkg/compiler/interop_test.go index 0448c7a..86e4ef5 100644 --- a/pkg/compiler/interop_test.go +++ b/pkg/compiler/interop_test.go @@ -23,8 +23,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/encoding/address" "github.com/tutus-one/tutus-chain/pkg/encoding/base58" cinterop "github.com/tutus-one/tutus-chain/pkg/interop" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/smartcontract/callflag" "github.com/tutus-one/tutus-chain/pkg/smartcontract/manifest" @@ -555,39 +555,39 @@ func TestLenForNil(t *testing.T) { func TestCallTConversionErrors(t *testing.T) { t.Run("variable hash", func(t *testing.T) { src := `package foo - import "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + import "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" func Main() int { var hash string - return neogointernal.CallWithToken(hash, "method", 0).(int) + return tutusinternal.CallWithToken(hash, "method", 0).(int) }` _, err := compiler.Compile("foo.go", strings.NewReader(src)) require.Error(t, err) }) t.Run("bad hash", func(t *testing.T) { src := `package foo - import "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + import "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" func Main() int { - return neogointernal.CallWithToken("badstring", "method", 0).(int) + return tutusinternal.CallWithToken("badstring", "method", 0).(int) }` _, err := compiler.Compile("foo.go", strings.NewReader(src)) require.Error(t, err) }) t.Run("variable method", func(t *testing.T) { src := `package foo - import "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + import "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" func Main() int { var method string - return neogointernal.CallWithToken("\xf5\x63\xea\x40\xbc\x28\x3d\x4d\x0e\x05\xc4\x8e\xa3\x05\xb3\xf2\xa0\x73\x40\xef", method, 0).(int) + return tutusinternal.CallWithToken("\xf5\x63\xea\x40\xbc\x28\x3d\x4d\x0e\x05\xc4\x8e\xa3\x05\xb3\xf2\xa0\x73\x40\xef", method, 0).(int) }` _, err := compiler.Compile("foo.go", strings.NewReader(src)) require.Error(t, err) }) t.Run("variable flags", func(t *testing.T) { src := `package foo - import "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + import "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" func Main() { var flags int - neogointernal.CallWithTokenNoRet("\xf5\x63\xea\x40\xbc\x28\x3d\x4d\x0e\x05\xc4\x8e\xa3\x05\xb3\xf2\xa0\x73\x40\xef", "method", flags) + tutusinternal.CallWithTokenNoRet("\xf5\x63\xea\x40\xbc\x28\x3d\x4d\x0e\x05\xc4\x8e\xa3\x05\xb3\xf2\xa0\x73\x40\xef", "method", flags) }` _, err := compiler.Compile("foo.go", strings.NewReader(src)) require.Error(t, err) diff --git a/pkg/compiler/syscall_test.go b/pkg/compiler/syscall_test.go index 0d27c17..be1b763 100644 --- a/pkg/compiler/syscall_test.go +++ b/pkg/compiler/syscall_test.go @@ -253,9 +253,9 @@ func TestSyscallInGlobalInit(t *testing.T) { func TestOpcode(t *testing.T) { t.Run("1 argument", func(t *testing.T) { src := `package foo - import "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + import "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" func abs(a int) int { - return neogointernal.Opcode1("ABS", a).(int) + return tutusinternal.Opcode1("ABS", a).(int) } func Main() int { return abs(-42) @@ -264,10 +264,10 @@ func TestOpcode(t *testing.T) { }) t.Run("2 arguments", func(t *testing.T) { src := `package foo - import "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + import "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" func add3(a, b, c int) int { - return neogointernal.Opcode2("SUB", a, - neogointernal.Opcode2("SUB", b, c).(int)).(int) + return tutusinternal.Opcode2("SUB", a, + tutusinternal.Opcode2("SUB", b, c).(int)).(int) } func Main() int { return add3(53, 12, 1) diff --git a/pkg/core/basic_chain_test.go b/pkg/core/basic_chain_test.go index 7ba2da4..6270727 100644 --- a/pkg/core/basic_chain_test.go +++ b/pkg/core/basic_chain_test.go @@ -9,8 +9,8 @@ import ( "github.com/tutus-one/tutus-chain/internal/basicchain" "github.com/tutus-one/tutus-chain/pkg/core/chaindump" "github.com/tutus-one/tutus-chain/pkg/io" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/stretchr/testify/require" ) diff --git a/pkg/core/bench_test.go b/pkg/core/bench_test.go index 9fcf7fa..ed96deb 100644 --- a/pkg/core/bench_test.go +++ b/pkg/core/bench_test.go @@ -14,8 +14,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/storage/dbconfig" "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/wallet" "github.com/stretchr/testify/require" diff --git a/pkg/core/blockchain.go b/pkg/core/blockchain.go index 0a67f28..f7fb6d9 100644 --- a/pkg/core/blockchain.go +++ b/pkg/core/blockchain.go @@ -13,7 +13,7 @@ import ( "time" lru "github.com/hashicorp/golang-lru/v2" - json "github.com/nspcc-dev/go-ordered-json" + json "github.com/tutus-one/tutus-ordered-json" "github.com/tutus-one/tutus-chain/pkg/config" "github.com/tutus-one/tutus-chain/pkg/config/limits" "github.com/tutus-one/tutus-chain/pkg/core/block" diff --git a/pkg/core/blockchain_neotest_test.go b/pkg/core/blockchain_neotest_test.go index 57eddf6..abd88df 100644 --- a/pkg/core/blockchain_neotest_test.go +++ b/pkg/core/blockchain_neotest_test.go @@ -37,8 +37,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/crypto/keys" "github.com/tutus-one/tutus-chain/pkg/encoding/address" "github.com/tutus-one/tutus-chain/pkg/io" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/smartcontract/callflag" "github.com/tutus-one/tutus-chain/pkg/smartcontract/trigger" diff --git a/pkg/core/chaindump/dump_test.go b/pkg/core/chaindump/dump_test.go index ad38ead..b642732 100644 --- a/pkg/core/chaindump/dump_test.go +++ b/pkg/core/chaindump/dump_test.go @@ -9,8 +9,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/block" "github.com/tutus-one/tutus-chain/pkg/core/chaindump" "github.com/tutus-one/tutus-chain/pkg/io" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/stretchr/testify/require" ) diff --git a/pkg/core/custom_native_test.go b/pkg/core/custom_native_test.go index 47d0a1c..0153ebb 100644 --- a/pkg/core/custom_native_test.go +++ b/pkg/core/custom_native_test.go @@ -13,8 +13,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/smartcontract/callflag" "github.com/tutus-one/tutus-chain/pkg/smartcontract/manifest" diff --git a/pkg/core/interop/contract/account_test.go b/pkg/core/interop/contract/account_test.go index c4d6426..3669cda 100644 --- a/pkg/core/interop/contract/account_test.go +++ b/pkg/core/interop/contract/account_test.go @@ -12,8 +12,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/crypto/hash" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" "github.com/tutus-one/tutus-chain/pkg/io" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/emit" diff --git a/pkg/core/interop/contract/call_test.go b/pkg/core/interop/contract/call_test.go index 1c21fea..81df2b5 100644 --- a/pkg/core/interop/contract/call_test.go +++ b/pkg/core/interop/contract/call_test.go @@ -18,8 +18,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/native" "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/smartcontract/callflag" "github.com/tutus-one/tutus-chain/pkg/smartcontract/manifest" diff --git a/pkg/core/interop/runtime/ext_test.go b/pkg/core/interop/runtime/ext_test.go index 5337c04..63e3fb3 100644 --- a/pkg/core/interop/runtime/ext_test.go +++ b/pkg/core/interop/runtime/ext_test.go @@ -25,8 +25,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/crypto/keys" "github.com/tutus-one/tutus-chain/pkg/encoding/address" "github.com/tutus-one/tutus-chain/pkg/io" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/smartcontract/callflag" "github.com/tutus-one/tutus-chain/pkg/smartcontract/manifest" diff --git a/pkg/core/interop/storage/storage_test.go b/pkg/core/interop/storage/storage_test.go index ba6eb7d..4ee3fb8 100644 --- a/pkg/core/interop/storage/storage_test.go +++ b/pkg/core/interop/storage/storage_test.go @@ -17,8 +17,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/crypto/hash" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/smartcontract/callflag" "github.com/tutus-one/tutus-chain/pkg/smartcontract/manifest" "github.com/tutus-one/tutus-chain/pkg/smartcontract/nef" diff --git a/pkg/core/native/invocation_test.go b/pkg/core/native/invocation_test.go index 8ed77f6..1a78263 100644 --- a/pkg/core/native/invocation_test.go +++ b/pkg/core/native/invocation_test.go @@ -13,8 +13,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/crypto/hash" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/smartcontract/callflag" "github.com/tutus-one/tutus-chain/pkg/smartcontract/trigger" "github.com/tutus-one/tutus-chain/pkg/util" diff --git a/pkg/core/native/management_neotest_test.go b/pkg/core/native/management_neotest_test.go index 554115d..c4ecf34 100644 --- a/pkg/core/native/management_neotest_test.go +++ b/pkg/core/native/management_neotest_test.go @@ -8,8 +8,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/config" "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" "github.com/tutus-one/tutus-chain/pkg/core/state" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/smartcontract/manifest" "github.com/tutus-one/tutus-chain/pkg/smartcontract/nef" diff --git a/pkg/core/native/native_test/annos_test.go b/pkg/core/native/native_test/annos_test.go index feabaf4..9212c41 100644 --- a/pkg/core/native/native_test/annos_test.go +++ b/pkg/core/native/native_test/annos_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/require" "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" "github.com/tutus-one/tutus-chain/pkg/core/state" - "github.com/tutus-one/tutus-chain/pkg/neotest" + "github.com/tutus-one/tutus-chain/pkg/tutustest" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" ) diff --git a/pkg/core/native/native_test/collocatio_test.go b/pkg/core/native/native_test/collocatio_test.go index b79094a..bb1e2a3 100644 --- a/pkg/core/native/native_test/collocatio_test.go +++ b/pkg/core/native/native_test/collocatio_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/require" "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" "github.com/tutus-one/tutus-chain/pkg/core/state" - "github.com/tutus-one/tutus-chain/pkg/neotest" + "github.com/tutus-one/tutus-chain/pkg/tutustest" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" ) diff --git a/pkg/core/native/native_test/common_test.go b/pkg/core/native/native_test/common_test.go index f18a923..9baaf88 100644 --- a/pkg/core/native/native_test/common_test.go +++ b/pkg/core/native/native_test/common_test.go @@ -10,8 +10,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" "github.com/tutus-one/tutus-chain/pkg/io" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/smartcontract/callflag" "github.com/tutus-one/tutus-chain/pkg/vm/emit" "github.com/tutus-one/tutus-chain/pkg/vm/opcode" diff --git a/pkg/core/native/native_test/cryptolib_test.go b/pkg/core/native/native_test/cryptolib_test.go index 15c5e4d..83da312 100644 --- a/pkg/core/native/native_test/cryptolib_test.go +++ b/pkg/core/native/native_test/cryptolib_test.go @@ -14,8 +14,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/native" "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" "github.com/tutus-one/tutus-chain/pkg/io" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/smartcontract/callflag" "github.com/tutus-one/tutus-chain/pkg/vm/emit" "github.com/tutus-one/tutus-chain/pkg/vm/opcode" diff --git a/pkg/core/native/native_test/cryptolib_verification_test.go b/pkg/core/native/native_test/cryptolib_verification_test.go index c08d13c..253dcb2 100644 --- a/pkg/core/native/native_test/cryptolib_verification_test.go +++ b/pkg/core/native/native_test/cryptolib_verification_test.go @@ -13,7 +13,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/crypto/hash" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" "github.com/tutus-one/tutus-chain/pkg/io" - "github.com/tutus-one/tutus-chain/pkg/neotest" + "github.com/tutus-one/tutus-chain/pkg/tutustest" "github.com/tutus-one/tutus-chain/pkg/smartcontract/callflag" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/emit" diff --git a/pkg/core/native/native_test/designate_test.go b/pkg/core/native/native_test/designate_test.go index 4ea8e91..5d9746a 100644 --- a/pkg/core/native/native_test/designate_test.go +++ b/pkg/core/native/native_test/designate_test.go @@ -10,8 +10,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" "github.com/tutus-one/tutus-chain/pkg/io" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/smartcontract/callflag" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/emit" diff --git a/pkg/core/native/native_test/eligere_test.go b/pkg/core/native/native_test/eligere_test.go index b84519f..9c8da9a 100644 --- a/pkg/core/native/native_test/eligere_test.go +++ b/pkg/core/native/native_test/eligere_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/require" "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" "github.com/tutus-one/tutus-chain/pkg/core/state" - "github.com/tutus-one/tutus-chain/pkg/neotest" + "github.com/tutus-one/tutus-chain/pkg/tutustest" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" ) diff --git a/pkg/core/native/native_test/federation_test.go b/pkg/core/native/native_test/federation_test.go index 9a3de80..91067e7 100644 --- a/pkg/core/native/native_test/federation_test.go +++ b/pkg/core/native/native_test/federation_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/require" "github.com/tutus-one/tutus-chain/pkg/config" "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" - "github.com/tutus-one/tutus-chain/pkg/neotest" + "github.com/tutus-one/tutus-chain/pkg/tutustest" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" ) diff --git a/pkg/core/native/native_test/gas_test.go b/pkg/core/native/native_test/gas_test.go index 951187f..b7c4eff 100644 --- a/pkg/core/native/native_test/gas_test.go +++ b/pkg/core/native/native_test/gas_test.go @@ -9,8 +9,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/native/noderoles" "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/opcode" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" diff --git a/pkg/core/native/native_test/generate_expected_test.go b/pkg/core/native/native_test/generate_expected_test.go index 0272fe1..95d39e1 100644 --- a/pkg/core/native/native_test/generate_expected_test.go +++ b/pkg/core/native/native_test/generate_expected_test.go @@ -1,165 +1,165 @@ -package native_test - -import ( - "encoding/json" - "fmt" - "testing" - - "github.com/tutus-one/tutus-chain/pkg/config" - "github.com/tutus-one/tutus-chain/pkg/core/state" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" -) - -// TestGenerateExpectedContractStates outputs the current contract states as JSON -// for updating the defaultCSS, cockatriceCSS, echidnaCSS, and faunCSS maps. -// Run with: go test -v -run TestGenerateExpectedContractStates -func TestGenerateExpectedContractStates(t *testing.T) { - const ( - cockatriceHeight = 3 - domovoiHeight = 5 - echidnaHeight = 6 - faunHeight = 7 - ) - bc, acc := chain.NewSingleWithCustomConfig(t, func(cfg *config.Blockchain) { - cfg.Hardforks = map[string]uint32{ - config.HFAspidochelone.String(): 0, - config.HFBasilisk.String(): 0, - config.HFCockatrice.String(): cockatriceHeight, - config.HFDomovoi.String(): domovoiHeight, - config.HFEchidna.String(): echidnaHeight, - config.HFFaun.String(): faunHeight, - } - }) - e := neotest.NewExecutor(t, bc, acc, acc) - - // Generate defaultCSS (genesis state) - fmt.Println("\n=== defaultCSS (genesis) ===") - fmt.Println("defaultCSS = map[string]string{") - natives := bc.GetNatives() - for _, cs := range natives { - csFull := state.Contract{ - ContractBase: cs.ContractBase, - UpdateCounter: 0, - } - jBytes, err := json.Marshal(csFull) - if err != nil { - t.Fatal(err) - } - fmt.Printf("\tnativenames.%s: `%s`,\n", getConstName(cs.Manifest.Name), string(jBytes)) - } - fmt.Println("}") - - // Generate cockatriceCSS - e.GenerateNewBlocks(t, cockatriceHeight) - fmt.Println("\n=== cockatriceCSS ===") - fmt.Println("cockatriceCSS = map[string]string{") - natives = bc.GetNatives() - for _, cs := range natives { - csFull := state.Contract{ - ContractBase: cs.ContractBase, - UpdateCounter: 0, - } - jBytes, err := json.Marshal(csFull) - if err != nil { - t.Fatal(err) - } - fmt.Printf("\tnativenames.%s: `%s`,\n", getConstName(cs.Manifest.Name), string(jBytes)) - } - fmt.Println("}") - - // Generate echidnaCSS - e.GenerateNewBlocks(t, echidnaHeight-cockatriceHeight) - fmt.Println("\n=== echidnaCSS ===") - fmt.Println("echidnaCSS = map[string]string{") - natives = bc.GetNatives() - for _, cs := range natives { - csFull := state.Contract{ - ContractBase: cs.ContractBase, - UpdateCounter: 0, - } - jBytes, err := json.Marshal(csFull) - if err != nil { - t.Fatal(err) - } - fmt.Printf("\tnativenames.%s: `%s`,\n", getConstName(cs.Manifest.Name), string(jBytes)) - } - fmt.Println("}") - - // Generate faunCSS - e.GenerateNewBlocks(t, faunHeight-echidnaHeight) - fmt.Println("\n=== faunCSS ===") - fmt.Println("faunCSS = map[string]string{") - natives = bc.GetNatives() - for _, cs := range natives { - csFull := state.Contract{ - ContractBase: cs.ContractBase, - UpdateCounter: 0, - } - jBytes, err := json.Marshal(csFull) - if err != nil { - t.Fatal(err) - } - fmt.Printf("\tnativenames.%s: `%s`,\n", getConstName(cs.Manifest.Name), string(jBytes)) - } - fmt.Println("}") -} - -func getConstName(name string) string { - switch name { - case "ContractManagement": - return "Management" - case "StdLib": - return "StdLib" - case "CryptoLib": - return "CryptoLib" - case "LedgerContract": - return "Ledger" - case "TutusToken": - return "Tutus" - case "LubToken": - return "Lub" - case "PolicyContract": - return "Policy" - case "OracleContract": - return "Oracle" - case "RoleManagement": - return "Designation" - case "Notary": - return "Notary" - case "VitaToken": - return "Vita" - case "VtsToken": - return "Vts" - case "LexContract": - return "Lex" - case "ScireContract": - return "Scire" - case "SalusContract": - return "Salus" - case "SeseContract": - return "Sese" - case "TributeContract": - return "Tribute" - case "EligereContract": - return "Eligere" - case "OpusContract": - return "Opus" - case "PalamContract": - return "Palam" - case "PonsContract": - return "Pons" - case "CollocatioContract": - return "Collocatio" - case "AnnosContract": - return "Annos" - case "RoleRegistry": - return "RoleRegistry" - case "Treasury": - return "Treasury" - case "Federation": - return "Federation" - default: - return name - } -} +package native_test + +import ( + "encoding/json" + "fmt" + "testing" + + "github.com/tutus-one/tutus-chain/pkg/config" + "github.com/tutus-one/tutus-chain/pkg/core/state" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" +) + +// TestGenerateExpectedContractStates outputs the current contract states as JSON +// for updating the defaultCSS, cockatriceCSS, echidnaCSS, and faunCSS maps. +// Run with: go test -v -run TestGenerateExpectedContractStates +func TestGenerateExpectedContractStates(t *testing.T) { + const ( + cockatriceHeight = 3 + domovoiHeight = 5 + echidnaHeight = 6 + faunHeight = 7 + ) + bc, acc := chain.NewSingleWithCustomConfig(t, func(cfg *config.Blockchain) { + cfg.Hardforks = map[string]uint32{ + config.HFAspidochelone.String(): 0, + config.HFBasilisk.String(): 0, + config.HFCockatrice.String(): cockatriceHeight, + config.HFDomovoi.String(): domovoiHeight, + config.HFEchidna.String(): echidnaHeight, + config.HFFaun.String(): faunHeight, + } + }) + e := neotest.NewExecutor(t, bc, acc, acc) + + // Generate defaultCSS (genesis state) + fmt.Println("\n=== defaultCSS (genesis) ===") + fmt.Println("defaultCSS = map[string]string{") + natives := bc.GetNatives() + for _, cs := range natives { + csFull := state.Contract{ + ContractBase: cs.ContractBase, + UpdateCounter: 0, + } + jBytes, err := json.Marshal(csFull) + if err != nil { + t.Fatal(err) + } + fmt.Printf("\tnativenames.%s: `%s`,\n", getConstName(cs.Manifest.Name), string(jBytes)) + } + fmt.Println("}") + + // Generate cockatriceCSS + e.GenerateNewBlocks(t, cockatriceHeight) + fmt.Println("\n=== cockatriceCSS ===") + fmt.Println("cockatriceCSS = map[string]string{") + natives = bc.GetNatives() + for _, cs := range natives { + csFull := state.Contract{ + ContractBase: cs.ContractBase, + UpdateCounter: 0, + } + jBytes, err := json.Marshal(csFull) + if err != nil { + t.Fatal(err) + } + fmt.Printf("\tnativenames.%s: `%s`,\n", getConstName(cs.Manifest.Name), string(jBytes)) + } + fmt.Println("}") + + // Generate echidnaCSS + e.GenerateNewBlocks(t, echidnaHeight-cockatriceHeight) + fmt.Println("\n=== echidnaCSS ===") + fmt.Println("echidnaCSS = map[string]string{") + natives = bc.GetNatives() + for _, cs := range natives { + csFull := state.Contract{ + ContractBase: cs.ContractBase, + UpdateCounter: 0, + } + jBytes, err := json.Marshal(csFull) + if err != nil { + t.Fatal(err) + } + fmt.Printf("\tnativenames.%s: `%s`,\n", getConstName(cs.Manifest.Name), string(jBytes)) + } + fmt.Println("}") + + // Generate faunCSS + e.GenerateNewBlocks(t, faunHeight-echidnaHeight) + fmt.Println("\n=== faunCSS ===") + fmt.Println("faunCSS = map[string]string{") + natives = bc.GetNatives() + for _, cs := range natives { + csFull := state.Contract{ + ContractBase: cs.ContractBase, + UpdateCounter: 0, + } + jBytes, err := json.Marshal(csFull) + if err != nil { + t.Fatal(err) + } + fmt.Printf("\tnativenames.%s: `%s`,\n", getConstName(cs.Manifest.Name), string(jBytes)) + } + fmt.Println("}") +} + +func getConstName(name string) string { + switch name { + case "ContractManagement": + return "Management" + case "StdLib": + return "StdLib" + case "CryptoLib": + return "CryptoLib" + case "LedgerContract": + return "Ledger" + case "TutusToken": + return "Tutus" + case "LubToken": + return "Lub" + case "PolicyContract": + return "Policy" + case "OracleContract": + return "Oracle" + case "RoleManagement": + return "Designation" + case "Notary": + return "Notary" + case "VitaToken": + return "Vita" + case "VtsToken": + return "Vts" + case "LexContract": + return "Lex" + case "ScireContract": + return "Scire" + case "SalusContract": + return "Salus" + case "SeseContract": + return "Sese" + case "TributeContract": + return "Tribute" + case "EligereContract": + return "Eligere" + case "OpusContract": + return "Opus" + case "PalamContract": + return "Palam" + case "PonsContract": + return "Pons" + case "CollocatioContract": + return "Collocatio" + case "AnnosContract": + return "Annos" + case "RoleRegistry": + return "RoleRegistry" + case "Treasury": + return "Treasury" + case "Federation": + return "Federation" + default: + return name + } +} diff --git a/pkg/core/native/native_test/ledger_test.go b/pkg/core/native/native_test/ledger_test.go index 610feef..4fbcedc 100644 --- a/pkg/core/native/native_test/ledger_test.go +++ b/pkg/core/native/native_test/ledger_test.go @@ -10,8 +10,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/config" "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/opcode" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" diff --git a/pkg/core/native/native_test/lex_test.go b/pkg/core/native/native_test/lex_test.go index 5caa237..9b871b5 100644 --- a/pkg/core/native/native_test/lex_test.go +++ b/pkg/core/native/native_test/lex_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/require" "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" "github.com/tutus-one/tutus-chain/pkg/core/state" - "github.com/tutus-one/tutus-chain/pkg/neotest" + "github.com/tutus-one/tutus-chain/pkg/tutustest" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" ) diff --git a/pkg/core/native/native_test/management_test.go b/pkg/core/native/native_test/management_test.go index 3c99071..fd6cc31 100644 --- a/pkg/core/native/native_test/management_test.go +++ b/pkg/core/native/native_test/management_test.go @@ -8,7 +8,7 @@ import ( "strings" "testing" - ojson "github.com/nspcc-dev/go-ordered-json" + ojson "github.com/tutus-one/tutus-ordered-json" "github.com/tutus-one/tutus-chain/internal/contracts" "github.com/tutus-one/tutus-chain/pkg/compiler" "github.com/tutus-one/tutus-chain/pkg/config" @@ -23,8 +23,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" "github.com/tutus-one/tutus-chain/pkg/io" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/smartcontract/callflag" "github.com/tutus-one/tutus-chain/pkg/smartcontract/manifest" diff --git a/pkg/core/native/native_test/neo_test.go b/pkg/core/native/native_test/neo_test.go index 582d809..197276a 100644 --- a/pkg/core/native/native_test/neo_test.go +++ b/pkg/core/native/native_test/neo_test.go @@ -22,8 +22,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/crypto/hash" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" "github.com/tutus-one/tutus-chain/pkg/io" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/smartcontract/callflag" "github.com/tutus-one/tutus-chain/pkg/smartcontract/trigger" diff --git a/pkg/core/native/native_test/notary_test.go b/pkg/core/native/native_test/notary_test.go index d247191..2787f75 100644 --- a/pkg/core/native/native_test/notary_test.go +++ b/pkg/core/native/native_test/notary_test.go @@ -13,8 +13,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/native/noderoles" "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/rpcclient/notary" "github.com/tutus-one/tutus-chain/pkg/smartcontract/manifest" "github.com/tutus-one/tutus-chain/pkg/util" diff --git a/pkg/core/native/native_test/opus_test.go b/pkg/core/native/native_test/opus_test.go index 0e60e14..405f81e 100644 --- a/pkg/core/native/native_test/opus_test.go +++ b/pkg/core/native/native_test/opus_test.go @@ -7,7 +7,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/crypto/hash" "github.com/stretchr/testify/require" "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" - "github.com/tutus-one/tutus-chain/pkg/neotest" + "github.com/tutus-one/tutus-chain/pkg/tutustest" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" ) diff --git a/pkg/core/native/native_test/oracle_test.go b/pkg/core/native/native_test/oracle_test.go index f8dd105..6dd3cf1 100644 --- a/pkg/core/native/native_test/oracle_test.go +++ b/pkg/core/native/native_test/oracle_test.go @@ -14,7 +14,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/native/noderoles" "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" - "github.com/tutus-one/tutus-chain/pkg/neotest" + "github.com/tutus-one/tutus-chain/pkg/tutustest" "github.com/tutus-one/tutus-chain/pkg/smartcontract/trigger" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" "github.com/stretchr/testify/require" diff --git a/pkg/core/native/native_test/palam_test.go b/pkg/core/native/native_test/palam_test.go index f0b3723..baa9fef 100644 --- a/pkg/core/native/native_test/palam_test.go +++ b/pkg/core/native/native_test/palam_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/require" "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" "github.com/tutus-one/tutus-chain/pkg/core/state" - "github.com/tutus-one/tutus-chain/pkg/neotest" + "github.com/tutus-one/tutus-chain/pkg/tutustest" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" ) diff --git a/pkg/core/native/native_test/policy_test.go b/pkg/core/native/native_test/policy_test.go index 6ed52cb..5b9ca67 100644 --- a/pkg/core/native/native_test/policy_test.go +++ b/pkg/core/native/native_test/policy_test.go @@ -18,8 +18,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/io" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/smartcontract/callflag" "github.com/tutus-one/tutus-chain/pkg/smartcontract/manifest" "github.com/tutus-one/tutus-chain/pkg/util" diff --git a/pkg/core/native/native_test/pons_test.go b/pkg/core/native/native_test/pons_test.go index 67e17a1..bef83b6 100644 --- a/pkg/core/native/native_test/pons_test.go +++ b/pkg/core/native/native_test/pons_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/require" "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" "github.com/tutus-one/tutus-chain/pkg/core/state" - "github.com/tutus-one/tutus-chain/pkg/neotest" + "github.com/tutus-one/tutus-chain/pkg/tutustest" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" ) diff --git a/pkg/core/native/native_test/role_registry_test.go b/pkg/core/native/native_test/role_registry_test.go index de243aa..7fc91d4 100644 --- a/pkg/core/native/native_test/role_registry_test.go +++ b/pkg/core/native/native_test/role_registry_test.go @@ -1,296 +1,296 @@ -package native_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" -) - -func newRoleRegistryClient(t *testing.T) *neotest.ContractInvoker { - return newNativeClient(t, nativenames.RoleRegistry) -} - -// TestRoleRegistry_BuiltinRoles tests that built-in roles are created at initialization. -func TestRoleRegistry_BuiltinRoles(t *testing.T) { - c := newRoleRegistryClient(t) - - // Check totalRoles returns at least 4 (the built-in roles) - c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - count, err := stack[0].TryInteger() - require.NoError(t, err) - require.GreaterOrEqual(t, count.Int64(), int64(4)) - }, "totalRoles") - - // Check COMMITTEE role exists (ID=1) - c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - // Should be an array (role struct) - arr, ok := stack[0].Value().([]stackitem.Item) - require.True(t, ok, "expected array for role") - require.Equal(t, 7, len(arr)) // Role has 7 fields - - // Check role ID is 1 - id, err := arr[0].TryInteger() - require.NoError(t, err) - require.Equal(t, int64(1), id.Int64()) - - // Check name is COMMITTEE - name, err := arr[1].TryBytes() - require.NoError(t, err) - require.Equal(t, "COMMITTEE", string(name)) - - // Check role is active - active, err := arr[6].TryBool() - require.NoError(t, err) - require.True(t, active) - }, "getRole", 1) - - // Check REGISTRAR role exists (ID=2) - c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - arr, ok := stack[0].Value().([]stackitem.Item) - require.True(t, ok, "expected array for role") - name, err := arr[1].TryBytes() - require.NoError(t, err) - require.Equal(t, "REGISTRAR", string(name)) - }, "getRole", 2) - - // Check ATTESTOR role exists (ID=3) - c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - arr, ok := stack[0].Value().([]stackitem.Item) - require.True(t, ok, "expected array for role") - name, err := arr[1].TryBytes() - require.NoError(t, err) - require.Equal(t, "ATTESTOR", string(name)) - }, "getRole", 3) - - // Check OPERATOR role exists (ID=4) - c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - arr, ok := stack[0].Value().([]stackitem.Item) - require.True(t, ok, "expected array for role") - name, err := arr[1].TryBytes() - require.NoError(t, err) - require.Equal(t, "OPERATOR", string(name)) - }, "getRole", 4) -} - -// TestRoleRegistry_GetRoleByName tests looking up roles by name. -func TestRoleRegistry_GetRoleByName(t *testing.T) { - c := newRoleRegistryClient(t) - - // Look up COMMITTEE by name - c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - arr, ok := stack[0].Value().([]stackitem.Item) - require.True(t, ok, "expected array for role") - id, err := arr[0].TryInteger() - require.NoError(t, err) - require.Equal(t, int64(1), id.Int64()) - }, "getRoleByName", "COMMITTEE") - - // Look up non-existent role by name - c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - require.Nil(t, stack[0].Value()) - }, "getRoleByName", "NONEXISTENT") -} - -// TestRoleRegistry_HasRole tests checking if an address has a role. -func TestRoleRegistry_HasRole(t *testing.T) { - c := newRoleRegistryClient(t) - e := c.Executor - - acc := e.NewAccount(t) - - // Account should not have COMMITTEE role initially - c.Invoke(t, false, "hasRole", acc.ScriptHash(), 1) - - // Grant COMMITTEE role (committee only) - committeeInvoker := c.WithSigners(c.Committee) - committeeInvoker.Invoke(t, true, "grantRole", acc.ScriptHash(), 1, 0) - - // Now account should have COMMITTEE role - c.Invoke(t, true, "hasRole", acc.ScriptHash(), 1) -} - -// TestRoleRegistry_GrantRevokeRole tests granting and revoking roles. -func TestRoleRegistry_GrantRevokeRole(t *testing.T) { - c := newRoleRegistryClient(t) - e := c.Executor - - acc := e.NewAccount(t) - committeeInvoker := c.WithSigners(c.Committee) - - // Non-committee cannot grant roles - userInvoker := c.WithSigners(acc) - userInvoker.InvokeFail(t, "caller is not a committee member", "grantRole", acc.ScriptHash(), 2, 0) - - // Committee can grant role - committeeInvoker.Invoke(t, true, "grantRole", acc.ScriptHash(), 2, 0) - - // Check role is granted - c.Invoke(t, true, "hasRole", acc.ScriptHash(), 2) - - // Get roles for address - c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - arr, ok := stack[0].Value().([]stackitem.Item) - require.True(t, ok, "expected array") - require.GreaterOrEqual(t, len(arr), 1) - }, "getRolesForAddress", acc.ScriptHash()) - - // Non-committee cannot revoke roles - userInvoker.InvokeFail(t, "caller is not a committee member", "revokeRole", acc.ScriptHash(), 2) - - // Committee can revoke role - committeeInvoker.Invoke(t, true, "revokeRole", acc.ScriptHash(), 2) - - // Check role is revoked - c.Invoke(t, false, "hasRole", acc.ScriptHash(), 2) -} - -// TestRoleRegistry_CreateRole tests creating custom roles. -func TestRoleRegistry_CreateRole(t *testing.T) { - c := newRoleRegistryClient(t) - e := c.Executor - - acc := e.NewAccount(t) - committeeInvoker := c.WithSigners(c.Committee) - - // Non-committee cannot create roles - userInvoker := c.WithSigners(acc) - userInvoker.InvokeFail(t, "caller is not a committee member", "createRole", "CUSTOM_ROLE", "A custom role", 0) - - // Committee can create role - committeeInvoker.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - roleID, err := stack[0].TryInteger() - require.NoError(t, err) - require.GreaterOrEqual(t, roleID.Int64(), int64(5)) // Custom roles start at 5 - }, "createRole", "CUSTOM_ROLE", "A custom role", 0) - - // Verify role exists - c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - arr, ok := stack[0].Value().([]stackitem.Item) - require.True(t, ok, "expected array for role") - name, err := arr[1].TryBytes() - require.NoError(t, err) - require.Equal(t, "CUSTOM_ROLE", string(name)) - }, "getRoleByName", "CUSTOM_ROLE") - - // Cannot create duplicate role name - committeeInvoker.InvokeFail(t, "role name already exists", "createRole", "CUSTOM_ROLE", "Duplicate", 0) -} - -// TestRoleRegistry_DeleteRole tests deleting (deactivating) roles. -func TestRoleRegistry_DeleteRole(t *testing.T) { - c := newRoleRegistryClient(t) - committeeInvoker := c.WithSigners(c.Committee) - - // Create a custom role first - var customRoleID int64 - committeeInvoker.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - roleID, _ := stack[0].TryInteger() - customRoleID = roleID.Int64() - }, "createRole", "DELETE_TEST", "Role to delete", 0) - - // Cannot delete built-in roles - committeeInvoker.InvokeFail(t, "cannot modify built-in role", "deleteRole", 1) - committeeInvoker.InvokeFail(t, "cannot modify built-in role", "deleteRole", 2) - committeeInvoker.InvokeFail(t, "cannot modify built-in role", "deleteRole", 3) - committeeInvoker.InvokeFail(t, "cannot modify built-in role", "deleteRole", 4) - - // Can delete custom role - committeeInvoker.Invoke(t, true, "deleteRole", customRoleID) - - // Verify role is deactivated (still exists but not active) - c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - arr, ok := stack[0].Value().([]stackitem.Item) - require.True(t, ok, "expected array for role") - active, err := arr[6].TryBool() - require.NoError(t, err) - require.False(t, active) - }, "getRole", customRoleID) -} - -// TestRoleRegistry_Permissions tests assigning and checking permissions. -func TestRoleRegistry_Permissions(t *testing.T) { - c := newRoleRegistryClient(t) - e := c.Executor - - acc := e.NewAccount(t) - committeeInvoker := c.WithSigners(c.Committee) - - // Create a custom role - var customRoleID int64 - committeeInvoker.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - roleID, _ := stack[0].TryInteger() - customRoleID = roleID.Int64() - }, "createRole", "PERM_TEST", "Permission test role", 0) - - // Assign permission to role - committeeInvoker.Invoke(t, true, "assignPermission", customRoleID, "documents", "read", 0) - - // Grant role to account - committeeInvoker.Invoke(t, true, "grantRole", acc.ScriptHash(), customRoleID, 0) - - // Check account has permission - c.Invoke(t, true, "hasPermission", acc.ScriptHash(), "documents", "read", 0) - - // Check account does NOT have other permission - c.Invoke(t, false, "hasPermission", acc.ScriptHash(), "documents", "write", 0) - - // Get permissions for role - c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - arr, ok := stack[0].Value().([]stackitem.Item) - require.True(t, ok, "expected array") - require.Equal(t, 1, len(arr)) - }, "getPermissions", customRoleID) - - // Remove permission - committeeInvoker.Invoke(t, true, "removePermission", customRoleID, "documents", "read") - - // Check permission is gone - c.Invoke(t, false, "hasPermission", acc.ScriptHash(), "documents", "read", 0) -} - -// TestRoleRegistry_RoleHierarchy tests role hierarchy (parent roles). -func TestRoleRegistry_RoleHierarchy(t *testing.T) { - c := newRoleRegistryClient(t) - e := c.Executor - - acc := e.NewAccount(t) - committeeInvoker := c.WithSigners(c.Committee) - - // Create parent role - var parentRoleID int64 - committeeInvoker.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - roleID, _ := stack[0].TryInteger() - parentRoleID = roleID.Int64() - }, "createRole", "PARENT_ROLE", "Parent role", 0) - - // Create child role with parent - var childRoleID int64 - committeeInvoker.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - roleID, _ := stack[0].TryInteger() - childRoleID = roleID.Int64() - }, "createRole", "CHILD_ROLE", "Child role", parentRoleID) - - // Grant child role to account - committeeInvoker.Invoke(t, true, "grantRole", acc.ScriptHash(), childRoleID, 0) - - // Check account has child role - c.Invoke(t, true, "hasRole", acc.ScriptHash(), childRoleID) - - // Check account ALSO has parent role through hierarchy - c.Invoke(t, true, "hasRole", acc.ScriptHash(), parentRoleID) -} +package native_test + +import ( + "testing" + + "github.com/stretchr/testify/require" + "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" +) + +func newRoleRegistryClient(t *testing.T) *neotest.ContractInvoker { + return newNativeClient(t, nativenames.RoleRegistry) +} + +// TestRoleRegistry_BuiltinRoles tests that built-in roles are created at initialization. +func TestRoleRegistry_BuiltinRoles(t *testing.T) { + c := newRoleRegistryClient(t) + + // Check totalRoles returns at least 4 (the built-in roles) + c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + count, err := stack[0].TryInteger() + require.NoError(t, err) + require.GreaterOrEqual(t, count.Int64(), int64(4)) + }, "totalRoles") + + // Check COMMITTEE role exists (ID=1) + c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + // Should be an array (role struct) + arr, ok := stack[0].Value().([]stackitem.Item) + require.True(t, ok, "expected array for role") + require.Equal(t, 7, len(arr)) // Role has 7 fields + + // Check role ID is 1 + id, err := arr[0].TryInteger() + require.NoError(t, err) + require.Equal(t, int64(1), id.Int64()) + + // Check name is COMMITTEE + name, err := arr[1].TryBytes() + require.NoError(t, err) + require.Equal(t, "COMMITTEE", string(name)) + + // Check role is active + active, err := arr[6].TryBool() + require.NoError(t, err) + require.True(t, active) + }, "getRole", 1) + + // Check REGISTRAR role exists (ID=2) + c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + arr, ok := stack[0].Value().([]stackitem.Item) + require.True(t, ok, "expected array for role") + name, err := arr[1].TryBytes() + require.NoError(t, err) + require.Equal(t, "REGISTRAR", string(name)) + }, "getRole", 2) + + // Check ATTESTOR role exists (ID=3) + c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + arr, ok := stack[0].Value().([]stackitem.Item) + require.True(t, ok, "expected array for role") + name, err := arr[1].TryBytes() + require.NoError(t, err) + require.Equal(t, "ATTESTOR", string(name)) + }, "getRole", 3) + + // Check OPERATOR role exists (ID=4) + c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + arr, ok := stack[0].Value().([]stackitem.Item) + require.True(t, ok, "expected array for role") + name, err := arr[1].TryBytes() + require.NoError(t, err) + require.Equal(t, "OPERATOR", string(name)) + }, "getRole", 4) +} + +// TestRoleRegistry_GetRoleByName tests looking up roles by name. +func TestRoleRegistry_GetRoleByName(t *testing.T) { + c := newRoleRegistryClient(t) + + // Look up COMMITTEE by name + c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + arr, ok := stack[0].Value().([]stackitem.Item) + require.True(t, ok, "expected array for role") + id, err := arr[0].TryInteger() + require.NoError(t, err) + require.Equal(t, int64(1), id.Int64()) + }, "getRoleByName", "COMMITTEE") + + // Look up non-existent role by name + c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + require.Nil(t, stack[0].Value()) + }, "getRoleByName", "NONEXISTENT") +} + +// TestRoleRegistry_HasRole tests checking if an address has a role. +func TestRoleRegistry_HasRole(t *testing.T) { + c := newRoleRegistryClient(t) + e := c.Executor + + acc := e.NewAccount(t) + + // Account should not have COMMITTEE role initially + c.Invoke(t, false, "hasRole", acc.ScriptHash(), 1) + + // Grant COMMITTEE role (committee only) + committeeInvoker := c.WithSigners(c.Committee) + committeeInvoker.Invoke(t, true, "grantRole", acc.ScriptHash(), 1, 0) + + // Now account should have COMMITTEE role + c.Invoke(t, true, "hasRole", acc.ScriptHash(), 1) +} + +// TestRoleRegistry_GrantRevokeRole tests granting and revoking roles. +func TestRoleRegistry_GrantRevokeRole(t *testing.T) { + c := newRoleRegistryClient(t) + e := c.Executor + + acc := e.NewAccount(t) + committeeInvoker := c.WithSigners(c.Committee) + + // Non-committee cannot grant roles + userInvoker := c.WithSigners(acc) + userInvoker.InvokeFail(t, "caller is not a committee member", "grantRole", acc.ScriptHash(), 2, 0) + + // Committee can grant role + committeeInvoker.Invoke(t, true, "grantRole", acc.ScriptHash(), 2, 0) + + // Check role is granted + c.Invoke(t, true, "hasRole", acc.ScriptHash(), 2) + + // Get roles for address + c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + arr, ok := stack[0].Value().([]stackitem.Item) + require.True(t, ok, "expected array") + require.GreaterOrEqual(t, len(arr), 1) + }, "getRolesForAddress", acc.ScriptHash()) + + // Non-committee cannot revoke roles + userInvoker.InvokeFail(t, "caller is not a committee member", "revokeRole", acc.ScriptHash(), 2) + + // Committee can revoke role + committeeInvoker.Invoke(t, true, "revokeRole", acc.ScriptHash(), 2) + + // Check role is revoked + c.Invoke(t, false, "hasRole", acc.ScriptHash(), 2) +} + +// TestRoleRegistry_CreateRole tests creating custom roles. +func TestRoleRegistry_CreateRole(t *testing.T) { + c := newRoleRegistryClient(t) + e := c.Executor + + acc := e.NewAccount(t) + committeeInvoker := c.WithSigners(c.Committee) + + // Non-committee cannot create roles + userInvoker := c.WithSigners(acc) + userInvoker.InvokeFail(t, "caller is not a committee member", "createRole", "CUSTOM_ROLE", "A custom role", 0) + + // Committee can create role + committeeInvoker.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + roleID, err := stack[0].TryInteger() + require.NoError(t, err) + require.GreaterOrEqual(t, roleID.Int64(), int64(5)) // Custom roles start at 5 + }, "createRole", "CUSTOM_ROLE", "A custom role", 0) + + // Verify role exists + c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + arr, ok := stack[0].Value().([]stackitem.Item) + require.True(t, ok, "expected array for role") + name, err := arr[1].TryBytes() + require.NoError(t, err) + require.Equal(t, "CUSTOM_ROLE", string(name)) + }, "getRoleByName", "CUSTOM_ROLE") + + // Cannot create duplicate role name + committeeInvoker.InvokeFail(t, "role name already exists", "createRole", "CUSTOM_ROLE", "Duplicate", 0) +} + +// TestRoleRegistry_DeleteRole tests deleting (deactivating) roles. +func TestRoleRegistry_DeleteRole(t *testing.T) { + c := newRoleRegistryClient(t) + committeeInvoker := c.WithSigners(c.Committee) + + // Create a custom role first + var customRoleID int64 + committeeInvoker.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + roleID, _ := stack[0].TryInteger() + customRoleID = roleID.Int64() + }, "createRole", "DELETE_TEST", "Role to delete", 0) + + // Cannot delete built-in roles + committeeInvoker.InvokeFail(t, "cannot modify built-in role", "deleteRole", 1) + committeeInvoker.InvokeFail(t, "cannot modify built-in role", "deleteRole", 2) + committeeInvoker.InvokeFail(t, "cannot modify built-in role", "deleteRole", 3) + committeeInvoker.InvokeFail(t, "cannot modify built-in role", "deleteRole", 4) + + // Can delete custom role + committeeInvoker.Invoke(t, true, "deleteRole", customRoleID) + + // Verify role is deactivated (still exists but not active) + c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + arr, ok := stack[0].Value().([]stackitem.Item) + require.True(t, ok, "expected array for role") + active, err := arr[6].TryBool() + require.NoError(t, err) + require.False(t, active) + }, "getRole", customRoleID) +} + +// TestRoleRegistry_Permissions tests assigning and checking permissions. +func TestRoleRegistry_Permissions(t *testing.T) { + c := newRoleRegistryClient(t) + e := c.Executor + + acc := e.NewAccount(t) + committeeInvoker := c.WithSigners(c.Committee) + + // Create a custom role + var customRoleID int64 + committeeInvoker.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + roleID, _ := stack[0].TryInteger() + customRoleID = roleID.Int64() + }, "createRole", "PERM_TEST", "Permission test role", 0) + + // Assign permission to role + committeeInvoker.Invoke(t, true, "assignPermission", customRoleID, "documents", "read", 0) + + // Grant role to account + committeeInvoker.Invoke(t, true, "grantRole", acc.ScriptHash(), customRoleID, 0) + + // Check account has permission + c.Invoke(t, true, "hasPermission", acc.ScriptHash(), "documents", "read", 0) + + // Check account does NOT have other permission + c.Invoke(t, false, "hasPermission", acc.ScriptHash(), "documents", "write", 0) + + // Get permissions for role + c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + arr, ok := stack[0].Value().([]stackitem.Item) + require.True(t, ok, "expected array") + require.Equal(t, 1, len(arr)) + }, "getPermissions", customRoleID) + + // Remove permission + committeeInvoker.Invoke(t, true, "removePermission", customRoleID, "documents", "read") + + // Check permission is gone + c.Invoke(t, false, "hasPermission", acc.ScriptHash(), "documents", "read", 0) +} + +// TestRoleRegistry_RoleHierarchy tests role hierarchy (parent roles). +func TestRoleRegistry_RoleHierarchy(t *testing.T) { + c := newRoleRegistryClient(t) + e := c.Executor + + acc := e.NewAccount(t) + committeeInvoker := c.WithSigners(c.Committee) + + // Create parent role + var parentRoleID int64 + committeeInvoker.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + roleID, _ := stack[0].TryInteger() + parentRoleID = roleID.Int64() + }, "createRole", "PARENT_ROLE", "Parent role", 0) + + // Create child role with parent + var childRoleID int64 + committeeInvoker.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + roleID, _ := stack[0].TryInteger() + childRoleID = roleID.Int64() + }, "createRole", "CHILD_ROLE", "Child role", parentRoleID) + + // Grant child role to account + committeeInvoker.Invoke(t, true, "grantRole", acc.ScriptHash(), childRoleID, 0) + + // Check account has child role + c.Invoke(t, true, "hasRole", acc.ScriptHash(), childRoleID) + + // Check account ALSO has parent role through hierarchy + c.Invoke(t, true, "hasRole", acc.ScriptHash(), parentRoleID) +} diff --git a/pkg/core/native/native_test/salus_test.go b/pkg/core/native/native_test/salus_test.go index 742286d..4c6fbd0 100644 --- a/pkg/core/native/native_test/salus_test.go +++ b/pkg/core/native/native_test/salus_test.go @@ -7,7 +7,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/crypto/hash" "github.com/stretchr/testify/require" "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" - "github.com/tutus-one/tutus-chain/pkg/neotest" + "github.com/tutus-one/tutus-chain/pkg/tutustest" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" ) diff --git a/pkg/core/native/native_test/scire_test.go b/pkg/core/native/native_test/scire_test.go index 08313a3..f40ba67 100644 --- a/pkg/core/native/native_test/scire_test.go +++ b/pkg/core/native/native_test/scire_test.go @@ -7,7 +7,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/crypto/hash" "github.com/stretchr/testify/require" "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" - "github.com/tutus-one/tutus-chain/pkg/neotest" + "github.com/tutus-one/tutus-chain/pkg/tutustest" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" ) diff --git a/pkg/core/native/native_test/sese_test.go b/pkg/core/native/native_test/sese_test.go index 432fc67..7ce24d3 100644 --- a/pkg/core/native/native_test/sese_test.go +++ b/pkg/core/native/native_test/sese_test.go @@ -7,7 +7,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/crypto/hash" "github.com/stretchr/testify/require" "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" - "github.com/tutus-one/tutus-chain/pkg/neotest" + "github.com/tutus-one/tutus-chain/pkg/tutustest" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" ) diff --git a/pkg/core/native/native_test/std_test.go b/pkg/core/native/native_test/std_test.go index fc0fdcd..1cdd98a 100644 --- a/pkg/core/native/native_test/std_test.go +++ b/pkg/core/native/native_test/std_test.go @@ -7,8 +7,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/compiler" "github.com/tutus-one/tutus-chain/pkg/config" "github.com/tutus-one/tutus-chain/pkg/core/native/nativehashes" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" ) diff --git a/pkg/core/native/native_test/treasury_test.go b/pkg/core/native/native_test/treasury_test.go index b1871ea..38f9ee8 100644 --- a/pkg/core/native/native_test/treasury_test.go +++ b/pkg/core/native/native_test/treasury_test.go @@ -7,8 +7,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/config" "github.com/tutus-one/tutus-chain/pkg/core/native/nativehashes" "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" ) func newTreasuryClient(t *testing.T) *neotest.ContractInvoker { diff --git a/pkg/core/native/native_test/tribute_test.go b/pkg/core/native/native_test/tribute_test.go index c5a08e2..b8639b7 100644 --- a/pkg/core/native/native_test/tribute_test.go +++ b/pkg/core/native/native_test/tribute_test.go @@ -7,7 +7,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/crypto/hash" "github.com/stretchr/testify/require" "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" - "github.com/tutus-one/tutus-chain/pkg/neotest" + "github.com/tutus-one/tutus-chain/pkg/tutustest" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" ) diff --git a/pkg/core/native/native_test/vita_test.go b/pkg/core/native/native_test/vita_test.go index d545a4c..c39426d 100644 --- a/pkg/core/native/native_test/vita_test.go +++ b/pkg/core/native/native_test/vita_test.go @@ -1,309 +1,309 @@ -package native_test - -import ( - "testing" - "time" - - "github.com/nspcc-dev/neo-go/pkg/crypto/hash" - "github.com/stretchr/testify/require" - "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" - "github.com/tutus-one/tutus-chain/pkg/core/state" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" -) - -func newVitaClient(t *testing.T) *neotest.ContractInvoker { - return newNativeClient(t, nativenames.Vita) -} - -// registerVita is a helper to register a Vita for a signer. -// Returns the tokenID bytes. -func registerVita(t *testing.T, c *neotest.ContractInvoker, signer neotest.Signer) []byte { - owner := signer.ScriptHash() - personHash := hash.Sha256(owner.BytesBE()).BytesBE() - isEntity := false - recoveryHash := hash.Sha256([]byte("recovery")).BytesBE() - birthTimestamp := time.Now().Unix() - 30*365*24*60*60 // Default: 30 years old - - invoker := c.WithSigners(signer) - // Register returns tokenID bytes, not null - txHash := invoker.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - // Result is a ByteArray (tokenID) - _, ok := stack[0].Value().([]byte) - require.True(t, ok, "expected ByteArray result") - }, "register", owner.BytesBE(), personHash, isEntity, recoveryHash, birthTimestamp) - - aer := c.Executor.GetTxExecResult(t, txHash) - require.Equal(t, 1, len(aer.Stack)) - tokenIDBytes := aer.Stack[0].Value().([]byte) - return tokenIDBytes -} - -// TestVita_Register tests basic registration functionality. -func TestVita_Register(t *testing.T) { - c := newVitaClient(t) - e := c.Executor - - acc := e.NewAccount(t) - owner := acc.ScriptHash() - personHash := hash.Sha256(owner.BytesBE()).BytesBE() - isEntity := false - recoveryHash := hash.Sha256([]byte("recovery")).BytesBE() - birthTimestamp := time.Now().Unix() - 30*365*24*60*60 // 30 years old - - invoker := c.WithSigners(acc) - - // Register token - returns tokenID bytes - txHash := invoker.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - _, ok := stack[0].Value().([]byte) - require.True(t, ok, "expected ByteArray result") - }, "register", owner.BytesBE(), personHash, isEntity, recoveryHash, birthTimestamp) - - // Check events were emitted (BirthRegistered from Annos + VitaCreated) - aer := e.GetTxExecResult(t, txHash) - require.Equal(t, 2, len(aer.Events)) - require.Equal(t, "BirthRegistered", aer.Events[0].Name) - require.Equal(t, "VitaCreated", aer.Events[1].Name) - - // Check exists returns true - invoker.Invoke(t, true, "exists", owner.BytesBE()) - - // Check getToken returns valid token - invoker.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - arr := stack[0].Value().([]stackitem.Item) - require.GreaterOrEqual(t, len(arr), 5) // At least tokenID, owner, personHash, isEntity, status - }, "getToken", owner.BytesBE()) -} - -// TestVita_ValidateCaller tests the validateCaller method. -// Note: validateCaller uses GetCallingScriptHash() which returns the calling contract's -// script hash, not the transaction signer's address. When called directly from a transaction -// (not from another contract), the caller has no token. These methods are designed for -// cross-contract authorization. -func TestVita_ValidateCaller(t *testing.T) { - c := newVitaClient(t) - - t.Run("no token - direct call", func(t *testing.T) { - acc := c.Executor.NewAccount(t) - invoker := c.WithSigners(acc) - - // validateCaller uses GetCallingScriptHash() which returns the transaction script hash - // when called directly, not the signer's account. This will always fail for direct calls. - invoker.InvokeFail(t, "caller does not have a Vita", "validateCaller") - }) - - // Note: Testing validateCaller with a token requires deploying a helper contract - // that has a Vita registered to its script hash, then calling validateCaller - // from within that contract. This is the intended usage pattern for cross-contract auth. -} - -// TestVita_RequireRole tests the requireRole method. -// Note: requireRole uses GetCallingScriptHash() - designed for cross-contract authorization. -func TestVita_RequireRole(t *testing.T) { - c := newVitaClient(t) - - t.Run("no token - direct call", func(t *testing.T) { - acc := c.Executor.NewAccount(t) - invoker := c.WithSigners(acc) - - // Direct calls always fail because GetCallingScriptHash() returns transaction script hash - invoker.InvokeFail(t, "caller does not have a Vita", "requireRole", 0) - }) - - // Note: Testing requireRole with actual role checks requires a deployed contract - // with a Vita registered to its script hash. -} - -// TestVita_RequireCoreRole tests the requireCoreRole method. -// Note: requireCoreRole uses GetCallingScriptHash() - designed for cross-contract authorization. -func TestVita_RequireCoreRole(t *testing.T) { - c := newVitaClient(t) - - // CoreRole constants - const ( - CoreRoleNone = 0 - CoreRoleRecovery = 5 - ) - - t.Run("invalid role", func(t *testing.T) { - acc := c.Executor.NewAccount(t) - invoker := c.WithSigners(acc) - - // requireCoreRole with invalid role (> 5) should fail before checking token - invoker.InvokeFail(t, "invalid core role", "requireCoreRole", 10) - }) - - t.Run("no token - direct call", func(t *testing.T) { - acc := c.Executor.NewAccount(t) - invoker := c.WithSigners(acc) - - // Direct calls always fail because GetCallingScriptHash() returns transaction script hash - invoker.InvokeFail(t, "caller does not have a Vita", "requireCoreRole", CoreRoleNone) - }) - - // Note: Testing requireCoreRole with actual role checks requires a deployed contract - // with a Vita registered to its script hash. -} - -// TestVita_RequirePermission tests the requirePermission method. -// Note: requirePermission uses GetCallingScriptHash() - designed for cross-contract authorization. -func TestVita_RequirePermission(t *testing.T) { - c := newVitaClient(t) - - t.Run("empty resource", func(t *testing.T) { - acc := c.Executor.NewAccount(t) - invoker := c.WithSigners(acc) - - // requirePermission with empty resource should fail before checking token - invoker.InvokeFail(t, "invalid resource", "requirePermission", "", "read", "global") - }) - - t.Run("empty action", func(t *testing.T) { - acc := c.Executor.NewAccount(t) - invoker := c.WithSigners(acc) - - // requirePermission with empty action should fail before checking token - invoker.InvokeFail(t, "invalid action", "requirePermission", "documents", "", "global") - }) - - t.Run("no token - direct call", func(t *testing.T) { - acc := c.Executor.NewAccount(t) - invoker := c.WithSigners(acc) - - // Direct calls always fail because GetCallingScriptHash() returns transaction script hash - invoker.InvokeFail(t, "caller does not have a Vita", "requirePermission", "documents", "read", "global") - }) - - // Note: Testing requirePermission with actual permission checks requires a deployed contract - // with a Vita registered to its script hash. -} - -// TestVita_TotalSupply tests the totalSupply method. -func TestVita_TotalSupply(t *testing.T) { - c := newVitaClient(t) - e := c.Executor - - // Initially, totalSupply should be 0 - c.Invoke(t, 0, "totalSupply") - - // Register a token - acc1 := e.NewAccount(t) - registerVita(t, c, acc1) - - // Now totalSupply should be 1 - c.Invoke(t, 1, "totalSupply") - - // Register another token - acc2 := e.NewAccount(t) - registerVita(t, c, acc2) - - // Now totalSupply should be 2 - c.Invoke(t, 2, "totalSupply") -} - -// TestVita_GetTokenByID tests the getTokenByID method. -func TestVita_GetTokenByID(t *testing.T) { - c := newVitaClient(t) - e := c.Executor - - // Register a token - the first token gets ID 0 (counter starts at 0) - acc := e.NewAccount(t) - registerVita(t, c, acc) - - // Token ID 0 should exist (first registered token) - c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - // Check that result is an array (not null) - arr, ok := stack[0].Value().([]stackitem.Item) - require.True(t, ok, "expected array result for existing token") - require.GreaterOrEqual(t, len(arr), 9) // Vita has 9 fields - - // Check owner matches (owner is at index 1) - owner, ok := arr[1].Value().([]byte) - require.True(t, ok, "expected owner to be bytes") - require.Equal(t, acc.ScriptHash().BytesBE(), owner) - }, "getTokenByID", 0) - - // Non-existent token should return null - c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - // Null returns nil from Value() - require.Nil(t, stack[0].Value(), "expected null for non-existent token") - }, "getTokenByID", 999999) -} - -// TestVita_SuspendReinstate tests suspend and reinstate functionality. -func TestVita_SuspendReinstate(t *testing.T) { - c := newVitaClient(t) - e := c.Executor - - acc := e.NewAccount(t) - registerVita(t, c, acc) - - invoker := c.WithSigners(acc) - committeeInvoker := c.WithSigners(c.Committee) - - // Create Lex invoker using same executor for liberty restriction (required for due process) - lexHash := e.NativeHash(t, nativenames.Lex) - lexCommitteeInvoker := e.CommitteeInvoker(lexHash) - - // Initially token is active - invoker.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - arr := stack[0].Value().([]stackitem.Item) - // Status is at index 6 (after tokenID, owner, personHash, isEntity, createdAt, updatedAt) - status, err := arr[6].TryInteger() - require.NoError(t, err) - require.Equal(t, int64(state.TokenStatusActive), status.Int64()) - }, "getToken", acc.ScriptHash().BytesBE()) - - // Non-committee cannot suspend - invoker.InvokeFail(t, "invalid committee signature", "suspend", acc.ScriptHash().BytesBE(), "test") - - // First, create a liberty restriction via Lex (due process requirement) - caseID := hash.Sha256([]byte("case-123")).BytesBE() // 32-byte case reference - lexCommitteeInvoker.Invoke(t, true, "restrictRight", - acc.ScriptHash().BytesBE(), // subject - int64(state.RightLiberty), // rightID = 2 (Liberty) - int64(state.RestrictionSuspend), // restrictionType = 1 (Suspend) - int64(100), // duration in blocks - "judicial order", // reason - caseID, // caseID (Hash256) - ) - - // Committee can suspend (now with valid Lex restriction order) - committeeInvoker.Invoke(t, true, "suspend", acc.ScriptHash().BytesBE(), "test suspension") - - // Token is now suspended - invoker.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - arr := stack[0].Value().([]stackitem.Item) - status, err := arr[6].TryInteger() - require.NoError(t, err) - require.Equal(t, int64(state.TokenStatusSuspended), status.Int64()) - }, "getToken", acc.ScriptHash().BytesBE()) - - // Non-committee cannot reinstate - invoker.InvokeFail(t, "invalid committee signature", "reinstate", acc.ScriptHash().BytesBE()) - - // Committee can reinstate - committeeInvoker.Invoke(t, true, "reinstate", acc.ScriptHash().BytesBE()) - - // Token is active again - invoker.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - arr := stack[0].Value().([]stackitem.Item) - status, err := arr[6].TryInteger() - require.NoError(t, err) - require.Equal(t, int64(state.TokenStatusActive), status.Int64()) - }, "getToken", acc.ScriptHash().BytesBE()) -} - -// Note: Full cross-contract testing of validateCaller, requireRole, requireCoreRole, and -// requirePermission would require deploying a helper contract that: -// 1. Has a Vita registered to its script hash -// 2. Calls the Vita cross-contract methods from within its own methods -// This is the intended usage pattern for these cross-contract authorization methods. +package native_test + +import ( + "testing" + "time" + + "github.com/nspcc-dev/neo-go/pkg/crypto/hash" + "github.com/stretchr/testify/require" + "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" + "github.com/tutus-one/tutus-chain/pkg/core/state" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" +) + +func newVitaClient(t *testing.T) *neotest.ContractInvoker { + return newNativeClient(t, nativenames.Vita) +} + +// registerVita is a helper to register a Vita for a signer. +// Returns the tokenID bytes. +func registerVita(t *testing.T, c *neotest.ContractInvoker, signer neotest.Signer) []byte { + owner := signer.ScriptHash() + personHash := hash.Sha256(owner.BytesBE()).BytesBE() + isEntity := false + recoveryHash := hash.Sha256([]byte("recovery")).BytesBE() + birthTimestamp := time.Now().Unix() - 30*365*24*60*60 // Default: 30 years old + + invoker := c.WithSigners(signer) + // Register returns tokenID bytes, not null + txHash := invoker.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + // Result is a ByteArray (tokenID) + _, ok := stack[0].Value().([]byte) + require.True(t, ok, "expected ByteArray result") + }, "register", owner.BytesBE(), personHash, isEntity, recoveryHash, birthTimestamp) + + aer := c.Executor.GetTxExecResult(t, txHash) + require.Equal(t, 1, len(aer.Stack)) + tokenIDBytes := aer.Stack[0].Value().([]byte) + return tokenIDBytes +} + +// TestVita_Register tests basic registration functionality. +func TestVita_Register(t *testing.T) { + c := newVitaClient(t) + e := c.Executor + + acc := e.NewAccount(t) + owner := acc.ScriptHash() + personHash := hash.Sha256(owner.BytesBE()).BytesBE() + isEntity := false + recoveryHash := hash.Sha256([]byte("recovery")).BytesBE() + birthTimestamp := time.Now().Unix() - 30*365*24*60*60 // 30 years old + + invoker := c.WithSigners(acc) + + // Register token - returns tokenID bytes + txHash := invoker.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + _, ok := stack[0].Value().([]byte) + require.True(t, ok, "expected ByteArray result") + }, "register", owner.BytesBE(), personHash, isEntity, recoveryHash, birthTimestamp) + + // Check events were emitted (BirthRegistered from Annos + VitaCreated) + aer := e.GetTxExecResult(t, txHash) + require.Equal(t, 2, len(aer.Events)) + require.Equal(t, "BirthRegistered", aer.Events[0].Name) + require.Equal(t, "VitaCreated", aer.Events[1].Name) + + // Check exists returns true + invoker.Invoke(t, true, "exists", owner.BytesBE()) + + // Check getToken returns valid token + invoker.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + arr := stack[0].Value().([]stackitem.Item) + require.GreaterOrEqual(t, len(arr), 5) // At least tokenID, owner, personHash, isEntity, status + }, "getToken", owner.BytesBE()) +} + +// TestVita_ValidateCaller tests the validateCaller method. +// Note: validateCaller uses GetCallingScriptHash() which returns the calling contract's +// script hash, not the transaction signer's address. When called directly from a transaction +// (not from another contract), the caller has no token. These methods are designed for +// cross-contract authorization. +func TestVita_ValidateCaller(t *testing.T) { + c := newVitaClient(t) + + t.Run("no token - direct call", func(t *testing.T) { + acc := c.Executor.NewAccount(t) + invoker := c.WithSigners(acc) + + // validateCaller uses GetCallingScriptHash() which returns the transaction script hash + // when called directly, not the signer's account. This will always fail for direct calls. + invoker.InvokeFail(t, "caller does not have a Vita", "validateCaller") + }) + + // Note: Testing validateCaller with a token requires deploying a helper contract + // that has a Vita registered to its script hash, then calling validateCaller + // from within that contract. This is the intended usage pattern for cross-contract auth. +} + +// TestVita_RequireRole tests the requireRole method. +// Note: requireRole uses GetCallingScriptHash() - designed for cross-contract authorization. +func TestVita_RequireRole(t *testing.T) { + c := newVitaClient(t) + + t.Run("no token - direct call", func(t *testing.T) { + acc := c.Executor.NewAccount(t) + invoker := c.WithSigners(acc) + + // Direct calls always fail because GetCallingScriptHash() returns transaction script hash + invoker.InvokeFail(t, "caller does not have a Vita", "requireRole", 0) + }) + + // Note: Testing requireRole with actual role checks requires a deployed contract + // with a Vita registered to its script hash. +} + +// TestVita_RequireCoreRole tests the requireCoreRole method. +// Note: requireCoreRole uses GetCallingScriptHash() - designed for cross-contract authorization. +func TestVita_RequireCoreRole(t *testing.T) { + c := newVitaClient(t) + + // CoreRole constants + const ( + CoreRoleNone = 0 + CoreRoleRecovery = 5 + ) + + t.Run("invalid role", func(t *testing.T) { + acc := c.Executor.NewAccount(t) + invoker := c.WithSigners(acc) + + // requireCoreRole with invalid role (> 5) should fail before checking token + invoker.InvokeFail(t, "invalid core role", "requireCoreRole", 10) + }) + + t.Run("no token - direct call", func(t *testing.T) { + acc := c.Executor.NewAccount(t) + invoker := c.WithSigners(acc) + + // Direct calls always fail because GetCallingScriptHash() returns transaction script hash + invoker.InvokeFail(t, "caller does not have a Vita", "requireCoreRole", CoreRoleNone) + }) + + // Note: Testing requireCoreRole with actual role checks requires a deployed contract + // with a Vita registered to its script hash. +} + +// TestVita_RequirePermission tests the requirePermission method. +// Note: requirePermission uses GetCallingScriptHash() - designed for cross-contract authorization. +func TestVita_RequirePermission(t *testing.T) { + c := newVitaClient(t) + + t.Run("empty resource", func(t *testing.T) { + acc := c.Executor.NewAccount(t) + invoker := c.WithSigners(acc) + + // requirePermission with empty resource should fail before checking token + invoker.InvokeFail(t, "invalid resource", "requirePermission", "", "read", "global") + }) + + t.Run("empty action", func(t *testing.T) { + acc := c.Executor.NewAccount(t) + invoker := c.WithSigners(acc) + + // requirePermission with empty action should fail before checking token + invoker.InvokeFail(t, "invalid action", "requirePermission", "documents", "", "global") + }) + + t.Run("no token - direct call", func(t *testing.T) { + acc := c.Executor.NewAccount(t) + invoker := c.WithSigners(acc) + + // Direct calls always fail because GetCallingScriptHash() returns transaction script hash + invoker.InvokeFail(t, "caller does not have a Vita", "requirePermission", "documents", "read", "global") + }) + + // Note: Testing requirePermission with actual permission checks requires a deployed contract + // with a Vita registered to its script hash. +} + +// TestVita_TotalSupply tests the totalSupply method. +func TestVita_TotalSupply(t *testing.T) { + c := newVitaClient(t) + e := c.Executor + + // Initially, totalSupply should be 0 + c.Invoke(t, 0, "totalSupply") + + // Register a token + acc1 := e.NewAccount(t) + registerVita(t, c, acc1) + + // Now totalSupply should be 1 + c.Invoke(t, 1, "totalSupply") + + // Register another token + acc2 := e.NewAccount(t) + registerVita(t, c, acc2) + + // Now totalSupply should be 2 + c.Invoke(t, 2, "totalSupply") +} + +// TestVita_GetTokenByID tests the getTokenByID method. +func TestVita_GetTokenByID(t *testing.T) { + c := newVitaClient(t) + e := c.Executor + + // Register a token - the first token gets ID 0 (counter starts at 0) + acc := e.NewAccount(t) + registerVita(t, c, acc) + + // Token ID 0 should exist (first registered token) + c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + // Check that result is an array (not null) + arr, ok := stack[0].Value().([]stackitem.Item) + require.True(t, ok, "expected array result for existing token") + require.GreaterOrEqual(t, len(arr), 9) // Vita has 9 fields + + // Check owner matches (owner is at index 1) + owner, ok := arr[1].Value().([]byte) + require.True(t, ok, "expected owner to be bytes") + require.Equal(t, acc.ScriptHash().BytesBE(), owner) + }, "getTokenByID", 0) + + // Non-existent token should return null + c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + // Null returns nil from Value() + require.Nil(t, stack[0].Value(), "expected null for non-existent token") + }, "getTokenByID", 999999) +} + +// TestVita_SuspendReinstate tests suspend and reinstate functionality. +func TestVita_SuspendReinstate(t *testing.T) { + c := newVitaClient(t) + e := c.Executor + + acc := e.NewAccount(t) + registerVita(t, c, acc) + + invoker := c.WithSigners(acc) + committeeInvoker := c.WithSigners(c.Committee) + + // Create Lex invoker using same executor for liberty restriction (required for due process) + lexHash := e.NativeHash(t, nativenames.Lex) + lexCommitteeInvoker := e.CommitteeInvoker(lexHash) + + // Initially token is active + invoker.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + arr := stack[0].Value().([]stackitem.Item) + // Status is at index 6 (after tokenID, owner, personHash, isEntity, createdAt, updatedAt) + status, err := arr[6].TryInteger() + require.NoError(t, err) + require.Equal(t, int64(state.TokenStatusActive), status.Int64()) + }, "getToken", acc.ScriptHash().BytesBE()) + + // Non-committee cannot suspend + invoker.InvokeFail(t, "invalid committee signature", "suspend", acc.ScriptHash().BytesBE(), "test") + + // First, create a liberty restriction via Lex (due process requirement) + caseID := hash.Sha256([]byte("case-123")).BytesBE() // 32-byte case reference + lexCommitteeInvoker.Invoke(t, true, "restrictRight", + acc.ScriptHash().BytesBE(), // subject + int64(state.RightLiberty), // rightID = 2 (Liberty) + int64(state.RestrictionSuspend), // restrictionType = 1 (Suspend) + int64(100), // duration in blocks + "judicial order", // reason + caseID, // caseID (Hash256) + ) + + // Committee can suspend (now with valid Lex restriction order) + committeeInvoker.Invoke(t, true, "suspend", acc.ScriptHash().BytesBE(), "test suspension") + + // Token is now suspended + invoker.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + arr := stack[0].Value().([]stackitem.Item) + status, err := arr[6].TryInteger() + require.NoError(t, err) + require.Equal(t, int64(state.TokenStatusSuspended), status.Int64()) + }, "getToken", acc.ScriptHash().BytesBE()) + + // Non-committee cannot reinstate + invoker.InvokeFail(t, "invalid committee signature", "reinstate", acc.ScriptHash().BytesBE()) + + // Committee can reinstate + committeeInvoker.Invoke(t, true, "reinstate", acc.ScriptHash().BytesBE()) + + // Token is active again + invoker.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + arr := stack[0].Value().([]stackitem.Item) + status, err := arr[6].TryInteger() + require.NoError(t, err) + require.Equal(t, int64(state.TokenStatusActive), status.Int64()) + }, "getToken", acc.ScriptHash().BytesBE()) +} + +// Note: Full cross-contract testing of validateCaller, requireRole, requireCoreRole, and +// requirePermission would require deploying a helper contract that: +// 1. Has a Vita registered to its script hash +// 2. Calls the Vita cross-contract methods from within its own methods +// This is the intended usage pattern for these cross-contract authorization methods. diff --git a/pkg/core/native/native_test/vts_test.go b/pkg/core/native/native_test/vts_test.go index a9c2a1f..3fbfd6c 100644 --- a/pkg/core/native/native_test/vts_test.go +++ b/pkg/core/native/native_test/vts_test.go @@ -1,671 +1,671 @@ -package native_test - -import ( - "testing" - "time" - - "github.com/nspcc-dev/neo-go/pkg/crypto/hash" - "github.com/stretchr/testify/require" - "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" - "github.com/tutus-one/tutus-chain/pkg/core/state" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" -) - -func newVTSClient(t *testing.T) *neotest.ContractInvoker { - return newNativeClient(t, nativenames.VTS) -} - -// registerVitaForVTS is a helper to register a Vita for an account. -// This is required for accounts receiving restricted VTS. -// Uses the existing executor to ensure we're on the same blockchain. -func registerVitaForVTS(t *testing.T, e *neotest.Executor, acc neotest.Signer) { - vitaHash := e.NativeHash(t, nativenames.Vita) - c := e.NewInvoker(vitaHash, acc) - owner := acc.ScriptHash() - personHash := hash.Sha256(owner.BytesBE()).BytesBE() - isEntity := false - recoveryHash := hash.Sha256([]byte("recovery")).BytesBE() - birthTimestamp := time.Now().Unix() - 30*365*24*60*60 // Default: 30 years old - - c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - _, ok := stack[0].Value().([]byte) - require.True(t, ok, "expected ByteArray result for tokenID") - }, "register", owner.BytesBE(), personHash, isEntity, recoveryHash, birthTimestamp) -} - -// addAgeVerifiedAttribute adds the "age_verified" attribute to an account's Vita. -// This is required for spending at age-restricted vendors. -// Uses the existing executor to ensure we're on the same blockchain. -func addAgeVerifiedAttribute(t *testing.T, e *neotest.Executor, committee neotest.Signer, acc neotest.Signer) { - vitaHash := e.NativeHash(t, nativenames.Vita) - c := e.CommitteeInvoker(vitaHash) - owner := acc.ScriptHash() - - // Get the token ID from getToken result - stack, err := c.TestInvoke(t, "getToken", owner.BytesBE()) - require.NoError(t, err) - tokenItem := stack.Pop().Item() - tokenArr := tokenItem.Value().([]stackitem.Item) - tokenIDBI, _ := tokenArr[0].TryInteger() - tokenID := tokenIDBI.Int64() - - // Create hash and encrypted value for the attribute - valueHash := hash.Sha256([]byte("true")).BytesBE() - valueEnc := []byte("true") // For testing, we just use plaintext - - // setAttribute: tokenId, key, valueHash, valueEnc, expiresAt, disclosureLevel - // disclosureLevel: 0 = private, 1 = selective, 2 = public - c.Invoke(t, true, "setAttribute", - tokenID, - "age_verified", - valueHash, - valueEnc, - int64(0), // expiresAt (0 = never expires) - int64(2), // disclosureLevel = public - ) -} - -// TestVTS_NEP17Compliance tests basic NEP-17 methods. -func TestVTS_NEP17Compliance(t *testing.T) { - c := newVTSClient(t) - - t.Run("symbol", func(t *testing.T) { - c.Invoke(t, "VTS", "symbol") - }) - - t.Run("decimals", func(t *testing.T) { - c.Invoke(t, 8, "decimals") - }) - - t.Run("totalSupply initial", func(t *testing.T) { - c.Invoke(t, 0, "totalSupply") - }) - - t.Run("balanceOf empty account", func(t *testing.T) { - acc := c.NewAccount(t) - c.Invoke(t, 0, "balanceOf", acc.ScriptHash()) - }) -} - -// TestVTS_Mint tests minting unrestricted VTS. -func TestVTS_Mint(t *testing.T) { - c := newVTSClient(t) - e := c.Executor - - acc := e.NewAccount(t) - committeeInvoker := c.WithSigners(c.Committee) - userInvoker := c.WithSigners(acc) - - t.Run("non-committee cannot mint", func(t *testing.T) { - userInvoker.InvokeFail(t, "caller is not a committee member", "mint", acc.ScriptHash(), 1000_00000000) - }) - - t.Run("committee can mint", func(t *testing.T) { - committeeInvoker.Invoke(t, true, "mint", acc.ScriptHash(), 1000_00000000) - }) - - t.Run("balance updated", func(t *testing.T) { - c.Invoke(t, 1000_00000000, "balanceOf", acc.ScriptHash()) - }) - - t.Run("unrestricted balance updated", func(t *testing.T) { - c.Invoke(t, 1000_00000000, "unrestrictedBalanceOf", acc.ScriptHash()) - }) - - t.Run("totalSupply updated", func(t *testing.T) { - c.Invoke(t, 1000_00000000, "totalSupply") - }) -} - -// TestVTS_MintRestricted tests minting restricted VTS. -func TestVTS_MintRestricted(t *testing.T) { - c := newVTSClient(t) - e := c.Executor - - acc := e.NewAccount(t) - committeeInvoker := c.WithSigners(c.Committee) - - // Restricted VTS requires recipient to have a Vita - registerVitaForVTS(t, e, acc) - - t.Run("mint food-restricted VTS", func(t *testing.T) { - committeeInvoker.Invoke(t, true, "mintRestricted", acc.ScriptHash(), 500_00000000, state.CategoryFood) - }) - - t.Run("total balance includes restricted", func(t *testing.T) { - c.Invoke(t, 500_00000000, "balanceOf", acc.ScriptHash()) - }) - - t.Run("unrestricted is still zero", func(t *testing.T) { - c.Invoke(t, 0, "unrestrictedBalanceOf", acc.ScriptHash()) - }) - - t.Run("restricted balance correct", func(t *testing.T) { - c.Invoke(t, 500_00000000, "restrictedBalanceOf", acc.ScriptHash(), state.CategoryFood) - }) - - t.Run("other restricted category is zero", func(t *testing.T) { - c.Invoke(t, 0, "restrictedBalanceOf", acc.ScriptHash(), state.CategoryShelter) - }) -} - -// TestVTS_Burn tests burning unrestricted VTS. -func TestVTS_Burn(t *testing.T) { - c := newVTSClient(t) - e := c.Executor - - acc := e.NewAccount(t) - committeeInvoker := c.WithSigners(c.Committee) - userInvoker := c.WithSigners(acc) - - // Mint first - committeeInvoker.Invoke(t, true, "mint", acc.ScriptHash(), 1000_00000000) - - t.Run("non-committee cannot burn", func(t *testing.T) { - userInvoker.InvokeFail(t, "caller is not a committee member", "burn", acc.ScriptHash(), 100_00000000) - }) - - t.Run("committee can burn", func(t *testing.T) { - committeeInvoker.Invoke(t, true, "burn", acc.ScriptHash(), 100_00000000) - }) - - t.Run("balance reduced", func(t *testing.T) { - c.Invoke(t, 900_00000000, "balanceOf", acc.ScriptHash()) - }) - - t.Run("totalSupply reduced", func(t *testing.T) { - c.Invoke(t, 900_00000000, "totalSupply") - }) -} - -// TestVTS_Transfer tests transferring unrestricted VTS. -func TestVTS_Transfer(t *testing.T) { - c := newVTSClient(t) - e := c.Executor - - sender := e.NewAccount(t) - receiver := e.NewAccount(t) - committeeInvoker := c.WithSigners(c.Committee) - senderInvoker := c.WithSigners(sender) - - // Setup: Register Vita for sender (required for property rights/transfers) - registerVitaForVTS(t, e, sender) - - // Mint to sender - committeeInvoker.Invoke(t, true, "mint", sender.ScriptHash(), 1000_00000000) - - t.Run("transfer without signature fails", func(t *testing.T) { - // Transfer returns false (not panic) when signature is missing - c.Invoke(t, false, "transfer", sender.ScriptHash(), receiver.ScriptHash(), 100_00000000, nil) - }) - - t.Run("transfer with signature succeeds", func(t *testing.T) { - senderInvoker.Invoke(t, true, "transfer", sender.ScriptHash(), receiver.ScriptHash(), 100_00000000, nil) - }) - - t.Run("sender balance reduced", func(t *testing.T) { - c.Invoke(t, 900_00000000, "balanceOf", sender.ScriptHash()) - }) - - t.Run("receiver balance increased", func(t *testing.T) { - c.Invoke(t, 100_00000000, "balanceOf", receiver.ScriptHash()) - }) - - t.Run("cannot transfer more than balance", func(t *testing.T) { - senderInvoker.Invoke(t, false, "transfer", sender.ScriptHash(), receiver.ScriptHash(), 10000_00000000, nil) - }) - - t.Run("cannot transfer negative", func(t *testing.T) { - // Transfer returns false (not panic) for negative amounts - senderInvoker.Invoke(t, false, "transfer", sender.ScriptHash(), receiver.ScriptHash(), -1, nil) - }) -} - -// TestVTS_VendorRegistration tests vendor management. -func TestVTS_VendorRegistration(t *testing.T) { - c := newVTSClient(t) - e := c.Executor - - vendorAcc := e.NewAccount(t) - userAcc := e.NewAccount(t) - committeeInvoker := c.WithSigners(c.Committee) - userInvoker := c.WithSigners(userAcc) - - t.Run("non-committee cannot register vendor", func(t *testing.T) { - userInvoker.InvokeFail(t, "caller is not a committee member", "registerVendor", vendorAcc.ScriptHash(), "Test Store", state.CategoryFood, false) - }) - - t.Run("committee can register vendor", func(t *testing.T) { - committeeInvoker.Invoke(t, true, "registerVendor", vendorAcc.ScriptHash(), "Test Store", state.CategoryFood, false) - }) - - t.Run("isVendor returns true", func(t *testing.T) { - c.Invoke(t, true, "isVendor", vendorAcc.ScriptHash()) - }) - - t.Run("non-vendor returns false", func(t *testing.T) { - c.Invoke(t, false, "isVendor", userAcc.ScriptHash()) - }) - - t.Run("getVendorCategories", func(t *testing.T) { - c.Invoke(t, int64(state.CategoryFood), "getVendorCategories", vendorAcc.ScriptHash()) - }) - - t.Run("getVendor returns vendor info", func(t *testing.T) { - c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - arr, ok := stack[0].Value().([]stackitem.Item) - require.True(t, ok, "expected array") - require.Equal(t, 7, len(arr)) // Vendor struct has 7 fields (including AgeRestricted) - }, "getVendor", vendorAcc.ScriptHash()) - }) - - t.Run("update vendor categories", func(t *testing.T) { - newCategories := state.CategoryFood | state.CategoryShelter - committeeInvoker.Invoke(t, true, "updateVendor", vendorAcc.ScriptHash(), "Test Store Updated", newCategories, false) - c.Invoke(t, int64(newCategories), "getVendorCategories", vendorAcc.ScriptHash()) - }) - - t.Run("deactivate vendor", func(t *testing.T) { - committeeInvoker.Invoke(t, true, "deactivateVendor", vendorAcc.ScriptHash()) - // isVendor should still return true (vendor exists) but Active=false - c.Invoke(t, false, "isVendor", vendorAcc.ScriptHash()) - }) -} - -// TestVTS_Spend tests spending at vendors. -func TestVTS_Spend(t *testing.T) { - c := newVTSClient(t) - e := c.Executor - - customer := e.NewAccount(t) - foodVendor := e.NewAccount(t) - committeeInvoker := c.WithSigners(c.Committee) - customerInvoker := c.WithSigners(customer) - - // Setup: Register Vita for customer (required for property rights/spending) - registerVitaForVTS(t, e, customer) - - // Setup: Register food vendor and mint to customer - committeeInvoker.Invoke(t, true, "registerVendor", foodVendor.ScriptHash(), "Food Store", state.CategoryFood, false) - committeeInvoker.Invoke(t, true, "mint", customer.ScriptHash(), 300_00000000) - - t.Run("customer can spend at vendor", func(t *testing.T) { - customerInvoker.Invoke(t, true, "spend", customer.ScriptHash(), foodVendor.ScriptHash(), 50_00000000, nil) - }) - - t.Run("vendor received VTS", func(t *testing.T) { - c.Invoke(t, 50_00000000, "balanceOf", foodVendor.ScriptHash()) - }) - - t.Run("customer balance reduced", func(t *testing.T) { - c.Invoke(t, 250_00000000, "balanceOf", customer.ScriptHash()) - }) - - t.Run("cannot spend at non-vendor", func(t *testing.T) { - nonVendor := e.NewAccount(t) - customerInvoker.InvokeFail(t, "invalid or inactive vendor", "spend", customer.ScriptHash(), nonVendor.ScriptHash(), 10_00000000, nil) - }) -} - -// TestVTS_CanSpendAt tests the canSpendAt query method. -func TestVTS_CanSpendAt(t *testing.T) { - c := newVTSClient(t) - e := c.Executor - - customer := e.NewAccount(t) - vendor := e.NewAccount(t) - committeeInvoker := c.WithSigners(c.Committee) - - // Setup: Register Vita for customer (required for property rights) - registerVitaForVTS(t, e, customer) - - // Setup - committeeInvoker.Invoke(t, true, "registerVendor", vendor.ScriptHash(), "Store", state.CategoryFood, false) - committeeInvoker.Invoke(t, true, "mint", customer.ScriptHash(), 100_00000000) - - t.Run("can spend within balance", func(t *testing.T) { - c.Invoke(t, true, "canSpendAt", customer.ScriptHash(), vendor.ScriptHash(), 50_00000000) - }) - - t.Run("cannot spend more than balance", func(t *testing.T) { - c.Invoke(t, false, "canSpendAt", customer.ScriptHash(), vendor.ScriptHash(), 200_00000000) - }) -} - -// TestVTS_ConvertToUnrestricted tests converting restricted VTS to unrestricted. -func TestVTS_ConvertToUnrestricted(t *testing.T) { - c := newVTSClient(t) - e := c.Executor - - acc := e.NewAccount(t) - committeeInvoker := c.WithSigners(c.Committee) - userInvoker := c.WithSigners(acc) - - // Restricted VTS requires Vita - registerVitaForVTS(t, e, acc) - - // Mint restricted VTS - committeeInvoker.Invoke(t, true, "mintRestricted", acc.ScriptHash(), 500_00000000, state.CategoryFood) - - t.Run("non-committee cannot convert", func(t *testing.T) { - userInvoker.InvokeFail(t, "caller is not a committee member", "convertToUnrestricted", acc.ScriptHash(), state.CategoryFood, 100_00000000) - }) - - t.Run("committee can convert", func(t *testing.T) { - committeeInvoker.Invoke(t, true, "convertToUnrestricted", acc.ScriptHash(), state.CategoryFood, 100_00000000) - }) - - t.Run("restricted balance reduced", func(t *testing.T) { - c.Invoke(t, 400_00000000, "restrictedBalanceOf", acc.ScriptHash(), state.CategoryFood) - }) - - t.Run("unrestricted balance increased", func(t *testing.T) { - c.Invoke(t, 100_00000000, "unrestrictedBalanceOf", acc.ScriptHash()) - }) - - t.Run("total balance unchanged", func(t *testing.T) { - c.Invoke(t, 500_00000000, "balanceOf", acc.ScriptHash()) - }) -} - -// TestVTS_TaxConfig tests tax configuration. -func TestVTS_TaxConfig(t *testing.T) { - c := newVTSClient(t) - e := c.Executor - - treasuryAcc := e.NewAccount(t) - userAcc := e.NewAccount(t) - committeeInvoker := c.WithSigners(c.Committee) - userInvoker := c.WithSigners(userAcc) - - t.Run("non-committee cannot set tax config", func(t *testing.T) { - userInvoker.InvokeFail(t, "caller is not a committee member", "setTaxConfig", 2500, 500, treasuryAcc.ScriptHash(), state.CategoryFood) - }) - - t.Run("committee can set tax config", func(t *testing.T) { - // 25% income tax, 5% sales tax - committeeInvoker.Invoke(t, true, "setTaxConfig", 2500, 500, treasuryAcc.ScriptHash(), state.CategoryFood) - }) - - t.Run("get tax config", func(t *testing.T) { - c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - arr, ok := stack[0].Value().([]stackitem.Item) - require.True(t, ok, "expected array") - require.Equal(t, 4, len(arr)) // TaxConfig has 4 fields - - incomeRate, _ := arr[0].TryInteger() - require.Equal(t, int64(2500), incomeRate.Int64()) - }, "getTaxConfig") - }) -} - -// TestVTS_PayWage tests payroll with automatic tax withholding. -func TestVTS_PayWage(t *testing.T) { - c := newVTSClient(t) - e := c.Executor - - employer := e.NewAccount(t) - employee := e.NewAccount(t) - treasury := e.NewAccount(t) - committeeInvoker := c.WithSigners(c.Committee) - employerInvoker := c.WithSigners(employer) - - // Setup: Register Vita for employer (required for property rights/transfers) - registerVitaForVTS(t, e, employer) - - // Setup: Set tax config and fund employer - committeeInvoker.Invoke(t, true, "setTaxConfig", 2500, 0, treasury.ScriptHash(), 0) // 25% income tax - committeeInvoker.Invoke(t, true, "mint", employer.ScriptHash(), 10000_00000000) - - t.Run("payWage with tax withholding", func(t *testing.T) { - // Pay $5000 gross, 25% tax rate - employerInvoker.Invoke(t, true, "payWage", employer.ScriptHash(), employee.ScriptHash(), 5000_00000000, 2500) - }) - - t.Run("employer balance reduced by gross", func(t *testing.T) { - c.Invoke(t, 5000_00000000, "balanceOf", employer.ScriptHash()) - }) - - t.Run("employee receives net (75%)", func(t *testing.T) { - c.Invoke(t, 3750_00000000, "balanceOf", employee.ScriptHash()) - }) - - t.Run("treasury receives tax (25%)", func(t *testing.T) { - c.Invoke(t, 1250_00000000, "balanceOf", treasury.ScriptHash()) - }) -} - -// TestVTS_TaxRefund tests issuing tax refunds. -func TestVTS_TaxRefund(t *testing.T) { - c := newVTSClient(t) - e := c.Executor - - acc := e.NewAccount(t) - treasury := e.NewAccount(t) - committeeInvoker := c.WithSigners(c.Committee) - userInvoker := c.WithSigners(acc) - - // Setup: Set tax config - committeeInvoker.Invoke(t, true, "setTaxConfig", 2500, 0, treasury.ScriptHash(), 0) - - t.Run("non-committee cannot issue refund", func(t *testing.T) { - userInvoker.InvokeFail(t, "caller is not a committee member", "issueTaxRefund", acc.ScriptHash(), 100_00000000) - }) - - t.Run("committee can issue refund", func(t *testing.T) { - committeeInvoker.Invoke(t, true, "issueTaxRefund", acc.ScriptHash(), 100_00000000) - }) - - t.Run("refund credited to account", func(t *testing.T) { - c.Invoke(t, 100_00000000, "balanceOf", acc.ScriptHash()) - }) -} - -// TestVTS_BalanceDetails tests the balanceDetails query. -func TestVTS_BalanceDetails(t *testing.T) { - c := newVTSClient(t) - e := c.Executor - - acc := e.NewAccount(t) - committeeInvoker := c.WithSigners(c.Committee) - - // Restricted VTS requires Vita - registerVitaForVTS(t, e, acc) - - // Mint mixed VTS - committeeInvoker.Invoke(t, true, "mint", acc.ScriptHash(), 100_00000000) - committeeInvoker.Invoke(t, true, "mintRestricted", acc.ScriptHash(), 200_00000000, state.CategoryFood) - committeeInvoker.Invoke(t, true, "mintRestricted", acc.ScriptHash(), 300_00000000, state.CategoryShelter) - - t.Run("balanceDetails returns all categories", func(t *testing.T) { - c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - arr, ok := stack[0].Value().([]stackitem.Item) - require.True(t, ok, "expected array") - // Should have unrestricted + categories with balances - require.GreaterOrEqual(t, len(arr), 1) - }, "balanceDetails", acc.ScriptHash()) - }) -} - -// TestVTS_TaxReportingMethods tests the tax reporting query methods. -func TestVTS_TaxReportingMethods(t *testing.T) { - c := newVTSClient(t) - e := c.Executor - - acc := e.NewAccount(t) - - // Block range for queries - startBlock := int64(0) - endBlock := int64(1000) - - t.Run("getTransactions returns array", func(t *testing.T) { - c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - _, ok := stack[0].Value().([]stackitem.Item) - require.True(t, ok, "expected array") - }, "getTransactions", acc.ScriptHash(), startBlock, endBlock) - }) - - t.Run("getIncomeForPeriod returns integer", func(t *testing.T) { - c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - _, err := stack[0].TryInteger() - require.NoError(t, err) - }, "getIncomeForPeriod", acc.ScriptHash(), startBlock, endBlock) - }) - - t.Run("getTaxWithheld returns integer", func(t *testing.T) { - c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - _, err := stack[0].TryInteger() - require.NoError(t, err) - }, "getTaxWithheld", acc.ScriptHash(), startBlock, endBlock) - }) - - t.Run("getDeductibleExpenses returns integer", func(t *testing.T) { - c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - _, err := stack[0].TryInteger() - require.NoError(t, err) - }, "getDeductibleExpenses", acc.ScriptHash(), startBlock, endBlock, 0) - }) - - t.Run("getTaxSummary returns array", func(t *testing.T) { - c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { - require.Equal(t, 1, len(stack)) - arr, ok := stack[0].Value().([]stackitem.Item) - require.True(t, ok, "expected array for tax summary") - // TaxSummary has 10 fields: Account, StartBlock, EndBlock, TotalIncome, - // TotalBenefits, TotalExpenses, DeductibleExpenses, TaxWithheld, EstimatedOwed, Balance - require.Equal(t, 10, len(arr)) - }, "getTaxSummary", acc.ScriptHash(), startBlock, endBlock) - }) -} - -// TestVTS_NegativeAmount tests that negative amounts are rejected. -func TestVTS_NegativeAmount(t *testing.T) { - c := newVTSClient(t) - e := c.Executor - - acc := e.NewAccount(t) - committeeInvoker := c.WithSigners(c.Committee) - - // Restricted VTS requires Vita - registerVitaForVTS(t, e, acc) - - t.Run("mint negative fails", func(t *testing.T) { - committeeInvoker.InvokeFail(t, "amount must be positive", "mint", acc.ScriptHash(), -1) - }) - - t.Run("mintRestricted negative fails", func(t *testing.T) { - committeeInvoker.InvokeFail(t, "amount must be positive", "mintRestricted", acc.ScriptHash(), -1, state.CategoryFood) - }) -} - -// TestVTS_MultiCategoryVendor tests vendors accepting multiple categories. -func TestVTS_MultiCategoryVendor(t *testing.T) { - c := newVTSClient(t) - e := c.Executor - - customer := e.NewAccount(t) - generalStore := e.NewAccount(t) - committeeInvoker := c.WithSigners(c.Committee) - customerInvoker := c.WithSigners(customer) - - // Restricted VTS requires Vita - registerVitaForVTS(t, e, customer) - - // Register vendor accepting food AND shelter - categories := state.CategoryFood | state.CategoryShelter - committeeInvoker.Invoke(t, true, "registerVendor", generalStore.ScriptHash(), "General Store", categories, false) - - // Mint restricted VTS for different categories - committeeInvoker.Invoke(t, true, "mintRestricted", customer.ScriptHash(), 100_00000000, state.CategoryFood) - committeeInvoker.Invoke(t, true, "mintRestricted", customer.ScriptHash(), 100_00000000, state.CategoryShelter) - - t.Run("can spend at multi-category vendor", func(t *testing.T) { - customerInvoker.Invoke(t, true, "spend", customer.ScriptHash(), generalStore.ScriptHash(), 50_00000000, nil) - // Total balance should be reduced by 50 - c.Invoke(t, 150_00000000, "balanceOf", customer.ScriptHash()) - }) - - t.Run("can spend more at same vendor", func(t *testing.T) { - customerInvoker.Invoke(t, true, "spend", customer.ScriptHash(), generalStore.ScriptHash(), 50_00000000, nil) - customerInvoker.Invoke(t, true, "spend", customer.ScriptHash(), generalStore.ScriptHash(), 50_00000000, nil) - // Total balance should be reduced by 150 - c.Invoke(t, 50_00000000, "balanceOf", customer.ScriptHash()) - }) - - t.Run("vendor has correct total", func(t *testing.T) { - c.Invoke(t, 150_00000000, "balanceOf", generalStore.ScriptHash()) - }) -} - -// TestVTS_AgeRestrictedVendor tests age verification for age-restricted vendors. -func TestVTS_AgeRestrictedVendor(t *testing.T) { - c := newVTSClient(t) - e := c.Executor - - adultCustomer := e.NewAccount(t) - minorCustomer := e.NewAccount(t) - liquorStore := e.NewAccount(t) - committeeInvoker := c.WithSigners(c.Committee) - adultInvoker := c.WithSigners(adultCustomer) - minorInvoker := c.WithSigners(minorCustomer) - - // Register Vita for both customers - registerVitaForVTS(t, e, adultCustomer) - registerVitaForVTS(t, e, minorCustomer) - - // Only adult has age_verified attribute - addAgeVerifiedAttribute(t, e, c.Committee, adultCustomer) - - // Register age-restricted vendor (liquor store) - committeeInvoker.Invoke(t, true, "registerVendor", liquorStore.ScriptHash(), "Liquor Store", state.CategoryFood, true) - - // Mint VTS to both customers - committeeInvoker.Invoke(t, true, "mint", adultCustomer.ScriptHash(), 100_00000000) - committeeInvoker.Invoke(t, true, "mint", minorCustomer.ScriptHash(), 100_00000000) - - t.Run("minor cannot spend at age-restricted vendor", func(t *testing.T) { - minorInvoker.InvokeFail(t, "age verification required for this vendor", "spend", minorCustomer.ScriptHash(), liquorStore.ScriptHash(), 10_00000000, nil) - }) - - t.Run("adult can spend at age-restricted vendor", func(t *testing.T) { - adultInvoker.Invoke(t, true, "spend", adultCustomer.ScriptHash(), liquorStore.ScriptHash(), 10_00000000, nil) - }) - - t.Run("canSpendAt returns false for minor at age-restricted vendor", func(t *testing.T) { - c.Invoke(t, false, "canSpendAt", minorCustomer.ScriptHash(), liquorStore.ScriptHash(), 10_00000000) - }) - - t.Run("canSpendAt returns true for adult at age-restricted vendor", func(t *testing.T) { - c.Invoke(t, true, "canSpendAt", adultCustomer.ScriptHash(), liquorStore.ScriptHash(), 10_00000000) - }) -} - -// TestVTS_MintRestrictedRequiresVita tests that minting restricted VTS requires a Vita. -func TestVTS_MintRestrictedRequiresVita(t *testing.T) { - c := newVTSClient(t) - e := c.Executor - - accWithVita := e.NewAccount(t) - accWithoutVita := e.NewAccount(t) - committeeInvoker := c.WithSigners(c.Committee) - - // Only register Vita for one account - registerVitaForVTS(t, e, accWithVita) - - t.Run("cannot mint restricted VTS to account without Vita", func(t *testing.T) { - committeeInvoker.InvokeFail(t, "restricted VTS requires Vita", "mintRestricted", accWithoutVita.ScriptHash(), 100_00000000, state.CategoryFood) - }) - - t.Run("can mint restricted VTS to account with Vita", func(t *testing.T) { - committeeInvoker.Invoke(t, true, "mintRestricted", accWithVita.ScriptHash(), 100_00000000, state.CategoryFood) - }) -} +package native_test + +import ( + "testing" + "time" + + "github.com/nspcc-dev/neo-go/pkg/crypto/hash" + "github.com/stretchr/testify/require" + "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" + "github.com/tutus-one/tutus-chain/pkg/core/state" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" +) + +func newVTSClient(t *testing.T) *neotest.ContractInvoker { + return newNativeClient(t, nativenames.VTS) +} + +// registerVitaForVTS is a helper to register a Vita for an account. +// This is required for accounts receiving restricted VTS. +// Uses the existing executor to ensure we're on the same blockchain. +func registerVitaForVTS(t *testing.T, e *neotest.Executor, acc neotest.Signer) { + vitaHash := e.NativeHash(t, nativenames.Vita) + c := e.NewInvoker(vitaHash, acc) + owner := acc.ScriptHash() + personHash := hash.Sha256(owner.BytesBE()).BytesBE() + isEntity := false + recoveryHash := hash.Sha256([]byte("recovery")).BytesBE() + birthTimestamp := time.Now().Unix() - 30*365*24*60*60 // Default: 30 years old + + c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + _, ok := stack[0].Value().([]byte) + require.True(t, ok, "expected ByteArray result for tokenID") + }, "register", owner.BytesBE(), personHash, isEntity, recoveryHash, birthTimestamp) +} + +// addAgeVerifiedAttribute adds the "age_verified" attribute to an account's Vita. +// This is required for spending at age-restricted vendors. +// Uses the existing executor to ensure we're on the same blockchain. +func addAgeVerifiedAttribute(t *testing.T, e *neotest.Executor, committee neotest.Signer, acc neotest.Signer) { + vitaHash := e.NativeHash(t, nativenames.Vita) + c := e.CommitteeInvoker(vitaHash) + owner := acc.ScriptHash() + + // Get the token ID from getToken result + stack, err := c.TestInvoke(t, "getToken", owner.BytesBE()) + require.NoError(t, err) + tokenItem := stack.Pop().Item() + tokenArr := tokenItem.Value().([]stackitem.Item) + tokenIDBI, _ := tokenArr[0].TryInteger() + tokenID := tokenIDBI.Int64() + + // Create hash and encrypted value for the attribute + valueHash := hash.Sha256([]byte("true")).BytesBE() + valueEnc := []byte("true") // For testing, we just use plaintext + + // setAttribute: tokenId, key, valueHash, valueEnc, expiresAt, disclosureLevel + // disclosureLevel: 0 = private, 1 = selective, 2 = public + c.Invoke(t, true, "setAttribute", + tokenID, + "age_verified", + valueHash, + valueEnc, + int64(0), // expiresAt (0 = never expires) + int64(2), // disclosureLevel = public + ) +} + +// TestVTS_NEP17Compliance tests basic NEP-17 methods. +func TestVTS_NEP17Compliance(t *testing.T) { + c := newVTSClient(t) + + t.Run("symbol", func(t *testing.T) { + c.Invoke(t, "VTS", "symbol") + }) + + t.Run("decimals", func(t *testing.T) { + c.Invoke(t, 8, "decimals") + }) + + t.Run("totalSupply initial", func(t *testing.T) { + c.Invoke(t, 0, "totalSupply") + }) + + t.Run("balanceOf empty account", func(t *testing.T) { + acc := c.NewAccount(t) + c.Invoke(t, 0, "balanceOf", acc.ScriptHash()) + }) +} + +// TestVTS_Mint tests minting unrestricted VTS. +func TestVTS_Mint(t *testing.T) { + c := newVTSClient(t) + e := c.Executor + + acc := e.NewAccount(t) + committeeInvoker := c.WithSigners(c.Committee) + userInvoker := c.WithSigners(acc) + + t.Run("non-committee cannot mint", func(t *testing.T) { + userInvoker.InvokeFail(t, "caller is not a committee member", "mint", acc.ScriptHash(), 1000_00000000) + }) + + t.Run("committee can mint", func(t *testing.T) { + committeeInvoker.Invoke(t, true, "mint", acc.ScriptHash(), 1000_00000000) + }) + + t.Run("balance updated", func(t *testing.T) { + c.Invoke(t, 1000_00000000, "balanceOf", acc.ScriptHash()) + }) + + t.Run("unrestricted balance updated", func(t *testing.T) { + c.Invoke(t, 1000_00000000, "unrestrictedBalanceOf", acc.ScriptHash()) + }) + + t.Run("totalSupply updated", func(t *testing.T) { + c.Invoke(t, 1000_00000000, "totalSupply") + }) +} + +// TestVTS_MintRestricted tests minting restricted VTS. +func TestVTS_MintRestricted(t *testing.T) { + c := newVTSClient(t) + e := c.Executor + + acc := e.NewAccount(t) + committeeInvoker := c.WithSigners(c.Committee) + + // Restricted VTS requires recipient to have a Vita + registerVitaForVTS(t, e, acc) + + t.Run("mint food-restricted VTS", func(t *testing.T) { + committeeInvoker.Invoke(t, true, "mintRestricted", acc.ScriptHash(), 500_00000000, state.CategoryFood) + }) + + t.Run("total balance includes restricted", func(t *testing.T) { + c.Invoke(t, 500_00000000, "balanceOf", acc.ScriptHash()) + }) + + t.Run("unrestricted is still zero", func(t *testing.T) { + c.Invoke(t, 0, "unrestrictedBalanceOf", acc.ScriptHash()) + }) + + t.Run("restricted balance correct", func(t *testing.T) { + c.Invoke(t, 500_00000000, "restrictedBalanceOf", acc.ScriptHash(), state.CategoryFood) + }) + + t.Run("other restricted category is zero", func(t *testing.T) { + c.Invoke(t, 0, "restrictedBalanceOf", acc.ScriptHash(), state.CategoryShelter) + }) +} + +// TestVTS_Burn tests burning unrestricted VTS. +func TestVTS_Burn(t *testing.T) { + c := newVTSClient(t) + e := c.Executor + + acc := e.NewAccount(t) + committeeInvoker := c.WithSigners(c.Committee) + userInvoker := c.WithSigners(acc) + + // Mint first + committeeInvoker.Invoke(t, true, "mint", acc.ScriptHash(), 1000_00000000) + + t.Run("non-committee cannot burn", func(t *testing.T) { + userInvoker.InvokeFail(t, "caller is not a committee member", "burn", acc.ScriptHash(), 100_00000000) + }) + + t.Run("committee can burn", func(t *testing.T) { + committeeInvoker.Invoke(t, true, "burn", acc.ScriptHash(), 100_00000000) + }) + + t.Run("balance reduced", func(t *testing.T) { + c.Invoke(t, 900_00000000, "balanceOf", acc.ScriptHash()) + }) + + t.Run("totalSupply reduced", func(t *testing.T) { + c.Invoke(t, 900_00000000, "totalSupply") + }) +} + +// TestVTS_Transfer tests transferring unrestricted VTS. +func TestVTS_Transfer(t *testing.T) { + c := newVTSClient(t) + e := c.Executor + + sender := e.NewAccount(t) + receiver := e.NewAccount(t) + committeeInvoker := c.WithSigners(c.Committee) + senderInvoker := c.WithSigners(sender) + + // Setup: Register Vita for sender (required for property rights/transfers) + registerVitaForVTS(t, e, sender) + + // Mint to sender + committeeInvoker.Invoke(t, true, "mint", sender.ScriptHash(), 1000_00000000) + + t.Run("transfer without signature fails", func(t *testing.T) { + // Transfer returns false (not panic) when signature is missing + c.Invoke(t, false, "transfer", sender.ScriptHash(), receiver.ScriptHash(), 100_00000000, nil) + }) + + t.Run("transfer with signature succeeds", func(t *testing.T) { + senderInvoker.Invoke(t, true, "transfer", sender.ScriptHash(), receiver.ScriptHash(), 100_00000000, nil) + }) + + t.Run("sender balance reduced", func(t *testing.T) { + c.Invoke(t, 900_00000000, "balanceOf", sender.ScriptHash()) + }) + + t.Run("receiver balance increased", func(t *testing.T) { + c.Invoke(t, 100_00000000, "balanceOf", receiver.ScriptHash()) + }) + + t.Run("cannot transfer more than balance", func(t *testing.T) { + senderInvoker.Invoke(t, false, "transfer", sender.ScriptHash(), receiver.ScriptHash(), 10000_00000000, nil) + }) + + t.Run("cannot transfer negative", func(t *testing.T) { + // Transfer returns false (not panic) for negative amounts + senderInvoker.Invoke(t, false, "transfer", sender.ScriptHash(), receiver.ScriptHash(), -1, nil) + }) +} + +// TestVTS_VendorRegistration tests vendor management. +func TestVTS_VendorRegistration(t *testing.T) { + c := newVTSClient(t) + e := c.Executor + + vendorAcc := e.NewAccount(t) + userAcc := e.NewAccount(t) + committeeInvoker := c.WithSigners(c.Committee) + userInvoker := c.WithSigners(userAcc) + + t.Run("non-committee cannot register vendor", func(t *testing.T) { + userInvoker.InvokeFail(t, "caller is not a committee member", "registerVendor", vendorAcc.ScriptHash(), "Test Store", state.CategoryFood, false) + }) + + t.Run("committee can register vendor", func(t *testing.T) { + committeeInvoker.Invoke(t, true, "registerVendor", vendorAcc.ScriptHash(), "Test Store", state.CategoryFood, false) + }) + + t.Run("isVendor returns true", func(t *testing.T) { + c.Invoke(t, true, "isVendor", vendorAcc.ScriptHash()) + }) + + t.Run("non-vendor returns false", func(t *testing.T) { + c.Invoke(t, false, "isVendor", userAcc.ScriptHash()) + }) + + t.Run("getVendorCategories", func(t *testing.T) { + c.Invoke(t, int64(state.CategoryFood), "getVendorCategories", vendorAcc.ScriptHash()) + }) + + t.Run("getVendor returns vendor info", func(t *testing.T) { + c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + arr, ok := stack[0].Value().([]stackitem.Item) + require.True(t, ok, "expected array") + require.Equal(t, 7, len(arr)) // Vendor struct has 7 fields (including AgeRestricted) + }, "getVendor", vendorAcc.ScriptHash()) + }) + + t.Run("update vendor categories", func(t *testing.T) { + newCategories := state.CategoryFood | state.CategoryShelter + committeeInvoker.Invoke(t, true, "updateVendor", vendorAcc.ScriptHash(), "Test Store Updated", newCategories, false) + c.Invoke(t, int64(newCategories), "getVendorCategories", vendorAcc.ScriptHash()) + }) + + t.Run("deactivate vendor", func(t *testing.T) { + committeeInvoker.Invoke(t, true, "deactivateVendor", vendorAcc.ScriptHash()) + // isVendor should still return true (vendor exists) but Active=false + c.Invoke(t, false, "isVendor", vendorAcc.ScriptHash()) + }) +} + +// TestVTS_Spend tests spending at vendors. +func TestVTS_Spend(t *testing.T) { + c := newVTSClient(t) + e := c.Executor + + customer := e.NewAccount(t) + foodVendor := e.NewAccount(t) + committeeInvoker := c.WithSigners(c.Committee) + customerInvoker := c.WithSigners(customer) + + // Setup: Register Vita for customer (required for property rights/spending) + registerVitaForVTS(t, e, customer) + + // Setup: Register food vendor and mint to customer + committeeInvoker.Invoke(t, true, "registerVendor", foodVendor.ScriptHash(), "Food Store", state.CategoryFood, false) + committeeInvoker.Invoke(t, true, "mint", customer.ScriptHash(), 300_00000000) + + t.Run("customer can spend at vendor", func(t *testing.T) { + customerInvoker.Invoke(t, true, "spend", customer.ScriptHash(), foodVendor.ScriptHash(), 50_00000000, nil) + }) + + t.Run("vendor received VTS", func(t *testing.T) { + c.Invoke(t, 50_00000000, "balanceOf", foodVendor.ScriptHash()) + }) + + t.Run("customer balance reduced", func(t *testing.T) { + c.Invoke(t, 250_00000000, "balanceOf", customer.ScriptHash()) + }) + + t.Run("cannot spend at non-vendor", func(t *testing.T) { + nonVendor := e.NewAccount(t) + customerInvoker.InvokeFail(t, "invalid or inactive vendor", "spend", customer.ScriptHash(), nonVendor.ScriptHash(), 10_00000000, nil) + }) +} + +// TestVTS_CanSpendAt tests the canSpendAt query method. +func TestVTS_CanSpendAt(t *testing.T) { + c := newVTSClient(t) + e := c.Executor + + customer := e.NewAccount(t) + vendor := e.NewAccount(t) + committeeInvoker := c.WithSigners(c.Committee) + + // Setup: Register Vita for customer (required for property rights) + registerVitaForVTS(t, e, customer) + + // Setup + committeeInvoker.Invoke(t, true, "registerVendor", vendor.ScriptHash(), "Store", state.CategoryFood, false) + committeeInvoker.Invoke(t, true, "mint", customer.ScriptHash(), 100_00000000) + + t.Run("can spend within balance", func(t *testing.T) { + c.Invoke(t, true, "canSpendAt", customer.ScriptHash(), vendor.ScriptHash(), 50_00000000) + }) + + t.Run("cannot spend more than balance", func(t *testing.T) { + c.Invoke(t, false, "canSpendAt", customer.ScriptHash(), vendor.ScriptHash(), 200_00000000) + }) +} + +// TestVTS_ConvertToUnrestricted tests converting restricted VTS to unrestricted. +func TestVTS_ConvertToUnrestricted(t *testing.T) { + c := newVTSClient(t) + e := c.Executor + + acc := e.NewAccount(t) + committeeInvoker := c.WithSigners(c.Committee) + userInvoker := c.WithSigners(acc) + + // Restricted VTS requires Vita + registerVitaForVTS(t, e, acc) + + // Mint restricted VTS + committeeInvoker.Invoke(t, true, "mintRestricted", acc.ScriptHash(), 500_00000000, state.CategoryFood) + + t.Run("non-committee cannot convert", func(t *testing.T) { + userInvoker.InvokeFail(t, "caller is not a committee member", "convertToUnrestricted", acc.ScriptHash(), state.CategoryFood, 100_00000000) + }) + + t.Run("committee can convert", func(t *testing.T) { + committeeInvoker.Invoke(t, true, "convertToUnrestricted", acc.ScriptHash(), state.CategoryFood, 100_00000000) + }) + + t.Run("restricted balance reduced", func(t *testing.T) { + c.Invoke(t, 400_00000000, "restrictedBalanceOf", acc.ScriptHash(), state.CategoryFood) + }) + + t.Run("unrestricted balance increased", func(t *testing.T) { + c.Invoke(t, 100_00000000, "unrestrictedBalanceOf", acc.ScriptHash()) + }) + + t.Run("total balance unchanged", func(t *testing.T) { + c.Invoke(t, 500_00000000, "balanceOf", acc.ScriptHash()) + }) +} + +// TestVTS_TaxConfig tests tax configuration. +func TestVTS_TaxConfig(t *testing.T) { + c := newVTSClient(t) + e := c.Executor + + treasuryAcc := e.NewAccount(t) + userAcc := e.NewAccount(t) + committeeInvoker := c.WithSigners(c.Committee) + userInvoker := c.WithSigners(userAcc) + + t.Run("non-committee cannot set tax config", func(t *testing.T) { + userInvoker.InvokeFail(t, "caller is not a committee member", "setTaxConfig", 2500, 500, treasuryAcc.ScriptHash(), state.CategoryFood) + }) + + t.Run("committee can set tax config", func(t *testing.T) { + // 25% income tax, 5% sales tax + committeeInvoker.Invoke(t, true, "setTaxConfig", 2500, 500, treasuryAcc.ScriptHash(), state.CategoryFood) + }) + + t.Run("get tax config", func(t *testing.T) { + c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + arr, ok := stack[0].Value().([]stackitem.Item) + require.True(t, ok, "expected array") + require.Equal(t, 4, len(arr)) // TaxConfig has 4 fields + + incomeRate, _ := arr[0].TryInteger() + require.Equal(t, int64(2500), incomeRate.Int64()) + }, "getTaxConfig") + }) +} + +// TestVTS_PayWage tests payroll with automatic tax withholding. +func TestVTS_PayWage(t *testing.T) { + c := newVTSClient(t) + e := c.Executor + + employer := e.NewAccount(t) + employee := e.NewAccount(t) + treasury := e.NewAccount(t) + committeeInvoker := c.WithSigners(c.Committee) + employerInvoker := c.WithSigners(employer) + + // Setup: Register Vita for employer (required for property rights/transfers) + registerVitaForVTS(t, e, employer) + + // Setup: Set tax config and fund employer + committeeInvoker.Invoke(t, true, "setTaxConfig", 2500, 0, treasury.ScriptHash(), 0) // 25% income tax + committeeInvoker.Invoke(t, true, "mint", employer.ScriptHash(), 10000_00000000) + + t.Run("payWage with tax withholding", func(t *testing.T) { + // Pay $5000 gross, 25% tax rate + employerInvoker.Invoke(t, true, "payWage", employer.ScriptHash(), employee.ScriptHash(), 5000_00000000, 2500) + }) + + t.Run("employer balance reduced by gross", func(t *testing.T) { + c.Invoke(t, 5000_00000000, "balanceOf", employer.ScriptHash()) + }) + + t.Run("employee receives net (75%)", func(t *testing.T) { + c.Invoke(t, 3750_00000000, "balanceOf", employee.ScriptHash()) + }) + + t.Run("treasury receives tax (25%)", func(t *testing.T) { + c.Invoke(t, 1250_00000000, "balanceOf", treasury.ScriptHash()) + }) +} + +// TestVTS_TaxRefund tests issuing tax refunds. +func TestVTS_TaxRefund(t *testing.T) { + c := newVTSClient(t) + e := c.Executor + + acc := e.NewAccount(t) + treasury := e.NewAccount(t) + committeeInvoker := c.WithSigners(c.Committee) + userInvoker := c.WithSigners(acc) + + // Setup: Set tax config + committeeInvoker.Invoke(t, true, "setTaxConfig", 2500, 0, treasury.ScriptHash(), 0) + + t.Run("non-committee cannot issue refund", func(t *testing.T) { + userInvoker.InvokeFail(t, "caller is not a committee member", "issueTaxRefund", acc.ScriptHash(), 100_00000000) + }) + + t.Run("committee can issue refund", func(t *testing.T) { + committeeInvoker.Invoke(t, true, "issueTaxRefund", acc.ScriptHash(), 100_00000000) + }) + + t.Run("refund credited to account", func(t *testing.T) { + c.Invoke(t, 100_00000000, "balanceOf", acc.ScriptHash()) + }) +} + +// TestVTS_BalanceDetails tests the balanceDetails query. +func TestVTS_BalanceDetails(t *testing.T) { + c := newVTSClient(t) + e := c.Executor + + acc := e.NewAccount(t) + committeeInvoker := c.WithSigners(c.Committee) + + // Restricted VTS requires Vita + registerVitaForVTS(t, e, acc) + + // Mint mixed VTS + committeeInvoker.Invoke(t, true, "mint", acc.ScriptHash(), 100_00000000) + committeeInvoker.Invoke(t, true, "mintRestricted", acc.ScriptHash(), 200_00000000, state.CategoryFood) + committeeInvoker.Invoke(t, true, "mintRestricted", acc.ScriptHash(), 300_00000000, state.CategoryShelter) + + t.Run("balanceDetails returns all categories", func(t *testing.T) { + c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + arr, ok := stack[0].Value().([]stackitem.Item) + require.True(t, ok, "expected array") + // Should have unrestricted + categories with balances + require.GreaterOrEqual(t, len(arr), 1) + }, "balanceDetails", acc.ScriptHash()) + }) +} + +// TestVTS_TaxReportingMethods tests the tax reporting query methods. +func TestVTS_TaxReportingMethods(t *testing.T) { + c := newVTSClient(t) + e := c.Executor + + acc := e.NewAccount(t) + + // Block range for queries + startBlock := int64(0) + endBlock := int64(1000) + + t.Run("getTransactions returns array", func(t *testing.T) { + c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + _, ok := stack[0].Value().([]stackitem.Item) + require.True(t, ok, "expected array") + }, "getTransactions", acc.ScriptHash(), startBlock, endBlock) + }) + + t.Run("getIncomeForPeriod returns integer", func(t *testing.T) { + c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + _, err := stack[0].TryInteger() + require.NoError(t, err) + }, "getIncomeForPeriod", acc.ScriptHash(), startBlock, endBlock) + }) + + t.Run("getTaxWithheld returns integer", func(t *testing.T) { + c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + _, err := stack[0].TryInteger() + require.NoError(t, err) + }, "getTaxWithheld", acc.ScriptHash(), startBlock, endBlock) + }) + + t.Run("getDeductibleExpenses returns integer", func(t *testing.T) { + c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + _, err := stack[0].TryInteger() + require.NoError(t, err) + }, "getDeductibleExpenses", acc.ScriptHash(), startBlock, endBlock, 0) + }) + + t.Run("getTaxSummary returns array", func(t *testing.T) { + c.InvokeAndCheck(t, func(t testing.TB, stack []stackitem.Item) { + require.Equal(t, 1, len(stack)) + arr, ok := stack[0].Value().([]stackitem.Item) + require.True(t, ok, "expected array for tax summary") + // TaxSummary has 10 fields: Account, StartBlock, EndBlock, TotalIncome, + // TotalBenefits, TotalExpenses, DeductibleExpenses, TaxWithheld, EstimatedOwed, Balance + require.Equal(t, 10, len(arr)) + }, "getTaxSummary", acc.ScriptHash(), startBlock, endBlock) + }) +} + +// TestVTS_NegativeAmount tests that negative amounts are rejected. +func TestVTS_NegativeAmount(t *testing.T) { + c := newVTSClient(t) + e := c.Executor + + acc := e.NewAccount(t) + committeeInvoker := c.WithSigners(c.Committee) + + // Restricted VTS requires Vita + registerVitaForVTS(t, e, acc) + + t.Run("mint negative fails", func(t *testing.T) { + committeeInvoker.InvokeFail(t, "amount must be positive", "mint", acc.ScriptHash(), -1) + }) + + t.Run("mintRestricted negative fails", func(t *testing.T) { + committeeInvoker.InvokeFail(t, "amount must be positive", "mintRestricted", acc.ScriptHash(), -1, state.CategoryFood) + }) +} + +// TestVTS_MultiCategoryVendor tests vendors accepting multiple categories. +func TestVTS_MultiCategoryVendor(t *testing.T) { + c := newVTSClient(t) + e := c.Executor + + customer := e.NewAccount(t) + generalStore := e.NewAccount(t) + committeeInvoker := c.WithSigners(c.Committee) + customerInvoker := c.WithSigners(customer) + + // Restricted VTS requires Vita + registerVitaForVTS(t, e, customer) + + // Register vendor accepting food AND shelter + categories := state.CategoryFood | state.CategoryShelter + committeeInvoker.Invoke(t, true, "registerVendor", generalStore.ScriptHash(), "General Store", categories, false) + + // Mint restricted VTS for different categories + committeeInvoker.Invoke(t, true, "mintRestricted", customer.ScriptHash(), 100_00000000, state.CategoryFood) + committeeInvoker.Invoke(t, true, "mintRestricted", customer.ScriptHash(), 100_00000000, state.CategoryShelter) + + t.Run("can spend at multi-category vendor", func(t *testing.T) { + customerInvoker.Invoke(t, true, "spend", customer.ScriptHash(), generalStore.ScriptHash(), 50_00000000, nil) + // Total balance should be reduced by 50 + c.Invoke(t, 150_00000000, "balanceOf", customer.ScriptHash()) + }) + + t.Run("can spend more at same vendor", func(t *testing.T) { + customerInvoker.Invoke(t, true, "spend", customer.ScriptHash(), generalStore.ScriptHash(), 50_00000000, nil) + customerInvoker.Invoke(t, true, "spend", customer.ScriptHash(), generalStore.ScriptHash(), 50_00000000, nil) + // Total balance should be reduced by 150 + c.Invoke(t, 50_00000000, "balanceOf", customer.ScriptHash()) + }) + + t.Run("vendor has correct total", func(t *testing.T) { + c.Invoke(t, 150_00000000, "balanceOf", generalStore.ScriptHash()) + }) +} + +// TestVTS_AgeRestrictedVendor tests age verification for age-restricted vendors. +func TestVTS_AgeRestrictedVendor(t *testing.T) { + c := newVTSClient(t) + e := c.Executor + + adultCustomer := e.NewAccount(t) + minorCustomer := e.NewAccount(t) + liquorStore := e.NewAccount(t) + committeeInvoker := c.WithSigners(c.Committee) + adultInvoker := c.WithSigners(adultCustomer) + minorInvoker := c.WithSigners(minorCustomer) + + // Register Vita for both customers + registerVitaForVTS(t, e, adultCustomer) + registerVitaForVTS(t, e, minorCustomer) + + // Only adult has age_verified attribute + addAgeVerifiedAttribute(t, e, c.Committee, adultCustomer) + + // Register age-restricted vendor (liquor store) + committeeInvoker.Invoke(t, true, "registerVendor", liquorStore.ScriptHash(), "Liquor Store", state.CategoryFood, true) + + // Mint VTS to both customers + committeeInvoker.Invoke(t, true, "mint", adultCustomer.ScriptHash(), 100_00000000) + committeeInvoker.Invoke(t, true, "mint", minorCustomer.ScriptHash(), 100_00000000) + + t.Run("minor cannot spend at age-restricted vendor", func(t *testing.T) { + minorInvoker.InvokeFail(t, "age verification required for this vendor", "spend", minorCustomer.ScriptHash(), liquorStore.ScriptHash(), 10_00000000, nil) + }) + + t.Run("adult can spend at age-restricted vendor", func(t *testing.T) { + adultInvoker.Invoke(t, true, "spend", adultCustomer.ScriptHash(), liquorStore.ScriptHash(), 10_00000000, nil) + }) + + t.Run("canSpendAt returns false for minor at age-restricted vendor", func(t *testing.T) { + c.Invoke(t, false, "canSpendAt", minorCustomer.ScriptHash(), liquorStore.ScriptHash(), 10_00000000) + }) + + t.Run("canSpendAt returns true for adult at age-restricted vendor", func(t *testing.T) { + c.Invoke(t, true, "canSpendAt", adultCustomer.ScriptHash(), liquorStore.ScriptHash(), 10_00000000) + }) +} + +// TestVTS_MintRestrictedRequiresVita tests that minting restricted VTS requires a Vita. +func TestVTS_MintRestrictedRequiresVita(t *testing.T) { + c := newVTSClient(t) + e := c.Executor + + accWithVita := e.NewAccount(t) + accWithoutVita := e.NewAccount(t) + committeeInvoker := c.WithSigners(c.Committee) + + // Only register Vita for one account + registerVitaForVTS(t, e, accWithVita) + + t.Run("cannot mint restricted VTS to account without Vita", func(t *testing.T) { + committeeInvoker.InvokeFail(t, "restricted VTS requires Vita", "mintRestricted", accWithoutVita.ScriptHash(), 100_00000000, state.CategoryFood) + }) + + t.Run("can mint restricted VTS to account with Vita", func(t *testing.T) { + committeeInvoker.Invoke(t, true, "mintRestricted", accWithVita.ScriptHash(), 100_00000000, state.CategoryFood) + }) +} diff --git a/pkg/core/native/policy_test.go b/pkg/core/native/policy_test.go index f944174..fd21cee 100644 --- a/pkg/core/native/policy_test.go +++ b/pkg/core/native/policy_test.go @@ -10,8 +10,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/native/nativehashes" "github.com/tutus-one/tutus-chain/pkg/core/native/nativenames" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/vm" "github.com/stretchr/testify/require" ) diff --git a/pkg/core/state/contract_invocation_test.go b/pkg/core/state/contract_invocation_test.go index 8ae0c2b..c53e208 100644 --- a/pkg/core/state/contract_invocation_test.go +++ b/pkg/core/state/contract_invocation_test.go @@ -3,7 +3,7 @@ package state import ( "testing" - json "github.com/nspcc-dev/go-ordered-json" + json "github.com/tutus-one/tutus-ordered-json" "github.com/tutus-one/tutus-chain/internal/testserdes" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" diff --git a/pkg/core/statesync/neotest_test.go b/pkg/core/statesync/neotest_test.go index a00648a..ce157b2 100644 --- a/pkg/core/statesync/neotest_test.go +++ b/pkg/core/statesync/neotest_test.go @@ -9,8 +9,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/block" "github.com/tutus-one/tutus-chain/pkg/core/mpt" "github.com/tutus-one/tutus-chain/pkg/core/storage" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/stretchr/testify/require" ) diff --git a/pkg/core/storage/boltdb_store.go b/pkg/core/storage/boltdb_store.go index 20a85ba..50a56df 100644 --- a/pkg/core/storage/boltdb_store.go +++ b/pkg/core/storage/boltdb_store.go @@ -7,7 +7,7 @@ import ( "os" "time" - "github.com/nspcc-dev/bbolt" + "github.com/tutus-one/tutus-bolt" "github.com/tutus-one/tutus-chain/pkg/core/storage/dbconfig" "github.com/tutus-one/tutus-chain/pkg/io" ) diff --git a/pkg/core/storage/boltdb_store_test.go b/pkg/core/storage/boltdb_store_test.go index 39608c9..b9b436b 100644 --- a/pkg/core/storage/boltdb_store_test.go +++ b/pkg/core/storage/boltdb_store_test.go @@ -6,8 +6,8 @@ import ( "strings" "testing" - "github.com/nspcc-dev/bbolt" - "github.com/nspcc-dev/bbolt/errors" + "github.com/tutus-one/tutus-bolt" + "github.com/tutus-one/tutus-bolt/errors" "github.com/tutus-one/tutus-chain/pkg/core/storage/dbconfig" "github.com/stretchr/testify/require" ) diff --git a/pkg/crypto/keys/private_key.go b/pkg/crypto/keys/private_key.go index c710b7c..fc8f710 100644 --- a/pkg/crypto/keys/private_key.go +++ b/pkg/crypto/keys/private_key.go @@ -13,7 +13,7 @@ import ( "github.com/decred/dcrd/dcrec/secp256k1/v4" "github.com/tutus-one/tutus-chain/pkg/crypto/hash" "github.com/tutus-one/tutus-chain/pkg/util" - "github.com/nspcc-dev/rfc6979" + "github.com/tutus-one/tutus-rfc6979" ) // PrivateKey represents a Neo private key and provides a high level API around diff --git a/pkg/interop/contract/contract.go b/pkg/interop/contract/contract.go index e56edf7..a7d272c 100644 --- a/pkg/interop/contract/contract.go +++ b/pkg/interop/contract/contract.go @@ -5,7 +5,7 @@ package contract import ( "github.com/tutus-one/tutus-chain/pkg/interop" - "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" ) // CallFlag specifies valid call flags. @@ -28,19 +28,19 @@ const ( // script using the given m and a set of public keys bytes. This function uses // `System.Contract.CreateMultisigAccount` syscall. func CreateMultisigAccount(m int, pubs []interop.PublicKey) []byte { - return neogointernal.Syscall2("System.Contract.CreateMultisigAccount", m, pubs).([]byte) + return tutusinternal.Syscall2("System.Contract.CreateMultisigAccount", m, pubs).([]byte) } // CreateStandardAccount calculates a script hash of the given public key. // This function uses `System.Contract.CreateStandardAccount` syscall. func CreateStandardAccount(pub interop.PublicKey) []byte { - return neogointernal.Syscall1("System.Contract.CreateStandardAccount", pub).([]byte) + return tutusinternal.Syscall1("System.Contract.CreateStandardAccount", pub).([]byte) } // GetCallFlags returns the calling flags which execution context was created with. // This function uses `System.Contract.GetCallFlags` syscall. func GetCallFlags() CallFlag { - return neogointernal.Syscall0("System.Contract.GetCallFlags").(CallFlag) + return tutusinternal.Syscall0("System.Contract.GetCallFlags").(CallFlag) } // Call executes the previously deployed blockchain contract with the specified hash @@ -48,5 +48,5 @@ func GetCallFlags() CallFlag { // It returns whatever this contract returns. This function uses // `System.Contract.Call` syscall. func Call(scriptHash interop.Hash160, method string, f CallFlag, args ...any) any { - return neogointernal.Syscall4("System.Contract.Call", scriptHash, method, f, args) + return tutusinternal.Syscall4("System.Contract.Call", scriptHash, method, f, args) } diff --git a/pkg/interop/convert/convert.go b/pkg/interop/convert/convert.go index 9ce6f88..c42c7dc 100644 --- a/pkg/interop/convert/convert.go +++ b/pkg/interop/convert/convert.go @@ -1,7 +1,7 @@ // Package convert provides functions for type conversion. package convert -import "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" +import "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" // ToInteger converts it's argument to an Integer. func ToInteger(v any) int { @@ -40,7 +40,7 @@ func BytesToUint8(data []byte) uint8 { func Uint16ToBytesBE(n uint16) []byte { var res = make([]byte, 2) copy(res, ToBytes(n)) - neogointernal.Opcode1NoReturn("REVERSEITEMS", res) + tutusinternal.Opcode1NoReturn("REVERSEITEMS", res) return res } @@ -51,7 +51,7 @@ func BytesBEToUint16(data []byte) uint16 { } src := make([]byte, 2) copy(src, data) - neogointernal.Opcode1NoReturn("REVERSEITEMS", src) + tutusinternal.Opcode1NoReturn("REVERSEITEMS", src) src = append(src, 0) // preserve compatibility with bigint.FromBytes. return uint16(ToInteger(src)) } @@ -77,7 +77,7 @@ func BytesLEToUint16(data []byte) uint16 { func Uint32ToBytesBE(n uint32) []byte { var res = make([]byte, 4) copy(res, ToBytes(n)) - neogointernal.Opcode1NoReturn("REVERSEITEMS", res) + tutusinternal.Opcode1NoReturn("REVERSEITEMS", res) return res } @@ -88,7 +88,7 @@ func BytesBEToUint32(data []byte) uint32 { } src := make([]byte, 4) copy(src, data) - neogointernal.Opcode1NoReturn("REVERSEITEMS", src) + tutusinternal.Opcode1NoReturn("REVERSEITEMS", src) src = append(src, 0) // preserve compatibility with bigint.FromBytes. return uint32(ToInteger(src)) } @@ -114,7 +114,7 @@ func BytesLEToUint32(data []byte) uint32 { func Uint64ToBytesBE(n uint64) []byte { var res = make([]byte, 8) copy(res, ToBytes(n)) - neogointernal.Opcode1NoReturn("REVERSEITEMS", res) + tutusinternal.Opcode1NoReturn("REVERSEITEMS", res) return res } @@ -125,7 +125,7 @@ func BytesBEToUint64(data []byte) uint64 { } src := make([]byte, 8) copy(src, data) - neogointernal.Opcode1NoReturn("REVERSEITEMS", src) + tutusinternal.Opcode1NoReturn("REVERSEITEMS", src) src = append(src, 0) // preserve compatibility with bigint.FromBytes. return uint64(ToInteger(src)) } diff --git a/pkg/interop/crypto/crypto.go b/pkg/interop/crypto/crypto.go index a70b281..b69e2ea 100644 --- a/pkg/interop/crypto/crypto.go +++ b/pkg/interop/crypto/crypto.go @@ -5,18 +5,18 @@ package crypto import ( "github.com/tutus-one/tutus-chain/pkg/interop" - "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" ) // CheckMultisig checks that the script container (transaction) is signed by multiple // ECDSA keys at once. It uses `System.Crypto.CheckMultisig` syscall. func CheckMultisig(pubs []interop.PublicKey, sigs []interop.Signature) bool { - return neogointernal.Syscall2("System.Crypto.CheckMultisig", pubs, sigs).(bool) + return tutusinternal.Syscall2("System.Crypto.CheckMultisig", pubs, sigs).(bool) } // CheckSig checks that sig is a correct signature of the script container // (transaction) for the given pub (serialized public key). It uses // `System.Crypto.CheckSig` syscall. func CheckSig(pub interop.PublicKey, sig interop.Signature) bool { - return neogointernal.Syscall2("System.Crypto.CheckSig", pub, sig).(bool) + return tutusinternal.Syscall2("System.Crypto.CheckSig", pub, sig).(bool) } diff --git a/pkg/interop/iterator/iterator.go b/pkg/interop/iterator/iterator.go index 3ebd919..b4e73d8 100644 --- a/pkg/interop/iterator/iterator.go +++ b/pkg/interop/iterator/iterator.go @@ -3,7 +3,7 @@ Package iterator provides functions to work with Neo iterators. */ package iterator -import "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" +import "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" // Iterator represents a Neo iterator, it's an opaque data structure that can // be properly created by storage.Find. Iterators range over key-value pairs, @@ -16,7 +16,7 @@ type Iterator struct{} // otherwise (and there are no more elements in this Iterator). This function // uses `System.Iterator.Next` syscall. func Next(it Iterator) bool { - return neogointernal.Syscall1("System.Iterator.Next", it).(bool) + return tutusinternal.Syscall1("System.Iterator.Next", it).(bool) } // Value returns iterator's current value. It's only valid to call after @@ -27,5 +27,5 @@ func Next(it Iterator) bool { // If the iterator is configured to return key-value pairs, the result can be // directly type-asserted to [storage.KeyValue] type. func Value(it Iterator) any { - return neogointernal.Syscall1("System.Iterator.Value", it) + return tutusinternal.Syscall1("System.Iterator.Value", it) } diff --git a/pkg/interop/math/math.go b/pkg/interop/math/math.go index 685cde5..c36c38e 100644 --- a/pkg/interop/math/math.go +++ b/pkg/interop/math/math.go @@ -3,17 +3,17 @@ Package math provides access to useful numeric functions available in Neo VM. */ package math -import "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" +import "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" // Pow returns a^b using POW VM opcode. // b must be >= 0 and <= 2^31-1. func Pow(a, b int) int { - return neogointernal.Opcode2("POW", a, b).(int) + return tutusinternal.Opcode2("POW", a, b).(int) } // Sqrt returns a positive square root of x rounded down. func Sqrt(x int) int { - return neogointernal.Opcode1("SQRT", x).(int) + return tutusinternal.Opcode1("SQRT", x).(int) } // Sign returns: @@ -22,26 +22,26 @@ func Sqrt(x int) int { // 0 if x == 0 // +1 if x > 0 func Sign(a int) int { - return neogointernal.Opcode1("SIGN", a).(int) + return tutusinternal.Opcode1("SIGN", a).(int) } // Abs returns an absolute value of a. func Abs(a int) int { - return neogointernal.Opcode1("ABS", a).(int) + return tutusinternal.Opcode1("ABS", a).(int) } // Within returns true if a <= x < b. func Within(x, a, b int) bool { - return neogointernal.Opcode3("WITHIN", x, a, b).(bool) + return tutusinternal.Opcode3("WITHIN", x, a, b).(bool) } // ModMul returns the result of modulus division on a*b. func ModMul(a, b, mod int) int { - return neogointernal.Opcode3("MODMUL", a, b, mod).(int) + return tutusinternal.Opcode3("MODMUL", a, b, mod).(int) } // ModPow returns the result of modulus division on a^b. If b is -1, // it returns the modular inverse of a. func ModPow(a, b, mod int) int { - return neogointernal.Opcode3("MODPOW", a, b, mod).(int) + return tutusinternal.Opcode3("MODPOW", a, b, mod).(int) } diff --git a/pkg/interop/native/crypto/crypto.go b/pkg/interop/native/crypto/crypto.go index 2f5c8ec..e714e7b 100644 --- a/pkg/interop/native/crypto/crypto.go +++ b/pkg/interop/native/crypto/crypto.go @@ -7,7 +7,7 @@ package crypto import ( "github.com/tutus-one/tutus-chain/pkg/interop" "github.com/tutus-one/tutus-chain/pkg/interop/contract" - "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" ) // Hash represents CryptoLib contract hash. @@ -26,31 +26,31 @@ const ( // Sha256 calls `sha256` method of native CryptoLib contract and computes SHA256 hash of b. func Sha256(b []byte) interop.Hash256 { - return neogointernal.CallWithToken(Hash, "sha256", int(contract.NoneFlag), b).(interop.Hash256) + return tutusinternal.CallWithToken(Hash, "sha256", int(contract.NoneFlag), b).(interop.Hash256) } // Ripemd160 calls `ripemd160` method of native CryptoLib contract and computes RIPEMD160 hash of b. func Ripemd160(b []byte) interop.Hash160 { - return neogointernal.CallWithToken(Hash, "ripemd160", int(contract.NoneFlag), b).(interop.Hash160) + return tutusinternal.CallWithToken(Hash, "ripemd160", int(contract.NoneFlag), b).(interop.Hash160) } // Murmur32 calls `murmur32` method of native CryptoLib contract and computes Murmur32 hash of b // using the given seed. func Murmur32(b []byte, seed int) []byte { - return neogointernal.CallWithToken(Hash, "murmur32", int(contract.NoneFlag), b, seed).([]byte) + return tutusinternal.CallWithToken(Hash, "murmur32", int(contract.NoneFlag), b, seed).([]byte) } // VerifyWithECDsa calls `verifyWithECDsa` method of native CryptoLib contract and checks that sig is // a correct msg's signature for the given pub (serialized public key on the given curve). func VerifyWithECDsa(msg []byte, pub interop.PublicKey, sig interop.Signature, curveHash NamedCurveHash) bool { - return neogointernal.CallWithToken(Hash, "verifyWithECDsa", int(contract.NoneFlag), msg, pub, sig, curveHash).(bool) + return tutusinternal.CallWithToken(Hash, "verifyWithECDsa", int(contract.NoneFlag), msg, pub, sig, curveHash).(bool) } // VerifyWithEd25519 calls `verifyWithEd25519` method of native CryptoLib contract and checks that sig is // a correct msg's signature for the given pub. Note that this method is available starting from // [config.HFEchidna] hardfork. func VerifyWithEd25519(msg []byte, pub []byte, sig []byte) bool { - return neogointernal.CallWithToken(Hash, "verifyWithEd25519", int(contract.NoneFlag), msg, pub, sig).(bool) + return tutusinternal.CallWithToken(Hash, "verifyWithEd25519", int(contract.NoneFlag), msg, pub, sig).(bool) } // RecoverSecp256K1 calls `recoverSecp256K1` method of native CryptoLib contract and returns Secp256K1 @@ -58,7 +58,7 @@ func VerifyWithEd25519(msg []byte, pub []byte, sig []byte) bool { // or in form of https://eips.ethereum.org/EIPS/eip-2098#specification). Note that this method is available // starting from [config.HFEchidna] hardfork. func RecoverSecp256K1(msgHash []byte, sig []byte) []byte { - return neogointernal.CallWithToken(Hash, "recoverSecp256K1", int(contract.NoneFlag), msgHash, sig).([]byte) + return tutusinternal.CallWithToken(Hash, "recoverSecp256K1", int(contract.NoneFlag), msgHash, sig).([]byte) } // Bls12381Point represents BLS12-381 curve point (G1 or G2 in the Affine or @@ -73,25 +73,25 @@ type Bls12381Point struct{} // Bls12381Serialize calls `bls12381Serialize` method of native CryptoLib contract // and serializes given BLS12-381 point into byte array. func Bls12381Serialize(g Bls12381Point) []byte { - return neogointernal.CallWithToken(Hash, "bls12381Serialize", int(contract.NoneFlag), g).([]byte) + return tutusinternal.CallWithToken(Hash, "bls12381Serialize", int(contract.NoneFlag), g).([]byte) } // Bls12381Deserialize calls `bls12381Deserialize` method of native CryptoLib // contract and deserializes given BLS12-381 point from byte array. func Bls12381Deserialize(data []byte) Bls12381Point { - return neogointernal.CallWithToken(Hash, "bls12381Deserialize", int(contract.NoneFlag), data).(Bls12381Point) + return tutusinternal.CallWithToken(Hash, "bls12381Deserialize", int(contract.NoneFlag), data).(Bls12381Point) } // Bls12381Equal calls `bls12381Equal` method of native CryptoLib contract and // checks whether two BLS12-381 points are equal. func Bls12381Equal(x, y Bls12381Point) bool { - return neogointernal.CallWithToken(Hash, "bls12381Equal", int(contract.NoneFlag), x, y).(bool) + return tutusinternal.CallWithToken(Hash, "bls12381Equal", int(contract.NoneFlag), x, y).(bool) } // Bls12381Add calls `bls12381Add` method of native CryptoLib contract and // performs addition operation over two BLS12-381 points. func Bls12381Add(x, y Bls12381Point) Bls12381Point { - return neogointernal.CallWithToken(Hash, "bls12381Add", int(contract.NoneFlag), x, y).(Bls12381Point) + return tutusinternal.CallWithToken(Hash, "bls12381Add", int(contract.NoneFlag), x, y).(Bls12381Point) } // Bls12381Mul calls `bls12381Mul` method of native CryptoLib contract and @@ -100,18 +100,18 @@ func Bls12381Add(x, y Bls12381Point) Bls12381Point { // field element stored on 4 words (uint64) with 32-bytes length. The last // argument denotes whether the multiplicator should be negative. func Bls12381Mul(x Bls12381Point, mul []byte, neg bool) Bls12381Point { - return neogointernal.CallWithToken(Hash, "bls12381Mul", int(contract.NoneFlag), x, mul, neg).(Bls12381Point) + return tutusinternal.CallWithToken(Hash, "bls12381Mul", int(contract.NoneFlag), x, mul, neg).(Bls12381Point) } // Bls12381Pairing calls `bls12381Pairing` method of native CryptoLib contract and // performs pairing operation over two BLS12-381 points which must be G1 and G2 either // in Affine or Jacobian forms. The result of this operation is GT point. func Bls12381Pairing(g1, g2 Bls12381Point) Bls12381Point { - return neogointernal.CallWithToken(Hash, "bls12381Pairing", int(contract.NoneFlag), g1, g2).(Bls12381Point) + return tutusinternal.CallWithToken(Hash, "bls12381Pairing", int(contract.NoneFlag), g1, g2).(Bls12381Point) } // Keccak256 calls `keccak256` method of native CryptoLib contract and // computes Keccak256 hash of b. func Keccak256(b []byte) interop.Hash256 { - return neogointernal.CallWithToken(Hash, "keccak256", int(contract.NoneFlag), b).(interop.Hash256) + return tutusinternal.CallWithToken(Hash, "keccak256", int(contract.NoneFlag), b).(interop.Hash256) } diff --git a/pkg/interop/native/ledger/ledger.go b/pkg/interop/native/ledger/ledger.go index 5f5f0c7..95fc97f 100644 --- a/pkg/interop/native/ledger/ledger.go +++ b/pkg/interop/native/ledger/ledger.go @@ -7,7 +7,7 @@ package ledger import ( "github.com/tutus-one/tutus-chain/pkg/interop" "github.com/tutus-one/tutus-chain/pkg/interop/contract" - "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" ) // Hash represents Ledger contract hash. @@ -30,42 +30,42 @@ const ( // CurrentHash represents `currentHash` method of Ledger native contract. func CurrentHash() interop.Hash256 { - return neogointernal.CallWithToken(Hash, "currentHash", int(contract.ReadStates)).(interop.Hash256) + return tutusinternal.CallWithToken(Hash, "currentHash", int(contract.ReadStates)).(interop.Hash256) } // CurrentIndex represents `currentIndex` method of Ledger native contract. func CurrentIndex() int { - return neogointernal.CallWithToken(Hash, "currentIndex", int(contract.ReadStates)).(int) + return tutusinternal.CallWithToken(Hash, "currentIndex", int(contract.ReadStates)).(int) } // GetBlock represents `getBlock` method of Ledger native contract. func GetBlock(indexOrHash any) *Block { - return neogointernal.CallWithToken(Hash, "getBlock", int(contract.ReadStates), indexOrHash).(*Block) + return tutusinternal.CallWithToken(Hash, "getBlock", int(contract.ReadStates), indexOrHash).(*Block) } // GetTransaction represents `getTransaction` method of Ledger native contract. func GetTransaction(hash interop.Hash256) *Transaction { - return neogointernal.CallWithToken(Hash, "getTransaction", int(contract.ReadStates), hash).(*Transaction) + return tutusinternal.CallWithToken(Hash, "getTransaction", int(contract.ReadStates), hash).(*Transaction) } // GetTransactionHeight represents `getTransactionHeight` method of Ledger native contract. func GetTransactionHeight(hash interop.Hash256) int { - return neogointernal.CallWithToken(Hash, "getTransactionHeight", int(contract.ReadStates), hash).(int) + return tutusinternal.CallWithToken(Hash, "getTransactionHeight", int(contract.ReadStates), hash).(int) } // GetTransactionFromBlock represents `getTransactionFromBlock` method of Ledger native contract. func GetTransactionFromBlock(indexOrHash any, txIndex int) *Transaction { - return neogointernal.CallWithToken(Hash, "getTransactionFromBlock", int(contract.ReadStates), + return tutusinternal.CallWithToken(Hash, "getTransactionFromBlock", int(contract.ReadStates), indexOrHash, txIndex).(*Transaction) } // GetTransactionSigners represents `getTransactionSigners` method of Ledger native contract. func GetTransactionSigners(hash interop.Hash256) []TransactionSigner { - return neogointernal.CallWithToken(Hash, "getTransactionSigners", int(contract.ReadStates), + return tutusinternal.CallWithToken(Hash, "getTransactionSigners", int(contract.ReadStates), hash).([]TransactionSigner) } // GetTransactionVMState represents `getTransactionVMState` method of Ledger native contract. func GetTransactionVMState(hash interop.Hash256) VMState { - return neogointernal.CallWithToken(Hash, "getTransactionVMState", int(contract.ReadStates), hash).(VMState) + return tutusinternal.CallWithToken(Hash, "getTransactionVMState", int(contract.ReadStates), hash).(VMState) } diff --git a/pkg/interop/native/lub/lub.go b/pkg/interop/native/lub/lub.go index c6e9745..85269b5 100644 --- a/pkg/interop/native/lub/lub.go +++ b/pkg/interop/native/lub/lub.go @@ -7,7 +7,7 @@ package lub import ( "github.com/tutus-one/tutus-chain/pkg/interop" "github.com/tutus-one/tutus-chain/pkg/interop/contract" - "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" ) // Hash represents Lub contract hash. @@ -15,26 +15,26 @@ const Hash = "\x69\xe8\x15\x86\x5e\xaa\x14\x6f\xdd\x64\x79\xd4\xa3\x57\xf0\x70\x // Symbol represents `symbol` method of Lub native contract. func Symbol() string { - return neogointernal.CallWithToken(Hash, "symbol", int(contract.NoneFlag)).(string) + return tutusinternal.CallWithToken(Hash, "symbol", int(contract.NoneFlag)).(string) } // Decimals represents `decimals` method of Lub native contract. func Decimals() int { - return neogointernal.CallWithToken(Hash, "decimals", int(contract.NoneFlag)).(int) + return tutusinternal.CallWithToken(Hash, "decimals", int(contract.NoneFlag)).(int) } // TotalSupply represents `totalSupply` method of Lub native contract. func TotalSupply() int { - return neogointernal.CallWithToken(Hash, "totalSupply", int(contract.ReadStates)).(int) + return tutusinternal.CallWithToken(Hash, "totalSupply", int(contract.ReadStates)).(int) } // BalanceOf represents `balanceOf` method of Lub native contract. func BalanceOf(addr interop.Hash160) int { - return neogointernal.CallWithToken(Hash, "balanceOf", int(contract.ReadStates), addr).(int) + return tutusinternal.CallWithToken(Hash, "balanceOf", int(contract.ReadStates), addr).(int) } // Transfer represents `transfer` method of Lub native contract. func Transfer(from, to interop.Hash160, amount int, data any) bool { - return neogointernal.CallWithToken(Hash, "transfer", + return tutusinternal.CallWithToken(Hash, "transfer", int(contract.All), from, to, amount, data).(bool) } diff --git a/pkg/interop/native/management/management.go b/pkg/interop/native/management/management.go index 41aef68..bdbd78e 100644 --- a/pkg/interop/native/management/management.go +++ b/pkg/interop/native/management/management.go @@ -8,7 +8,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/interop" "github.com/tutus-one/tutus-chain/pkg/interop/contract" "github.com/tutus-one/tutus-chain/pkg/interop/iterator" - "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" ) // Hash represents Management contract hash. @@ -24,29 +24,29 @@ type IDHash struct { // Deploy represents `deploy` method of Management native contract. func Deploy(script, manifest []byte) *Contract { - return neogointernal.CallWithToken(Hash, "deploy", + return tutusinternal.CallWithToken(Hash, "deploy", int(contract.All), script, manifest).(*Contract) } // DeployWithData represents `deploy` method of Management native contract. func DeployWithData(script, manifest []byte, data any) *Contract { - return neogointernal.CallWithToken(Hash, "deploy", + return tutusinternal.CallWithToken(Hash, "deploy", int(contract.All), script, manifest, data).(*Contract) } // Destroy represents `destroy` method of Management native contract. func Destroy() { - neogointernal.CallWithTokenNoRet(Hash, "destroy", int(contract.States|contract.AllowNotify)) + tutusinternal.CallWithTokenNoRet(Hash, "destroy", int(contract.States|contract.AllowNotify)) } // GetContract represents `getContract` method of Management native contract. func GetContract(addr interop.Hash160) *Contract { - return neogointernal.CallWithToken(Hash, "getContract", int(contract.ReadStates), addr).(*Contract) + return tutusinternal.CallWithToken(Hash, "getContract", int(contract.ReadStates), addr).(*Contract) } // GetContractByID represents `getContractById` method of the Management native contract. func GetContractByID(id int) *Contract { - return neogointernal.CallWithToken(Hash, "getContractById", int(contract.ReadStates), id).(*Contract) + return tutusinternal.CallWithToken(Hash, "getContractById", int(contract.ReadStates), id).(*Contract) } // GetContractHashes represents `getContractHashes` method of the Management @@ -54,34 +54,34 @@ func GetContractByID(id int) *Contract { // hashes. Each iterator value can be cast to IDHash. Use [iterator] interop // package to work with the returned Iterator. func GetContractHashes() iterator.Iterator { - return neogointernal.CallWithToken(Hash, "getContractHashes", int(contract.ReadStates)).(iterator.Iterator) + return tutusinternal.CallWithToken(Hash, "getContractHashes", int(contract.ReadStates)).(iterator.Iterator) } // GetMinimumDeploymentFee represents `getMinimumDeploymentFee` method of Management native contract. func GetMinimumDeploymentFee() int { - return neogointernal.CallWithToken(Hash, "getMinimumDeploymentFee", int(contract.ReadStates)).(int) + return tutusinternal.CallWithToken(Hash, "getMinimumDeploymentFee", int(contract.ReadStates)).(int) } // HasMethod represents `hasMethod` method of Management native contract. It allows to check // if the "hash" contract has a method named "method" with parameters number equal to "pcount". func HasMethod(hash interop.Hash160, method string, pcount int) bool { - return neogointernal.CallWithToken(Hash, "hasMethod", int(contract.ReadStates), hash, method, pcount).(bool) + return tutusinternal.CallWithToken(Hash, "hasMethod", int(contract.ReadStates), hash, method, pcount).(bool) } // SetMinimumDeploymentFee represents `setMinimumDeploymentFee` method of Management native contract. func SetMinimumDeploymentFee(value int) { - neogointernal.CallWithTokenNoRet(Hash, "setMinimumDeploymentFee", int(contract.States), value) + tutusinternal.CallWithTokenNoRet(Hash, "setMinimumDeploymentFee", int(contract.States), value) } // Update represents `update` method of Management native contract. func Update(script, manifest []byte) { - neogointernal.CallWithTokenNoRet(Hash, "update", + tutusinternal.CallWithTokenNoRet(Hash, "update", int(contract.All), script, manifest) } // UpdateWithData represents `update` method of Management native contract. func UpdateWithData(script, manifest []byte, data any) { - neogointernal.CallWithTokenNoRet(Hash, "update", + tutusinternal.CallWithTokenNoRet(Hash, "update", int(contract.All), script, manifest, data) } @@ -89,5 +89,5 @@ func UpdateWithData(script, manifest []byte, data any) { // if contract with the specified hash is deployed. Note that this method is available starting // from [config.HFEchidna] hardfork. func IsContract(hash interop.Hash160) bool { - return neogointernal.CallWithToken(Hash, "isContract", int(contract.ReadStates), hash).(bool) + return tutusinternal.CallWithToken(Hash, "isContract", int(contract.ReadStates), hash).(bool) } diff --git a/pkg/interop/native/notary/notary.go b/pkg/interop/native/notary/notary.go index 5ac88d4..dec1209 100644 --- a/pkg/interop/native/notary/notary.go +++ b/pkg/interop/native/notary/notary.go @@ -8,7 +8,7 @@ package notary import ( "github.com/tutus-one/tutus-chain/pkg/interop" "github.com/tutus-one/tutus-chain/pkg/interop/contract" - "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" ) // Hash represents Notary contract hash. @@ -16,32 +16,32 @@ const Hash = "\x3b\xec\x35\x31\x11\x9b\xba\xd7\x6d\xd0\x44\x92\x0b\x0d\xe6\xc3\x // LockDepositUntil represents `lockDepositUntil` method of Notary native contract. func LockDepositUntil(addr interop.Hash160, till int) bool { - return neogointernal.CallWithToken(Hash, "lockDepositUntil", int(contract.States), + return tutusinternal.CallWithToken(Hash, "lockDepositUntil", int(contract.States), addr, till).(bool) } // Withdraw represents `withdraw` method of Notary native contract. func Withdraw(from, to interop.Hash160) bool { - return neogointernal.CallWithToken(Hash, "withdraw", int(contract.All), + return tutusinternal.CallWithToken(Hash, "withdraw", int(contract.All), from, to).(bool) } // BalanceOf represents `balanceOf` method of Notary native contract. func BalanceOf(addr interop.Hash160) int { - return neogointernal.CallWithToken(Hash, "balanceOf", int(contract.ReadStates), addr).(int) + return tutusinternal.CallWithToken(Hash, "balanceOf", int(contract.ReadStates), addr).(int) } // ExpirationOf represents `expirationOf` method of Notary native contract. func ExpirationOf(addr interop.Hash160) int { - return neogointernal.CallWithToken(Hash, "expirationOf", int(contract.ReadStates), addr).(int) + return tutusinternal.CallWithToken(Hash, "expirationOf", int(contract.ReadStates), addr).(int) } // GetMaxNotValidBeforeDelta represents `getMaxNotValidBeforeDelta` method of Notary native contract. func GetMaxNotValidBeforeDelta() int { - return neogointernal.CallWithToken(Hash, "getMaxNotValidBeforeDelta", int(contract.ReadStates)).(int) + return tutusinternal.CallWithToken(Hash, "getMaxNotValidBeforeDelta", int(contract.ReadStates)).(int) } // SetMaxNotValidBeforeDelta represents `setMaxNotValidBeforeDelta` method of Notary native contract. func SetMaxNotValidBeforeDelta(value int) { - neogointernal.CallWithTokenNoRet(Hash, "setMaxNotValidBeforeDelta", int(contract.States), value) + tutusinternal.CallWithTokenNoRet(Hash, "setMaxNotValidBeforeDelta", int(contract.States), value) } diff --git a/pkg/interop/native/oracle/oracle.go b/pkg/interop/native/oracle/oracle.go index 7003767..242b616 100644 --- a/pkg/interop/native/oracle/oracle.go +++ b/pkg/interop/native/oracle/oracle.go @@ -7,7 +7,7 @@ package oracle import ( "github.com/tutus-one/tutus-chain/pkg/interop/contract" - "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" ) // These are potential response codes you get in your callback completing @@ -65,18 +65,18 @@ const MinimumResponseGas = 10_000_000 // so it should be enough to pay for reply data as well as // its processing. func Request(url string, filter []byte, cb string, userData any, gasForResponse int) { - neogointernal.CallWithTokenNoRet(Hash, "request", + tutusinternal.CallWithTokenNoRet(Hash, "request", int(contract.States|contract.AllowNotify), url, filter, cb, userData, gasForResponse) } // GetPrice returns the current oracle request price. func GetPrice() int { - return neogointernal.CallWithToken(Hash, "getPrice", int(contract.ReadStates)).(int) + return tutusinternal.CallWithToken(Hash, "getPrice", int(contract.ReadStates)).(int) } // SetPrice allows to set the oracle request price. This method can only be // successfully invoked by the committee. func SetPrice(amount int) { - neogointernal.CallWithTokenNoRet(Hash, "setPrice", int(contract.States), amount) + tutusinternal.CallWithTokenNoRet(Hash, "setPrice", int(contract.States), amount) } diff --git a/pkg/interop/native/policy/policy.go b/pkg/interop/native/policy/policy.go index ce43d44..8428c9d 100644 --- a/pkg/interop/native/policy/policy.go +++ b/pkg/interop/native/policy/policy.go @@ -8,7 +8,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/interop" "github.com/tutus-one/tutus-chain/pkg/interop/contract" "github.com/tutus-one/tutus-chain/pkg/interop/iterator" - "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" ) // Hash represents Policy contract hash. @@ -16,115 +16,115 @@ const Hash = "\x7b\xc6\x81\xc0\xa1\xf7\x1d\x54\x34\x57\xb6\x8b\xba\x8d\x5f\x9f\x // GetFeePerByte represents `getFeePerByte` method of Policy native contract. func GetFeePerByte() int { - return neogointernal.CallWithToken(Hash, "getFeePerByte", int(contract.ReadStates)).(int) + return tutusinternal.CallWithToken(Hash, "getFeePerByte", int(contract.ReadStates)).(int) } // SetFeePerByte represents `setFeePerByte` method of Policy native contract. func SetFeePerByte(value int) { - neogointernal.CallWithTokenNoRet(Hash, "setFeePerByte", int(contract.States), value) + tutusinternal.CallWithTokenNoRet(Hash, "setFeePerByte", int(contract.States), value) } // GetExecFeeFactor represents `getExecFeeFactor` method of Policy native contract. // It returns the execution fee factor in Datoshi units. func GetExecFeeFactor() int { - return neogointernal.CallWithToken(Hash, "getExecFeeFactor", int(contract.ReadStates)).(int) + return tutusinternal.CallWithToken(Hash, "getExecFeeFactor", int(contract.ReadStates)).(int) } // GetExecPicoFeeFactor represents `getExecPicoFeeFactor` method of Policy native contract. // It returns the execution fee factor in picoGAS units. Note that this method is available // starting from [config.HFFaun] hardfork. func GetExecPicoFeeFactor() int { - return neogointernal.CallWithToken(Hash, "getExecPicoFeeFactor", int(contract.ReadStates)).(int) + return tutusinternal.CallWithToken(Hash, "getExecPicoFeeFactor", int(contract.ReadStates)).(int) } // SetExecFeeFactor represents `setExecFeeFactor` method of Policy native contract. // Note that starting from [config.HFFaun] hardfork this method accepts the value // in picoGAS units instead of Datoshi units. func SetExecFeeFactor(value int) { - neogointernal.CallWithTokenNoRet(Hash, "setExecFeeFactor", int(contract.States), value) + tutusinternal.CallWithTokenNoRet(Hash, "setExecFeeFactor", int(contract.States), value) } // GetStoragePrice represents `getStoragePrice` method of Policy native contract. func GetStoragePrice() int { - return neogointernal.CallWithToken(Hash, "getStoragePrice", int(contract.ReadStates)).(int) + return tutusinternal.CallWithToken(Hash, "getStoragePrice", int(contract.ReadStates)).(int) } // SetStoragePrice represents `setStoragePrice` method of Policy native contract. func SetStoragePrice(value int) { - neogointernal.CallWithTokenNoRet(Hash, "setStoragePrice", int(contract.States), value) + tutusinternal.CallWithTokenNoRet(Hash, "setStoragePrice", int(contract.States), value) } // GetAttributeFee represents `getAttributeFee` method of Policy native contract. func GetAttributeFee(t AttributeType) int { - return neogointernal.CallWithToken(Hash, "getAttributeFee", int(contract.ReadStates), t).(int) + return tutusinternal.CallWithToken(Hash, "getAttributeFee", int(contract.ReadStates), t).(int) } // SetAttributeFee represents `setAttributeFee` method of Policy native contract. func SetAttributeFee(t AttributeType, value int) { - neogointernal.CallWithTokenNoRet(Hash, "setAttributeFee", int(contract.States), t, value) + tutusinternal.CallWithTokenNoRet(Hash, "setAttributeFee", int(contract.States), t, value) } // IsBlocked represents `isBlocked` method of Policy native contract. func IsBlocked(addr interop.Hash160) bool { - return neogointernal.CallWithToken(Hash, "isBlocked", int(contract.ReadStates), addr).(bool) + return tutusinternal.CallWithToken(Hash, "isBlocked", int(contract.ReadStates), addr).(bool) } // BlockAccount represents `blockAccount` method of Policy native contract. func BlockAccount(addr interop.Hash160) bool { - return neogointernal.CallWithToken(Hash, "blockAccount", int(contract.States|contract.AllowNotify), addr).(bool) + return tutusinternal.CallWithToken(Hash, "blockAccount", int(contract.States|contract.AllowNotify), addr).(bool) } // UnblockAccount represents `unblockAccount` method of Policy native contract. func UnblockAccount(addr interop.Hash160) bool { - return neogointernal.CallWithToken(Hash, "unblockAccount", int(contract.States), addr).(bool) + return tutusinternal.CallWithToken(Hash, "unblockAccount", int(contract.States), addr).(bool) } // GetMaxValidUntilBlockIncrement represents `getMaxValidUntilBlockIncrement` method of Policy native contract. // Note that this method is available starting from [config.HFEchidna] hardfork. func GetMaxValidUntilBlockIncrement() int { - return neogointernal.CallWithToken(Hash, "getMaxValidUntilBlockIncrement", int(contract.ReadStates)).(int) + return tutusinternal.CallWithToken(Hash, "getMaxValidUntilBlockIncrement", int(contract.ReadStates)).(int) } // SetMaxValidUntilBlockIncrement represents `setMaxValidUntilBlockIncrement` method of Policy native contract. // Note that this method is available starting from [config.HFEchidna] hardfork. func SetMaxValidUntilBlockIncrement(value int) { - neogointernal.CallWithTokenNoRet(Hash, "setMaxValidUntilBlockIncrement", int(contract.States), value) + tutusinternal.CallWithTokenNoRet(Hash, "setMaxValidUntilBlockIncrement", int(contract.States), value) } // GetMillisecondsPerBlock represents `getMillisecondsPerBlock` method of Policy native contract. // Note that this method is available starting from [config.HFEchidna] hardfork. func GetMillisecondsPerBlock() int { - return neogointernal.CallWithToken(Hash, "getMillisecondsPerBlock", int(contract.ReadStates)).(int) + return tutusinternal.CallWithToken(Hash, "getMillisecondsPerBlock", int(contract.ReadStates)).(int) } // SetMillisecondsPerBlock represents `setMaxValidUntilBlockIncrement` method of Policy native contract. // Note that this method is available starting from [config.HFEchidna] hardfork. func SetMillisecondsPerBlock(value int) { - neogointernal.CallWithTokenNoRet(Hash, "setMillisecondsPerBlock", int(contract.States|contract.AllowNotify), value) + tutusinternal.CallWithTokenNoRet(Hash, "setMillisecondsPerBlock", int(contract.States|contract.AllowNotify), value) } // GetBlockedAccounts represents `getBlockedAccounts` method of Policy native contract. // Note that this method is available starting from [config.HFFaun] hardfork. func GetBlockedAccounts() iterator.Iterator { - return neogointernal.CallWithToken(Hash, "getBlockedAccounts", int(contract.ReadStates)).(iterator.Iterator) + return tutusinternal.CallWithToken(Hash, "getBlockedAccounts", int(contract.ReadStates)).(iterator.Iterator) } // SetWhitelistFeeContract represents the `setWhitelistFeeContract` method of Policy native contract. // Note that this method is available starting from [config.HFFaun] hardfork. func SetWhitelistFeeContract(hash interop.Hash160, method string, argCnt int, fixedFee int) { - neogointernal.CallWithTokenNoRet(Hash, "setWhitelistFeeContract", int(contract.States|contract.AllowNotify), + tutusinternal.CallWithTokenNoRet(Hash, "setWhitelistFeeContract", int(contract.States|contract.AllowNotify), hash, method, argCnt, fixedFee) } // RemoveWhitelistFeeContract represents the `removeWhitelistFeeContract` method of Policy native contract. // Note that this method is available starting from [config.HFFaun] hardfork. func RemoveWhitelistFeeContract(hash interop.Hash160, method string, argCnt int) { - neogointernal.CallWithTokenNoRet(Hash, "removeWhitelistFeeContract", int(contract.States|contract.AllowNotify), + tutusinternal.CallWithTokenNoRet(Hash, "removeWhitelistFeeContract", int(contract.States|contract.AllowNotify), hash, method, argCnt) } // GetWhitelistFeeContracts represents the `getWhitelistFeeContracts` method of Policy native contract. // Note that this method is available starting from [config.HFFaun] hardfork. func GetWhitelistFeeContracts() iterator.Iterator { - return neogointernal.CallWithToken(Hash, "getWhitelistFeeContracts", int(contract.ReadStates)).(iterator.Iterator) + return tutusinternal.CallWithToken(Hash, "getWhitelistFeeContracts", int(contract.ReadStates)).(iterator.Iterator) } diff --git a/pkg/interop/native/roles/roles.go b/pkg/interop/native/roles/roles.go index b214e9a..a362c9a 100644 --- a/pkg/interop/native/roles/roles.go +++ b/pkg/interop/native/roles/roles.go @@ -8,7 +8,7 @@ package roles import ( "github.com/tutus-one/tutus-chain/pkg/interop" "github.com/tutus-one/tutus-chain/pkg/interop/contract" - "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" ) // Hash represents RoleManagement contract hash. @@ -27,12 +27,12 @@ const ( // GetDesignatedByRole represents `getDesignatedByRole` method of RoleManagement native contract. func GetDesignatedByRole(r Role, height uint32) []interop.PublicKey { - return neogointernal.CallWithToken(Hash, "getDesignatedByRole", + return tutusinternal.CallWithToken(Hash, "getDesignatedByRole", int(contract.ReadStates), r, height).([]interop.PublicKey) } // DesignateAsRole represents `designateAsRole` method of RoleManagement native contract. func DesignateAsRole(r Role, pubs []interop.PublicKey) { - neogointernal.CallWithTokenNoRet(Hash, "designateAsRole", + tutusinternal.CallWithTokenNoRet(Hash, "designateAsRole", int(contract.States|contract.AllowNotify), r, pubs) } diff --git a/pkg/interop/native/std/std.go b/pkg/interop/native/std/std.go index 47d583b..8773974 100644 --- a/pkg/interop/native/std/std.go +++ b/pkg/interop/native/std/std.go @@ -6,7 +6,7 @@ package std import ( "github.com/tutus-one/tutus-chain/pkg/interop/contract" - "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" ) // Hash represents StdLib contract hash. @@ -17,14 +17,14 @@ const Hash = "\xc0\xef\x39\xce\xe0\xe4\xe9\x25\xc6\xc2\xa0\x6a\x79\xe1\x44\x0d\x // from interop package) and allows to save them in the storage or pass them into Notify // and then Deserialize them on the next run or in the external event receiver. func Serialize(item any) []byte { - return neogointernal.CallWithToken(Hash, "serialize", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "serialize", int(contract.NoneFlag), item).([]byte) } // Deserialize calls `deserialize` method of StdLib native contract and unpacks // a previously serialized value from a byte slice, it's the opposite of Serialize. func Deserialize(b []byte) any { - return neogointernal.CallWithToken(Hash, "deserialize", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "deserialize", int(contract.NoneFlag), b) } @@ -40,7 +40,7 @@ func Deserialize(b []byte) any { // []any -> json array // map[type1]type2 -> json object with string keys marshaled as strings (not base64). func JSONSerialize(item any) []byte { - return neogointernal.CallWithToken(Hash, "jsonSerialize", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "jsonSerialize", int(contract.NoneFlag), item).([]byte) } @@ -54,7 +54,7 @@ func JSONSerialize(item any) []byte { // arrays -> []interface{} // maps -> map[string]interface{} func JSONDeserialize(data []byte) any { - return neogointernal.CallWithToken(Hash, "jsonDeserialize", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "jsonDeserialize", int(contract.NoneFlag), data) } @@ -62,14 +62,14 @@ func JSONDeserialize(data []byte) any { // the given byte slice into a base64 string and returns byte representation of this // string. func Base64Encode(b []byte) string { - return neogointernal.CallWithToken(Hash, "base64Encode", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "base64Encode", int(contract.NoneFlag), b).(string) } // Base64Decode calls `base64Decode` method of StdLib native contract and decodes // the given base64 string represented as a byte slice into byte slice. func Base64Decode(b []byte) []byte { - return neogointernal.CallWithToken(Hash, "base64Decode", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "base64Decode", int(contract.NoneFlag), b).([]byte) } @@ -77,14 +77,14 @@ func Base64Decode(b []byte) []byte { // the given byte slice into a base58 string and returns byte representation of this // string. func Base58Encode(b []byte) string { - return neogointernal.CallWithToken(Hash, "base58Encode", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "base58Encode", int(contract.NoneFlag), b).(string) } // Base58Decode calls `base58Decode` method of StdLib native contract and decodes // the given base58 string represented as a byte slice into a new byte slice. func Base58Decode(b []byte) []byte { - return neogointernal.CallWithToken(Hash, "base58Decode", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "base58Decode", int(contract.NoneFlag), b).([]byte) } @@ -92,42 +92,42 @@ func Base58Decode(b []byte) []byte { // the given byte slice into a base58 string with checksum and returns byte representation of this // string. func Base58CheckEncode(b []byte) string { - return neogointernal.CallWithToken(Hash, "base58CheckEncode", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "base58CheckEncode", int(contract.NoneFlag), b).(string) } // Base58CheckDecode calls `base58CheckDecode` method of StdLib native contract and decodes // thr given base58 string with a checksum represented as a byte slice into a new byte slice. func Base58CheckDecode(b []byte) []byte { - return neogointernal.CallWithToken(Hash, "base58CheckDecode", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "base58CheckDecode", int(contract.NoneFlag), b).([]byte) } // Itoa converts num in the given base to a string. Base should be either 10 or 16. // It uses `itoa` method of StdLib native contract. func Itoa(num int, base int) string { - return neogointernal.CallWithToken(Hash, "itoa", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "itoa", int(contract.NoneFlag), num, base).(string) } // Itoa10 converts num in base 10 to a string. // It uses `itoa` method of StdLib native contract. func Itoa10(num int) string { - return neogointernal.CallWithToken(Hash, "itoa", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "itoa", int(contract.NoneFlag), num).(string) } // Atoi converts a string to a number in the given base. Base should be either 10 or 16. // It uses `atoi` method of StdLib native contract. func Atoi(s string, base int) int { - return neogointernal.CallWithToken(Hash, "atoi", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "atoi", int(contract.NoneFlag), s, base).(int) } // Atoi10 converts a string to a number in base 10. // It uses `atoi` method of StdLib native contract. func Atoi10(s string) int { - return neogointernal.CallWithToken(Hash, "atoi", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "atoi", int(contract.NoneFlag), s).(int) } @@ -135,49 +135,49 @@ func Atoi10(s string) int { // The result will be 0 if a==b, -1 if a < b, and +1 if a > b. // It uses `memoryCompare` method of StdLib native contract. func MemoryCompare(s1, s2 []byte) int { - return neogointernal.CallWithToken(Hash, "memoryCompare", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "memoryCompare", int(contract.NoneFlag), s1, s2).(int) } // MemorySearch returns the index of the first occurrence of the val in the mem. // If not found, -1 is returned. It uses `memorySearch` method of StdLib native contract. func MemorySearch(mem, pattern []byte) int { - return neogointernal.CallWithToken(Hash, "memorySearch", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "memorySearch", int(contract.NoneFlag), mem, pattern).(int) } // MemorySearchIndex returns the index of the first occurrence of the val in the mem starting from the start. // If not found, -1 is returned. It uses `memorySearch` method of StdLib native contract. func MemorySearchIndex(mem, pattern []byte, start int) int { - return neogointernal.CallWithToken(Hash, "memorySearch", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "memorySearch", int(contract.NoneFlag), mem, pattern, start).(int) } // MemorySearchLastIndex returns the index of the last occurrence of the val in the mem ending before start. // If not found, -1 is returned. It uses `memorySearch` method of StdLib native contract. func MemorySearchLastIndex(mem, pattern []byte, start int) int { - return neogointernal.CallWithToken(Hash, "memorySearch", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "memorySearch", int(contract.NoneFlag), mem, pattern, start, true).(int) } // StringSplit splits s by occurrences of the sep. // It uses `stringSplit` method of StdLib native contract. func StringSplit(s, sep string) []string { - return neogointernal.CallWithToken(Hash, "stringSplit", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "stringSplit", int(contract.NoneFlag), s, sep).([]string) } // StringSplitNonEmpty splits s by occurrences of the sep and returns a list of non-empty items. // It uses `stringSplit` method of StdLib native contract. func StringSplitNonEmpty(s, sep string) []string { - return neogointernal.CallWithToken(Hash, "stringSplit", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "stringSplit", int(contract.NoneFlag), s, sep, true).([]string) } // StrLen returns length of the string in Utf- characters. // It uses `strLen` method of StdLib native contract. func StrLen(s string) int { - return neogointernal.CallWithToken(Hash, "strLen", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "strLen", int(contract.NoneFlag), s).(int) } @@ -185,7 +185,7 @@ func StrLen(s string) int { // It uses `hexEncode` method of StdLib native contract. Note that this method is // available starting from [config.HFFaun] hardfork. func HexEncode(b []byte) string { - return neogointernal.CallWithToken(Hash, "hexEncode", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "hexEncode", int(contract.NoneFlag), b).(string) } @@ -193,6 +193,6 @@ func HexEncode(b []byte) string { // It uses `hexDecode` method of StdLib native contract. Note that this method is // available starting from [config.HFFaun] hardfork. func HexDecode(s string) []byte { - return neogointernal.CallWithToken(Hash, "hexDecode", int(contract.NoneFlag), + return tutusinternal.CallWithToken(Hash, "hexDecode", int(contract.NoneFlag), s).([]byte) } diff --git a/pkg/interop/native/tutus/tutus.go b/pkg/interop/native/tutus/tutus.go index 7d039c1..d97f3f6 100644 --- a/pkg/interop/native/tutus/tutus.go +++ b/pkg/interop/native/tutus/tutus.go @@ -10,7 +10,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/interop" "github.com/tutus-one/tutus-chain/pkg/interop/contract" "github.com/tutus-one/tutus-chain/pkg/interop/iterator" - "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" ) // AccountState contains info about a Tutus holder. @@ -26,40 +26,40 @@ const Hash = "\x89\x1d\x6f\x53\x9d\xb3\x6b\x85\xd5\xcf\x6e\x3f\x79\x96\x6b\x8b\x // Symbol represents `symbol` method of Tutus native contract. func Symbol() string { - return neogointernal.CallWithToken(Hash, "symbol", int(contract.NoneFlag)).(string) + return tutusinternal.CallWithToken(Hash, "symbol", int(contract.NoneFlag)).(string) } // Decimals represents `decimals` method of Tutus native contract. func Decimals() int { - return neogointernal.CallWithToken(Hash, "decimals", int(contract.NoneFlag)).(int) + return tutusinternal.CallWithToken(Hash, "decimals", int(contract.NoneFlag)).(int) } // TotalSupply represents `totalSupply` method of Tutus native contract. func TotalSupply() int { - return neogointernal.CallWithToken(Hash, "totalSupply", int(contract.ReadStates)).(int) + return tutusinternal.CallWithToken(Hash, "totalSupply", int(contract.ReadStates)).(int) } // BalanceOf represents `balanceOf` method of Tutus native contract. func BalanceOf(addr interop.Hash160) int { - return neogointernal.CallWithToken(Hash, "balanceOf", int(contract.ReadStates), addr).(int) + return tutusinternal.CallWithToken(Hash, "balanceOf", int(contract.ReadStates), addr).(int) } // Transfer represents `transfer` method of Tutus native contract. func Transfer(from, to interop.Hash160, amount int, data any) bool { - return neogointernal.CallWithToken(Hash, "transfer", + return tutusinternal.CallWithToken(Hash, "transfer", int(contract.All), from, to, amount, data).(bool) } // GetCommittee represents `getCommittee` method of Tutus native contract. func GetCommittee() []interop.PublicKey { - return neogointernal.CallWithToken(Hash, "getCommittee", int(contract.ReadStates)).([]interop.PublicKey) + return tutusinternal.CallWithToken(Hash, "getCommittee", int(contract.ReadStates)).([]interop.PublicKey) } // GetCandidates represents `getCandidates` method of Tutus native contract. It // returns up to 256 candidates. Use GetAllCandidates in case if you need the // whole set of candidates. func GetCandidates() []Candidate { - return neogointernal.CallWithToken(Hash, "getCandidates", int(contract.ReadStates)).([]Candidate) + return tutusinternal.CallWithToken(Hash, "getCandidates", int(contract.ReadStates)).([]Candidate) } // GetAllCandidates represents `getAllCandidates` method of Tutus native contract. @@ -67,67 +67,67 @@ func GetCandidates() []Candidate { // bytes. Each iterator value can be cast to Candidate. Use iterator interop // package to work with the returned Iterator. func GetAllCandidates() iterator.Iterator { - return neogointernal.CallWithToken(Hash, "getAllCandidates", int(contract.ReadStates)).(iterator.Iterator) + return tutusinternal.CallWithToken(Hash, "getAllCandidates", int(contract.ReadStates)).(iterator.Iterator) } // GetCandidateVote represents `getCandidateVote` method of Tutus native contract. // It returns -1 if the candidate hasn't been registered or voted for and the // overall candidate votes otherwise. func GetCandidateVote(pub interop.PublicKey) int { - return neogointernal.CallWithToken(Hash, "getCandidateVote", int(contract.ReadStates), pub).(int) + return tutusinternal.CallWithToken(Hash, "getCandidateVote", int(contract.ReadStates), pub).(int) } // GetNextBlockValidators represents `getNextBlockValidators` method of Tutus native contract. func GetNextBlockValidators() []interop.PublicKey { - return neogointernal.CallWithToken(Hash, "getNextBlockValidators", int(contract.ReadStates)).([]interop.PublicKey) + return tutusinternal.CallWithToken(Hash, "getNextBlockValidators", int(contract.ReadStates)).([]interop.PublicKey) } // GetLubPerBlock represents `getLubPerBlock` method of Tutus native contract. func GetLubPerBlock() int { - return neogointernal.CallWithToken(Hash, "getLubPerBlock", int(contract.ReadStates)).(int) + return tutusinternal.CallWithToken(Hash, "getLubPerBlock", int(contract.ReadStates)).(int) } // SetLubPerBlock represents `setLubPerBlock` method of Tutus native contract. func SetLubPerBlock(amount int) { - neogointernal.CallWithTokenNoRet(Hash, "setLubPerBlock", int(contract.States), amount) + tutusinternal.CallWithTokenNoRet(Hash, "setLubPerBlock", int(contract.States), amount) } // GetRegisterPrice represents `getRegisterPrice` method of Tutus native contract. func GetRegisterPrice() int { - return neogointernal.CallWithToken(Hash, "getRegisterPrice", int(contract.ReadStates)).(int) + return tutusinternal.CallWithToken(Hash, "getRegisterPrice", int(contract.ReadStates)).(int) } // SetRegisterPrice represents `setRegisterPrice` method of Tutus native contract. func SetRegisterPrice(amount int) { - neogointernal.CallWithTokenNoRet(Hash, "setRegisterPrice", int(contract.States), amount) + tutusinternal.CallWithTokenNoRet(Hash, "setRegisterPrice", int(contract.States), amount) } // RegisterCandidate represents `registerCandidate` method of Tutus native contract. func RegisterCandidate(pub interop.PublicKey) bool { - return neogointernal.CallWithToken(Hash, "registerCandidate", int(contract.States|contract.AllowNotify), pub).(bool) + return tutusinternal.CallWithToken(Hash, "registerCandidate", int(contract.States|contract.AllowNotify), pub).(bool) } // UnregisterCandidate represents `unregisterCandidate` method of Tutus native contract. func UnregisterCandidate(pub interop.PublicKey) bool { - return neogointernal.CallWithToken(Hash, "unregisterCandidate", int(contract.States|contract.AllowNotify), pub).(bool) + return tutusinternal.CallWithToken(Hash, "unregisterCandidate", int(contract.States|contract.AllowNotify), pub).(bool) } // Vote represents `vote` method of Tutus native contract. func Vote(addr interop.Hash160, pub interop.PublicKey) bool { - return neogointernal.CallWithToken(Hash, "vote", int(contract.States|contract.AllowNotify), addr, pub).(bool) + return tutusinternal.CallWithToken(Hash, "vote", int(contract.States|contract.AllowNotify), addr, pub).(bool) } // UnclaimedLub represents `unclaimedLub` method of Tutus native contract. func UnclaimedLub(addr interop.Hash160, end int) int { - return neogointernal.CallWithToken(Hash, "unclaimedLub", int(contract.ReadStates), addr, end).(int) + return tutusinternal.CallWithToken(Hash, "unclaimedLub", int(contract.ReadStates), addr, end).(int) } // GetAccountState represents `getAccountState` method of Tutus native contract. func GetAccountState(addr interop.Hash160) *AccountState { - return neogointernal.CallWithToken(Hash, "getAccountState", int(contract.ReadStates), addr).(*AccountState) + return tutusinternal.CallWithToken(Hash, "getAccountState", int(contract.ReadStates), addr).(*AccountState) } // GetCommitteeAddress represents `getCommitteeAddress` method of Tutus native contract. func GetCommitteeAddress() interop.Hash160 { - return neogointernal.CallWithToken(Hash, "getCommitteeAddress", int(contract.ReadStates)).(interop.Hash160) + return tutusinternal.CallWithToken(Hash, "getCommitteeAddress", int(contract.ReadStates)).(interop.Hash160) } diff --git a/pkg/interop/runtime/engine.go b/pkg/interop/runtime/engine.go index 306a200..62270f6 100644 --- a/pkg/interop/runtime/engine.go +++ b/pkg/interop/runtime/engine.go @@ -3,7 +3,7 @@ package runtime import ( "github.com/tutus-one/tutus-chain/pkg/interop" "github.com/tutus-one/tutus-chain/pkg/interop/native/ledger" - "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" ) // GetScriptContainer returns the transaction that initially triggered current @@ -11,7 +11,7 @@ import ( // this execution goes. This function uses // `System.Runtime.GetScriptContainer` syscall. func GetScriptContainer() *ledger.Transaction { - return neogointernal.Syscall0("System.Runtime.GetScriptContainer").(*ledger.Transaction) + return tutusinternal.Syscall0("System.Runtime.GetScriptContainer").(*ledger.Transaction) } // GetExecutingScriptHash returns script hash (160 bit in BE form represented @@ -20,7 +20,7 @@ func GetScriptContainer() *ledger.Transaction { // different contract. This function uses // `System.Runtime.GetExecutingScriptHash` syscall. func GetExecutingScriptHash() interop.Hash160 { - return neogointernal.Syscall0("System.Runtime.GetExecutingScriptHash").(interop.Hash160) + return tutusinternal.Syscall0("System.Runtime.GetExecutingScriptHash").(interop.Hash160) } // GetCallingScriptHash returns script hash (160 bit in BE form represented @@ -29,7 +29,7 @@ func GetExecutingScriptHash() interop.Hash160 { // above the GetExecutingScriptHash in the call stack. It uses // `System.Runtime.GetCallingScriptHash` syscall. func GetCallingScriptHash() interop.Hash160 { - return neogointernal.Syscall0("System.Runtime.GetCallingScriptHash").(interop.Hash160) + return tutusinternal.Syscall0("System.Runtime.GetCallingScriptHash").(interop.Hash160) } // GetEntryScriptHash returns script hash (160 bit in BE form represented @@ -38,5 +38,5 @@ func GetCallingScriptHash() interop.Hash160 { // GetScriptContainer) execution from the start. This function uses // `System.Runtime.GetEntryScriptHash` syscall. func GetEntryScriptHash() interop.Hash160 { - return neogointernal.Syscall0("System.Runtime.GetEntryScriptHash").(interop.Hash160) + return tutusinternal.Syscall0("System.Runtime.GetEntryScriptHash").(interop.Hash160) } diff --git a/pkg/interop/runtime/runtime.go b/pkg/interop/runtime/runtime.go index 6afd457..6905234 100644 --- a/pkg/interop/runtime/runtime.go +++ b/pkg/interop/runtime/runtime.go @@ -8,7 +8,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/interop" "github.com/tutus-one/tutus-chain/pkg/interop/contract" "github.com/tutus-one/tutus-chain/pkg/interop/native/ledger" - "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" ) // Trigger values to compare with GetTrigger result. @@ -21,21 +21,21 @@ const ( // BurnGas burns provided amount of GAS. It uses `System.Runtime.BurnGas` syscall. func BurnGas(gas int) { - neogointernal.Syscall1NoReturn("System.Runtime.BurnGas", gas) + tutusinternal.Syscall1NoReturn("System.Runtime.BurnGas", gas) } // CheckWitness verifies if the given script hash (160-bit BE value in a 20 byte // slice) or key (compressed serialized 33-byte form) is one of the signers of // this invocation. It uses `System.Runtime.CheckWitness` syscall. func CheckWitness(hashOrKey []byte) bool { - return neogointernal.Syscall1("System.Runtime.CheckWitness", hashOrKey).(bool) + return tutusinternal.Syscall1("System.Runtime.CheckWitness", hashOrKey).(bool) } // CurrentSigners returns signers of the currently loaded transaction or nil if // executing script container is not a transaction. It uses // `System.Runtime.CurrentSigners` syscall. func CurrentSigners() []ledger.TransactionSigner { - return neogointernal.Syscall0("System.Runtime.CurrentSigners").([]ledger.TransactionSigner) + return tutusinternal.Syscall0("System.Runtime.CurrentSigners").([]ledger.TransactionSigner) } // LoadScript loads the given bytecode into the VM and executes it with the @@ -50,14 +50,14 @@ func CurrentSigners() []ledger.TransactionSigner { // appropriately handle exceptions if bytecode comes from untrusted source. // This function uses `System.Runtime.LoadScript` syscall. func LoadScript(script []byte, f contract.CallFlag, args ...any) any { - return neogointernal.Syscall3("System.Runtime.LoadScript", script, f, args) + return tutusinternal.Syscall3("System.Runtime.LoadScript", script, f, args) } // Log instructs VM to log the given message. It's mostly used for debugging // purposes as these messages are not saved anywhere normally and usually are // only visible in the VM logs. This function uses `System.Runtime.Log` syscall. func Log(message string) { - neogointernal.Syscall1NoReturn("System.Runtime.Log", message) + tutusinternal.Syscall1NoReturn("System.Runtime.Log", message) } // Notify sends a notification (collecting all arguments in an array) to the @@ -67,7 +67,7 @@ func Log(message string) { // from outside and act upon accordingly. This function uses // `System.Runtime.Notify` syscall. func Notify(name string, args ...any) { - neogointernal.Syscall2NoReturn("System.Runtime.Notify", name, args) + tutusinternal.Syscall2NoReturn("System.Runtime.Notify", name, args) } // GetAddressVersion returns the address version of the current protocol. The @@ -75,13 +75,13 @@ func Notify(name string, args ...any) { // encoding them. The default value for Neo3 is 53 (0x35). This function uses // `System.Runtime.GetAddressVersion` syscall. func GetAddressVersion() int { - return neogointernal.Syscall0("System.Runtime.GetAddressVersion").(int) + return tutusinternal.Syscall0("System.Runtime.GetAddressVersion").(int) } // GetNetwork returns network magic number. This function uses // `System.Runtime.GetNetwork` syscall. func GetNetwork() int { - return neogointernal.Syscall0("System.Runtime.GetNetwork").(int) + return tutusinternal.Syscall0("System.Runtime.GetNetwork").(int) } // GetTime returns the timestamp of the most recent block. Note that when running @@ -90,7 +90,7 @@ func GetNetwork() int { // time of this (currently being processed) block. This function uses // `System.Runtime.GetTime` syscall. func GetTime() int { - return neogointernal.Syscall0("System.Runtime.GetTime").(int) + return tutusinternal.Syscall0("System.Runtime.GetTime").(int) } // GetTrigger returns the smart contract invocation trigger which can be either @@ -100,13 +100,13 @@ func GetTime() int { // not available when running with verification trigger. This function uses // `System.Runtime.GetTrigger` syscall. func GetTrigger() byte { - return neogointernal.Syscall0("System.Runtime.GetTrigger").(byte) + return tutusinternal.Syscall0("System.Runtime.GetTrigger").(byte) } // GasLeft returns the amount of gas available for the current execution. // This function uses `System.Runtime.GasLeft` syscall. func GasLeft() int { - return neogointernal.Syscall0("System.Runtime.GasLeft").(int) + return tutusinternal.Syscall0("System.Runtime.GasLeft").(int) } // GetNotifications returns notifications emitted by contract h. @@ -114,24 +114,24 @@ func GasLeft() int { // [ scripthash of notification's contract , emitted item ]. // This function uses `System.Runtime.GetNotifications` syscall. func GetNotifications(h interop.Hash160) [][]any { - return neogointernal.Syscall1("System.Runtime.GetNotifications", h).([][]any) + return tutusinternal.Syscall1("System.Runtime.GetNotifications", h).([][]any) } // GetInvocationCounter returns how many times current contract was invoked during current tx execution. // This function uses `System.Runtime.GetInvocationCounter` syscall. func GetInvocationCounter() int { - return neogointernal.Syscall0("System.Runtime.GetInvocationCounter").(int) + return tutusinternal.Syscall0("System.Runtime.GetInvocationCounter").(int) } // Platform returns the platform name, which is set to be `NEO`. This function uses // `System.Runtime.Platform` syscall. func Platform() []byte { - return neogointernal.Syscall0("System.Runtime.Platform").([]byte) + return tutusinternal.Syscall0("System.Runtime.Platform").([]byte) } // GetRandom returns pseudo-random number which depends on block nonce and tx hash. // Each invocation will return a different number. This function uses // `System.Runtime.GetRandom` syscall. func GetRandom() int { - return neogointernal.Syscall0("System.Runtime.GetRandom").(int) + return tutusinternal.Syscall0("System.Runtime.GetRandom").(int) } diff --git a/pkg/interop/storage/storage.go b/pkg/interop/storage/storage.go index 27c01b1..f947177 100644 --- a/pkg/interop/storage/storage.go +++ b/pkg/interop/storage/storage.go @@ -8,7 +8,7 @@ package storage import ( "github.com/tutus-one/tutus-chain/pkg/interop/iterator" - "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" ) // Context represents storage context that is mandatory for Put/Get/Delete @@ -52,13 +52,13 @@ const ( // using this new Context. If Context is already read-only this function is a // no-op. It uses `System.Storage.AsReadOnly` syscall. func ConvertContextToReadOnly(ctx Context) Context { - return neogointernal.Syscall1("System.Storage.AsReadOnly", ctx).(Context) + return tutusinternal.Syscall1("System.Storage.AsReadOnly", ctx).(Context) } // GetContext returns current contract's (that invokes this function) storage // context. It uses `System.Storage.GetContext` syscall. func GetContext() Context { - return neogointernal.Syscall0("System.Storage.GetContext").(Context) + return tutusinternal.Syscall0("System.Storage.GetContext").(Context) } // GetReadOnlyContext returns current contract's (that invokes this function) @@ -66,7 +66,7 @@ func GetContext() Context { // functions, but using it for Put and Delete will fail. It uses // `System.Storage.GetReadOnlyContext` syscall. func GetReadOnlyContext() Context { - return neogointernal.Syscall0("System.Storage.GetReadOnlyContext").(Context) + return tutusinternal.Syscall0("System.Storage.GetReadOnlyContext").(Context) } // Put saves given value with given key in the storage using given Context. @@ -75,36 +75,36 @@ func GetReadOnlyContext() Context { // slices of more complex types). To put more complex types there serialize them // first using runtime.Serialize. This function uses `System.Storage.Put` syscall. func Put(ctx Context, key any, value any) { - neogointernal.Syscall3NoReturn("System.Storage.Put", ctx, key, value) + tutusinternal.Syscall3NoReturn("System.Storage.Put", ctx, key, value) } // LocalPut is similar to Put, but does not require context. func LocalPut(key []byte, value []byte) { - neogointernal.Syscall2NoReturn("System.Storage.Local.Put", key, value) + tutusinternal.Syscall2NoReturn("System.Storage.Local.Put", key, value) } // Get retrieves value stored for the given key using given Context. See Put // documentation on possible key and value types. If the value is not present in // the database it returns nil. This function uses `System.Storage.Get` syscall. func Get(ctx Context, key any) any { - return neogointernal.Syscall2("System.Storage.Get", ctx, key) + return tutusinternal.Syscall2("System.Storage.Get", ctx, key) } // LocalGet is similar to Get, but does not require context. func LocalGet(key []byte) any { - return neogointernal.Syscall1("System.Storage.Local.Get", key) + return tutusinternal.Syscall1("System.Storage.Local.Get", key) } // Delete removes key-value pair from storage by the given key using given // Context. See Put documentation on possible key types. This function uses // `System.Storage.Delete` syscall. func Delete(ctx Context, key any) { - neogointernal.Syscall2NoReturn("System.Storage.Delete", ctx, key) + tutusinternal.Syscall2NoReturn("System.Storage.Delete", ctx, key) } // LocalDelete is similar to Delete, but does not require context. func LocalDelete(key []byte) { - neogointernal.Syscall1NoReturn("System.Storage.Local.Delete", key) + tutusinternal.Syscall1NoReturn("System.Storage.Local.Delete", key) } // Find returns an iterator.Iterator over key-value pairs in the given Context @@ -112,10 +112,10 @@ func LocalDelete(key []byte) { // possible key types and iterator package documentation on how to use the // returned value. This function uses `System.Storage.Find` syscall. func Find(ctx Context, key any, options FindFlags) iterator.Iterator { - return neogointernal.Syscall3("System.Storage.Find", ctx, key, options).(iterator.Iterator) + return tutusinternal.Syscall3("System.Storage.Find", ctx, key, options).(iterator.Iterator) } // LocalFind is similar to Find, but does not require context. func LocalFind(key []byte, options FindFlags) iterator.Iterator { - return neogointernal.Syscall2("System.Storage.Local.Find", key, options).(iterator.Iterator) + return tutusinternal.Syscall2("System.Storage.Local.Find", key, options).(iterator.Iterator) } diff --git a/pkg/interop/neogointernal/call.go b/pkg/interop/tutusinternal/call.go similarity index 95% rename from pkg/interop/neogointernal/call.go rename to pkg/interop/tutusinternal/call.go index f32e65f..7e4b97f 100644 --- a/pkg/interop/neogointernal/call.go +++ b/pkg/interop/tutusinternal/call.go @@ -1,4 +1,4 @@ -package neogointernal +package tutusinternal // CallWithToken performs contract call using CALLT instruction. It only works // for static script hashes and methods, requiring additional metadata compared to diff --git a/pkg/interop/neogointernal/doc.go b/pkg/interop/tutusinternal/doc.go similarity index 85% rename from pkg/interop/neogointernal/doc.go rename to pkg/interop/tutusinternal/doc.go index 11e1b50..c8ffa95 100644 --- a/pkg/interop/neogointernal/doc.go +++ b/pkg/interop/tutusinternal/doc.go @@ -2,4 +2,4 @@ Package neogointernal contains definitions of compiler intrinsics. It's not intended to be used directly by smart contracts. */ -package neogointernal +package tutusinternal diff --git a/pkg/interop/neogointernal/opcode.go b/pkg/interop/tutusinternal/opcode.go similarity index 96% rename from pkg/interop/neogointernal/opcode.go rename to pkg/interop/tutusinternal/opcode.go index 0b39138..aa36e5b 100644 --- a/pkg/interop/neogointernal/opcode.go +++ b/pkg/interop/tutusinternal/opcode.go @@ -1,4 +1,4 @@ -package neogointernal +package tutusinternal // Opcode0NoReturn emits opcode without arguments. func Opcode0NoReturn(op string) { diff --git a/pkg/interop/neogointernal/syscall.go b/pkg/interop/tutusinternal/syscall.go similarity index 98% rename from pkg/interop/neogointernal/syscall.go rename to pkg/interop/tutusinternal/syscall.go index d106d2c..3d417d4 100644 --- a/pkg/interop/neogointernal/syscall.go +++ b/pkg/interop/tutusinternal/syscall.go @@ -1,4 +1,4 @@ -package neogointernal +package tutusinternal // Syscall0 performs syscall with 0 arguments. func Syscall0(name string) any { diff --git a/pkg/interop/types.go b/pkg/interop/types.go index 9cf3834..7aacbbb 100644 --- a/pkg/interop/types.go +++ b/pkg/interop/types.go @@ -1,6 +1,6 @@ package interop -import "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" +import "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" const ( // Hash160Len is the length of proper Hash160 in bytes, use it to @@ -78,5 +78,5 @@ func (a Signature) Equals(b any) bool { // converted to ByteString. func bytesEquals(a any, b any) bool { return (a == nil && b == nil) || - (a != nil && b != nil && neogointernal.Opcode2("EQUAL", a.(string), b.(string)).(bool)) + (a != nil && b != nil && tutusinternal.Opcode2("EQUAL", a.(string), b.(string)).(bool)) } diff --git a/pkg/interop/util/util.go b/pkg/interop/util/util.go index 288292d..4f8f928 100644 --- a/pkg/interop/util/util.go +++ b/pkg/interop/util/util.go @@ -4,43 +4,43 @@ Package util contains some special useful functions that are provided by compile package util import ( - "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal" + "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal" ) // Abort terminates current execution, unlike exception throwing with panic() it // can't be recovered from. func Abort() { - neogointernal.Opcode0NoReturn("ABORT") + tutusinternal.Opcode0NoReturn("ABORT") } // AbortMsg terminates current execution with the specified message. Unlike // exception throwing with panic() it can't be recovered from. func AbortMsg(msg string) { - neogointernal.Opcode1NoReturn("ABORTMSG", msg) + tutusinternal.Opcode1NoReturn("ABORTMSG", msg) } // Assert terminates current execution if the condition specified is false. Unlike // exception throwing with panic() it can't be recovered from. func Assert(ok bool) { - neogointernal.Opcode1NoReturn("ASSERT", ok) + tutusinternal.Opcode1NoReturn("ASSERT", ok) } // AssertMsg terminates current execution with the specified message if the // condition specified is false. Unlike exception throwing with panic() it can't // be recovered from. func AssertMsg(ok bool, msg string) { - neogointernal.Opcode2NoReturn("ASSERTMSG", ok, msg) + tutusinternal.Opcode2NoReturn("ASSERTMSG", ok, msg) } // Equals compares a with b and will return true when a and b are equal. It's // implemented as an EQUAL VM opcode, so the rules of comparison are those // of EQUAL. func Equals(a, b any) bool { - return neogointernal.Opcode2("EQUAL", a, b).(bool) + return tutusinternal.Opcode2("EQUAL", a, b).(bool) } // Remove removes element with index i from slice. // This is done in place and slice must have type other than `[]byte`. func Remove(slice any, i int) { - neogointernal.Opcode2NoReturn("REMOVE", slice, i) + tutusinternal.Opcode2NoReturn("REMOVE", slice, i) } diff --git a/pkg/rpcclient/actor/actor.go b/pkg/rpcclient/actor/actor.go index ad59df4..d5e5fe9 100644 --- a/pkg/rpcclient/actor/actor.go +++ b/pkg/rpcclient/actor/actor.go @@ -17,7 +17,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/config/netmode" "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient/invoker" "github.com/tutus-one/tutus-chain/pkg/rpcclient/waiter" "github.com/tutus-one/tutus-chain/pkg/util" diff --git a/pkg/rpcclient/actor/actor_test.go b/pkg/rpcclient/actor/actor_test.go index 887171d..553ea81 100644 --- a/pkg/rpcclient/actor/actor_test.go +++ b/pkg/rpcclient/actor/actor_test.go @@ -10,7 +10,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/config/netmode" "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/smartcontract/trigger" "github.com/tutus-one/tutus-chain/pkg/util" diff --git a/pkg/rpcclient/actor/doc_test.go b/pkg/rpcclient/actor/doc_test.go index 28a8e56..4274aab 100644 --- a/pkg/rpcclient/actor/doc_test.go +++ b/pkg/rpcclient/actor/doc_test.go @@ -6,10 +6,10 @@ import ( "os" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient" "github.com/tutus-one/tutus-chain/pkg/rpcclient/actor" - "github.com/tutus-one/tutus-chain/pkg/rpcclient/neo" + "github.com/tutus-one/tutus-chain/pkg/rpcclient/tutus" "github.com/tutus-one/tutus-chain/pkg/rpcclient/policy" sccontext "github.com/tutus-one/tutus-chain/pkg/smartcontract/context" "github.com/tutus-one/tutus-chain/pkg/util" @@ -64,7 +64,7 @@ func ExampleActor() { // Actor can be used for higher-level wrappers as well, if we want to interact with // NEO then [neo] package can accept our Actor and allow to easily use NEO methods. - neoContract := neo.New(a) + neoContract := tutus.New(a) balance, _ := neoContract.BalanceOf(a.Sender()) _ = balance diff --git a/pkg/rpcclient/actor/maker.go b/pkg/rpcclient/actor/maker.go index 20ed899..8aeb42a 100644 --- a/pkg/rpcclient/actor/maker.go +++ b/pkg/rpcclient/actor/maker.go @@ -5,7 +5,7 @@ import ( "fmt" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/vmstate" ) diff --git a/pkg/rpcclient/actor/maker_test.go b/pkg/rpcclient/actor/maker_test.go index 104527d..3e004e1 100644 --- a/pkg/rpcclient/actor/maker_test.go +++ b/pkg/rpcclient/actor/maker_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/stretchr/testify/require" ) diff --git a/pkg/rpcclient/client.go b/pkg/rpcclient/client.go index 92d0124..5a86c37 100644 --- a/pkg/rpcclient/client.go +++ b/pkg/rpcclient/client.go @@ -14,7 +14,7 @@ import ( "time" "github.com/tutus-one/tutus-chain/pkg/config/netmode" - "github.com/tutus-one/tutus-chain/pkg/neorpc" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc" "github.com/tutus-one/tutus-chain/pkg/rpcclient/invoker" "github.com/tutus-one/tutus-chain/pkg/util" ) @@ -35,7 +35,7 @@ type Client struct { // ctx. ctxCancel func() opts Options - requestF func(*neorpc.Request) (*neorpc.Response, error) + requestF func(*tutusrpc.Request) (*tutusrpc.Response, error) // reader is an Invoker that has no signers and uses current state, // it's used to implement various getters. It'll be removed eventually, @@ -175,8 +175,8 @@ func (c *Client) performRequest(method string, p []any, v any) error { if p == nil { p = []any{} // neo-project/neo-modules#742 } - var r = neorpc.Request{ - JSONRPC: neorpc.JSONRPCVersion, + var r = tutusrpc.Request{ + JSONRPC: tutusrpc.JSONRPCVersion, Method: method, Params: p, ID: c.getNextRequestID(), @@ -194,10 +194,10 @@ func (c *Client) performRequest(method string, p []any, v any) error { return json.Unmarshal(raw.Result, v) } -func (c *Client) makeHTTPRequest(r *neorpc.Request) (*neorpc.Response, error) { +func (c *Client) makeHTTPRequest(r *tutusrpc.Request) (*tutusrpc.Response, error) { var ( buf = new(bytes.Buffer) - raw = new(neorpc.Response) + raw = new(tutusrpc.Response) ) if err := json.NewEncoder(buf).Encode(r); err != nil { diff --git a/pkg/rpcclient/gas/gas_test.go b/pkg/rpcclient/gas/gas_test.go index bec297c..2e05225 100644 --- a/pkg/rpcclient/gas/gas_test.go +++ b/pkg/rpcclient/gas/gas_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/stretchr/testify/require" ) diff --git a/pkg/rpcclient/invoker/doc_test.go b/pkg/rpcclient/invoker/doc_test.go index 118be6c..3d4e61f 100644 --- a/pkg/rpcclient/invoker/doc_test.go +++ b/pkg/rpcclient/invoker/doc_test.go @@ -8,7 +8,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/encoding/address" "github.com/tutus-one/tutus-chain/pkg/rpcclient" "github.com/tutus-one/tutus-chain/pkg/rpcclient/invoker" - "github.com/tutus-one/tutus-chain/pkg/rpcclient/neo" + "github.com/tutus-one/tutus-chain/pkg/rpcclient/tutus" "github.com/tutus-one/tutus-chain/pkg/rpcclient/unwrap" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/vmstate" @@ -22,16 +22,16 @@ func ExampleInvoker() { inv := invoker.New(c, nil) // Get the NEO token supply (notice that unwrap is used to get the result). - supply, _ := unwrap.BigInt(inv.Call(neo.Hash, "totalSupply")) + supply, _ := unwrap.BigInt(inv.Call(tutus.Hash, "totalSupply")) _ = supply acc, _ := address.StringToUint160("NVTiAjNgagDkTr5HTzDmQP9kPwPHN5BgVq") // Get the NEO balance for account NVTiAjNgagDkTr5HTzDmQP9kPwPHN5BgVq. - balance, _ := unwrap.BigInt(inv.Call(neo.Hash, "balanceOf", acc)) + balance, _ := unwrap.BigInt(inv.Call(tutus.Hash, "balanceOf", acc)) _ = balance // Test-invoke transfer call. - res, _ := inv.Call(neo.Hash, "transfer", acc, util.Uint160{1, 2, 3}, 1, nil) + res, _ := inv.Call(tutus.Hash, "transfer", acc, util.Uint160{1, 2, 3}, 1, nil) if res.State == vmstate.Halt.String() { panic("NEO is broken!") // inv has no signers and transfer requires a witness to be performed. } else { // nolint:revive // superfluous-else: if block ends with call to panic function, so drop this else and outdent its block (revive) @@ -42,7 +42,7 @@ func ExampleInvoker() { inv = invoker.NewHistoricAtHeight(1000000, c, nil) // It's the same call as above, but the data is for a state at block 1000000. - balance, _ = unwrap.BigInt(inv.Call(neo.Hash, "balanceOf", acc)) + balance, _ = unwrap.BigInt(inv.Call(tutus.Hash, "balanceOf", acc)) _ = balance // This invoker has a signer for NVTiAjNgagDkTr5HTzDmQP9kPwPHN5BgVq account with @@ -52,7 +52,7 @@ func ExampleInvoker() { inv = invoker.New(c, []transaction.Signer{{Account: acc, Scopes: transaction.CalledByEntry}}) // Now test invocation should be fine (if NVTiAjNgagDkTr5HTzDmQP9kPwPHN5BgVq has 1 NEO of course). - res, _ = inv.Call(neo.Hash, "transfer", acc, util.Uint160{1, 2, 3}, 1, nil) + res, _ = inv.Call(tutus.Hash, "transfer", acc, util.Uint160{1, 2, 3}, 1, nil) if res.State == vmstate.Halt.String() { // transfer actually returns a value, so check it too. ok, _ := unwrap.Bool(res, nil) diff --git a/pkg/rpcclient/invoker/invoker.go b/pkg/rpcclient/invoker/invoker.go index d575ac2..3fbf554 100644 --- a/pkg/rpcclient/invoker/invoker.go +++ b/pkg/rpcclient/invoker/invoker.go @@ -15,7 +15,7 @@ import ( "github.com/google/uuid" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" diff --git a/pkg/rpcclient/invoker/invoker_test.go b/pkg/rpcclient/invoker/invoker_test.go index 92cf176..934e925 100644 --- a/pkg/rpcclient/invoker/invoker_test.go +++ b/pkg/rpcclient/invoker/invoker_test.go @@ -6,7 +6,7 @@ import ( "github.com/google/uuid" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" diff --git a/pkg/rpcclient/local.go b/pkg/rpcclient/local.go index 0f6e47b..69d3911 100644 --- a/pkg/rpcclient/local.go +++ b/pkg/rpcclient/local.go @@ -3,13 +3,13 @@ package rpcclient import ( "context" - "github.com/tutus-one/tutus-chain/pkg/neorpc" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc" ) // InternalHook is a function signature that is required to create a local client // (see NewInternal). It performs registration of local client's event channel // and returns a request handler function. -type InternalHook func(context.Context, chan<- neorpc.Notification) func(*neorpc.Request) (*neorpc.Response, error) +type InternalHook func(context.Context, chan<- tutusrpc.Notification) func(*tutusrpc.Request) (*tutusrpc.Response, error) // Internal is an experimental "local" client that does not connect to RPC via // network. It's made for deeply integrated applications like NeoFS that have @@ -18,7 +18,7 @@ type InternalHook func(context.Context, chan<- neorpc.Notification) func(*neorpc type Internal struct { WSClient - events chan neorpc.Notification + events chan tutusrpc.Notification } // NewInternal creates an instance of internal client. It accepts a method @@ -34,7 +34,7 @@ func NewInternal(ctx context.Context, register InternalHook) (*Internal, error) subscriptions: make(map[string]notificationReceiver), receivers: make(map[any][]string), }, - events: make(chan neorpc.Notification), + events: make(chan tutusrpc.Notification), } err := initClient(ctx, &c.Client, "localhost:0", Options{}) diff --git a/pkg/rpcclient/local_test.go b/pkg/rpcclient/local_test.go index 6667873..59b081b 100644 --- a/pkg/rpcclient/local_test.go +++ b/pkg/rpcclient/local_test.go @@ -6,13 +6,13 @@ import ( "github.com/tutus-one/tutus-chain/internal/testcli" "github.com/tutus-one/tutus-chain/pkg/config" - "github.com/tutus-one/tutus-chain/pkg/neorpc" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc" "github.com/tutus-one/tutus-chain/pkg/rpcclient" "github.com/stretchr/testify/require" ) func TestInternalClientClose(t *testing.T) { - icl, err := rpcclient.NewInternal(context.TODO(), func(ctx context.Context, ch chan<- neorpc.Notification) func(*neorpc.Request) (*neorpc.Response, error) { + icl, err := rpcclient.NewInternal(context.TODO(), func(ctx context.Context, ch chan<- tutusrpc.Notification) func(*tutusrpc.Request) (*tutusrpc.Response, error) { return nil }) require.NoError(t, err) diff --git a/pkg/rpcclient/management/management.go b/pkg/rpcclient/management/management.go index 1f8937c..45a493a 100644 --- a/pkg/rpcclient/management/management.go +++ b/pkg/rpcclient/management/management.go @@ -17,7 +17,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/native/nativehashes" "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient/unwrap" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/smartcontract/manifest" diff --git a/pkg/rpcclient/management/management_test.go b/pkg/rpcclient/management/management_test.go index dc30e6a..3eb221a 100644 --- a/pkg/rpcclient/management/management_test.go +++ b/pkg/rpcclient/management/management_test.go @@ -8,7 +8,7 @@ import ( "github.com/google/uuid" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/smartcontract/manifest" "github.com/tutus-one/tutus-chain/pkg/smartcontract/nef" "github.com/tutus-one/tutus-chain/pkg/util" diff --git a/pkg/rpcclient/nep11/base.go b/pkg/rpcclient/nep11/base.go index 7add829..a79df7b 100644 --- a/pkg/rpcclient/nep11/base.go +++ b/pkg/rpcclient/nep11/base.go @@ -17,7 +17,7 @@ import ( "github.com/google/uuid" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient/neptoken" "github.com/tutus-one/tutus-chain/pkg/rpcclient/unwrap" "github.com/tutus-one/tutus-chain/pkg/smartcontract" diff --git a/pkg/rpcclient/nep11/base_test.go b/pkg/rpcclient/nep11/base_test.go index 8944740..661700f 100644 --- a/pkg/rpcclient/nep11/base_test.go +++ b/pkg/rpcclient/nep11/base_test.go @@ -7,7 +7,7 @@ import ( "github.com/google/uuid" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" "github.com/stretchr/testify/require" diff --git a/pkg/rpcclient/nep11/divisible.go b/pkg/rpcclient/nep11/divisible.go index f0a00a0..c0ac634 100644 --- a/pkg/rpcclient/nep11/divisible.go +++ b/pkg/rpcclient/nep11/divisible.go @@ -6,7 +6,7 @@ import ( "github.com/google/uuid" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient/unwrap" "github.com/tutus-one/tutus-chain/pkg/util" ) diff --git a/pkg/rpcclient/nep11/divisible_test.go b/pkg/rpcclient/nep11/divisible_test.go index 06399aa..0372633 100644 --- a/pkg/rpcclient/nep11/divisible_test.go +++ b/pkg/rpcclient/nep11/divisible_test.go @@ -7,7 +7,7 @@ import ( "github.com/google/uuid" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" "github.com/stretchr/testify/require" diff --git a/pkg/rpcclient/nep11/nondivisible_test.go b/pkg/rpcclient/nep11/nondivisible_test.go index d2ef189..e190805 100644 --- a/pkg/rpcclient/nep11/nondivisible_test.go +++ b/pkg/rpcclient/nep11/nondivisible_test.go @@ -4,7 +4,7 @@ import ( "errors" "testing" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" "github.com/stretchr/testify/require" diff --git a/pkg/rpcclient/nep17/nep17.go b/pkg/rpcclient/nep17/nep17.go index 946a3ec..340306e 100644 --- a/pkg/rpcclient/nep17/nep17.go +++ b/pkg/rpcclient/nep17/nep17.go @@ -12,7 +12,7 @@ import ( "math/big" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient/neptoken" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/util" diff --git a/pkg/rpcclient/nep17/nep17_test.go b/pkg/rpcclient/nep17/nep17_test.go index 734a742..2781c66 100644 --- a/pkg/rpcclient/nep17/nep17_test.go +++ b/pkg/rpcclient/nep17/nep17_test.go @@ -6,7 +6,7 @@ import ( "testing" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" "github.com/stretchr/testify/require" diff --git a/pkg/rpcclient/nep24/royalty.go b/pkg/rpcclient/nep24/royalty.go index ea05087..303ac31 100644 --- a/pkg/rpcclient/nep24/royalty.go +++ b/pkg/rpcclient/nep24/royalty.go @@ -13,7 +13,7 @@ import ( "fmt" "math/big" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient/neptoken" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" diff --git a/pkg/rpcclient/nep24/royalty_test.go b/pkg/rpcclient/nep24/royalty_test.go index 44c8701..791cfb0 100644 --- a/pkg/rpcclient/nep24/royalty_test.go +++ b/pkg/rpcclient/nep24/royalty_test.go @@ -7,7 +7,7 @@ import ( "testing" "github.com/tutus-one/tutus-chain/pkg/core/state" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" "github.com/stretchr/testify/require" diff --git a/pkg/rpcclient/neptoken/base.go b/pkg/rpcclient/neptoken/base.go index 6bda4e8..ee02b15 100644 --- a/pkg/rpcclient/neptoken/base.go +++ b/pkg/rpcclient/neptoken/base.go @@ -8,7 +8,7 @@ package neptoken import ( "math/big" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient/unwrap" "github.com/tutus-one/tutus-chain/pkg/util" ) diff --git a/pkg/rpcclient/neptoken/base_test.go b/pkg/rpcclient/neptoken/base_test.go index 7bd4786..c1962de 100644 --- a/pkg/rpcclient/neptoken/base_test.go +++ b/pkg/rpcclient/neptoken/base_test.go @@ -5,7 +5,7 @@ import ( "math/big" "testing" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" "github.com/stretchr/testify/require" diff --git a/pkg/rpcclient/neptoken/info_test.go b/pkg/rpcclient/neptoken/info_test.go index be32404..b78fd41 100644 --- a/pkg/rpcclient/neptoken/info_test.go +++ b/pkg/rpcclient/neptoken/info_test.go @@ -8,7 +8,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/block" "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/smartcontract/manifest" "github.com/tutus-one/tutus-chain/pkg/smartcontract/trigger" diff --git a/pkg/rpcclient/nns/contract.go b/pkg/rpcclient/nns/contract.go index 3489cb2..a744dbd 100644 --- a/pkg/rpcclient/nns/contract.go +++ b/pkg/rpcclient/nns/contract.go @@ -10,7 +10,7 @@ import ( "unicode/utf8" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient/nep11" "github.com/tutus-one/tutus-chain/pkg/rpcclient/unwrap" "github.com/tutus-one/tutus-chain/pkg/smartcontract" diff --git a/pkg/rpcclient/nns/contract_test.go b/pkg/rpcclient/nns/contract_test.go index d3211aa..12c952c 100644 --- a/pkg/rpcclient/nns/contract_test.go +++ b/pkg/rpcclient/nns/contract_test.go @@ -7,7 +7,7 @@ import ( "github.com/google/uuid" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" diff --git a/pkg/rpcclient/nns/iterators.go b/pkg/rpcclient/nns/iterators.go index d5f05c9..70defa4 100644 --- a/pkg/rpcclient/nns/iterators.go +++ b/pkg/rpcclient/nns/iterators.go @@ -5,7 +5,7 @@ import ( "fmt" "github.com/google/uuid" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" ) diff --git a/pkg/rpcclient/notary/actor.go b/pkg/rpcclient/notary/actor.go index a743ad0..5d6b101 100644 --- a/pkg/rpcclient/notary/actor.go +++ b/pkg/rpcclient/notary/actor.go @@ -8,8 +8,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" - "github.com/tutus-one/tutus-chain/pkg/neorpc" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/network/payload" "github.com/tutus-one/tutus-chain/pkg/rpcclient/actor" "github.com/tutus-one/tutus-chain/pkg/rpcclient/invoker" @@ -328,12 +328,12 @@ func (a *Actor) SendRequestExactly(mainTx *transaction.Transaction, fbTx *transa // the resulting application execution result or actor.ErrTxNotAccepted if both transactions // failed to persist. Wait can be used if underlying Actor supports transaction awaiting, // see actor.Actor and actor.Waiter documentation for details. Wait may be used as a wrapper -// for Notarize, SendRequest or SendRequestExactly. Notice that [neorpc.ErrAlreadyExists] +// for Notarize, SendRequest or SendRequestExactly. Notice that [tutusrpc.ErrAlreadyExists] // answer is not treated as an error by this routine because they mean that some // of the transactions given might be already accepted or soon going to be accepted. These // transactions can be waited for in a usual way potentially with positive result. func (a *Actor) Wait(mainHash, fbHash util.Uint256, vub uint32, err error) (*state.AppExecResult, error) { - if err != nil && !errors.Is(err, neorpc.ErrAlreadyExists) { + if err != nil && !errors.Is(err, tutusrpc.ErrAlreadyExists) { return nil, err } return a.WaitAny(context.TODO(), vub, mainHash, fbHash) diff --git a/pkg/rpcclient/notary/actor_test.go b/pkg/rpcclient/notary/actor_test.go index faa87fd..f319041 100644 --- a/pkg/rpcclient/notary/actor_test.go +++ b/pkg/rpcclient/notary/actor_test.go @@ -11,7 +11,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" "github.com/tutus-one/tutus-chain/pkg/encoding/address" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/network/payload" "github.com/tutus-one/tutus-chain/pkg/rpcclient/actor" "github.com/tutus-one/tutus-chain/pkg/rpcclient/invoker" diff --git a/pkg/rpcclient/notary/contract.go b/pkg/rpcclient/notary/contract.go index 6d4ce1b..6b1a15d 100644 --- a/pkg/rpcclient/notary/contract.go +++ b/pkg/rpcclient/notary/contract.go @@ -15,7 +15,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/native/nativehashes" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient/unwrap" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/util" diff --git a/pkg/rpcclient/notary/contract_test.go b/pkg/rpcclient/notary/contract_test.go index 19015a4..34aebe6 100644 --- a/pkg/rpcclient/notary/contract_test.go +++ b/pkg/rpcclient/notary/contract_test.go @@ -9,7 +9,7 @@ import ( "github.com/tutus-one/tutus-chain/internal/testserdes" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" "github.com/stretchr/testify/require" diff --git a/pkg/rpcclient/oracle/oracle.go b/pkg/rpcclient/oracle/oracle.go index 07b1063..21eb7de 100644 --- a/pkg/rpcclient/oracle/oracle.go +++ b/pkg/rpcclient/oracle/oracle.go @@ -11,7 +11,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/native/nativehashes" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient/unwrap" "github.com/tutus-one/tutus-chain/pkg/util" ) diff --git a/pkg/rpcclient/oracle/oracle_test.go b/pkg/rpcclient/oracle/oracle_test.go index ed8444a..67ea1b5 100644 --- a/pkg/rpcclient/oracle/oracle_test.go +++ b/pkg/rpcclient/oracle/oracle_test.go @@ -6,7 +6,7 @@ import ( "testing" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" "github.com/stretchr/testify/require" diff --git a/pkg/rpcclient/policy/policy.go b/pkg/rpcclient/policy/policy.go index b07479d..0b40b8c 100644 --- a/pkg/rpcclient/policy/policy.go +++ b/pkg/rpcclient/policy/policy.go @@ -14,7 +14,7 @@ import ( "github.com/google/uuid" "github.com/tutus-one/tutus-chain/pkg/core/native/nativehashes" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient/unwrap" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/util" diff --git a/pkg/rpcclient/policy/policy_test.go b/pkg/rpcclient/policy/policy_test.go index cf264a1..57e6c30 100644 --- a/pkg/rpcclient/policy/policy_test.go +++ b/pkg/rpcclient/policy/policy_test.go @@ -6,7 +6,7 @@ import ( "github.com/google/uuid" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" "github.com/stretchr/testify/require" diff --git a/pkg/rpcclient/rolemgmt/roles.go b/pkg/rpcclient/rolemgmt/roles.go index 8221ce0..27f558d 100644 --- a/pkg/rpcclient/rolemgmt/roles.go +++ b/pkg/rpcclient/rolemgmt/roles.go @@ -15,7 +15,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/native/noderoles" "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient/unwrap" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" diff --git a/pkg/rpcclient/rolemgmt/roles_test.go b/pkg/rpcclient/rolemgmt/roles_test.go index 24ad58e..57bfa49 100644 --- a/pkg/rpcclient/rolemgmt/roles_test.go +++ b/pkg/rpcclient/rolemgmt/roles_test.go @@ -9,7 +9,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/native/noderoles" "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" "github.com/stretchr/testify/require" diff --git a/pkg/rpcclient/rpc.go b/pkg/rpcclient/rpc.go index fd65f9a..fcb6d89 100644 --- a/pkg/rpcclient/rpc.go +++ b/pkg/rpcclient/rpc.go @@ -15,8 +15,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/crypto/keys" "github.com/tutus-one/tutus-chain/pkg/encoding/fixedn" "github.com/tutus-one/tutus-chain/pkg/io" - "github.com/tutus-one/tutus-chain/pkg/neorpc" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/network/payload" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/smartcontract/trigger" @@ -869,9 +869,9 @@ func (c *Client) invokeSomething(method string, p []any, signers []transaction.S if len(witnesses) != len(signers) { return nil, fmt.Errorf("number of witnesses should match number of signers, got %d vs %d", len(witnesses), len(signers)) } - signersWithWitnesses := make([]neorpc.SignerWithWitness, len(signers)) + signersWithWitnesses := make([]tutusrpc.SignerWithWitness, len(signers)) for i := range signersWithWitnesses { - signersWithWitnesses[i] = neorpc.SignerWithWitness{ + signersWithWitnesses[i] = tutusrpc.SignerWithWitness{ Signer: signers[i], Witness: witnesses[i], } @@ -1054,7 +1054,7 @@ func (c *Client) GetRawNotaryPool() (*result.RawNotaryPool, error) { } // GetBlockNotifications returns notifications from a block organized by trigger type. -func (c *Client) GetBlockNotifications(blockHash util.Uint256, filter *neorpc.NotificationFilter) (*result.BlockNotifications, error) { +func (c *Client) GetBlockNotifications(blockHash util.Uint256, filter *tutusrpc.NotificationFilter) (*result.BlockNotifications, error) { var ( resp = &result.BlockNotifications{} params = []any{blockHash.StringLE()} diff --git a/pkg/rpcclient/rpc_test.go b/pkg/rpcclient/rpc_test.go index 4e33a3e..ac13a79 100644 --- a/pkg/rpcclient/rpc_test.go +++ b/pkg/rpcclient/rpc_test.go @@ -26,7 +26,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/encoding/bigint" "github.com/tutus-one/tutus-chain/pkg/encoding/fixedn" "github.com/tutus-one/tutus-chain/pkg/io" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/services/rpcsrv/params" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/smartcontract/manifest" diff --git a/pkg/rpcclient/neo/doc_test.go b/pkg/rpcclient/tutus/doc_test.go similarity index 92% rename from pkg/rpcclient/neo/doc_test.go rename to pkg/rpcclient/tutus/doc_test.go index a94369c..2297323 100644 --- a/pkg/rpcclient/neo/doc_test.go +++ b/pkg/rpcclient/tutus/doc_test.go @@ -1,4 +1,4 @@ -package neo_test +package tutus_test import ( "cmp" @@ -7,11 +7,11 @@ import ( "slices" "github.com/tutus-one/tutus-chain/pkg/encoding/address" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient" "github.com/tutus-one/tutus-chain/pkg/rpcclient/actor" "github.com/tutus-one/tutus-chain/pkg/rpcclient/invoker" - "github.com/tutus-one/tutus-chain/pkg/rpcclient/neo" + "github.com/tutus-one/tutus-chain/pkg/rpcclient/tutus" "github.com/tutus-one/tutus-chain/pkg/wallet" ) @@ -23,7 +23,7 @@ func ExampleContractReader() { inv := invoker.New(c, nil) // Create a reader interface. - neoToken := neo.NewReader(inv) + neoToken := tutus.NewReader(inv) // Account hash we're interested in. accHash, _ := address.StringToUint160("NdypBhqkz2CMMnwxBgvoC9X2XjKF5axgKo") @@ -62,7 +62,7 @@ func ExampleContract() { a, _ := actor.NewSimple(c, w.Accounts[0]) // Create a complete contract representation. - neoToken := neo.New(a) + neoToken := tutus.New(a) tgtAcc, _ := address.StringToUint160("NdypBhqkz2CMMnwxBgvoC9X2XjKF5axgKo") diff --git a/pkg/rpcclient/neo/neo.go b/pkg/rpcclient/tutus/tutus.go similarity index 99% rename from pkg/rpcclient/neo/neo.go rename to pkg/rpcclient/tutus/tutus.go index 7a71cc3..6cb331f 100644 --- a/pkg/rpcclient/neo/neo.go +++ b/pkg/rpcclient/tutus/tutus.go @@ -4,7 +4,7 @@ Package neo provides an RPC-based wrapper for the NEOToken contract. Safe methods are encapsulated into ContractReader structure while Contract provides various methods to perform state-changing calls. */ -package neo +package tutus import ( "crypto/elliptic" @@ -16,7 +16,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient/nep17" "github.com/tutus-one/tutus-chain/pkg/rpcclient/unwrap" "github.com/tutus-one/tutus-chain/pkg/smartcontract" diff --git a/pkg/rpcclient/neo/neo_test.go b/pkg/rpcclient/tutus/tutus_test.go similarity index 99% rename from pkg/rpcclient/neo/neo_test.go rename to pkg/rpcclient/tutus/tutus_test.go index 0e1534f..92ba0cc 100644 --- a/pkg/rpcclient/neo/neo_test.go +++ b/pkg/rpcclient/tutus/tutus_test.go @@ -1,4 +1,4 @@ -package neo +package tutus import ( "errors" @@ -9,7 +9,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" "github.com/stretchr/testify/require" diff --git a/pkg/rpcclient/unwrap/unwrap.go b/pkg/rpcclient/unwrap/unwrap.go index fb1df49..683f30b 100644 --- a/pkg/rpcclient/unwrap/unwrap.go +++ b/pkg/rpcclient/unwrap/unwrap.go @@ -19,7 +19,7 @@ import ( "github.com/google/uuid" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" "github.com/tutus-one/tutus-chain/pkg/vm/vmstate" diff --git a/pkg/rpcclient/unwrap/unwrap_test.go b/pkg/rpcclient/unwrap/unwrap_test.go index dacd556..469b6ae 100644 --- a/pkg/rpcclient/unwrap/unwrap_test.go +++ b/pkg/rpcclient/unwrap/unwrap_test.go @@ -10,7 +10,7 @@ import ( "github.com/google/uuid" "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" "github.com/stretchr/testify/require" diff --git a/pkg/rpcclient/waiter/waiter.go b/pkg/rpcclient/waiter/waiter.go index 5b5045f..1899e77 100644 --- a/pkg/rpcclient/waiter/waiter.go +++ b/pkg/rpcclient/waiter/waiter.go @@ -8,8 +8,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/block" "github.com/tutus-one/tutus-chain/pkg/core/state" - "github.com/tutus-one/tutus-chain/pkg/neorpc" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/smartcontract/trigger" "github.com/tutus-one/tutus-chain/pkg/util" ) @@ -72,8 +72,8 @@ type ( RPCEventBased interface { RPCPollingBased - ReceiveHeadersOfAddedBlocks(flt *neorpc.BlockFilter, rcvr chan<- *block.Header) (string, error) - ReceiveExecutions(flt *neorpc.ExecutionFilter, rcvr chan<- *state.AppExecResult) (string, error) + ReceiveHeadersOfAddedBlocks(flt *tutusrpc.BlockFilter, rcvr chan<- *block.Header) (string, error) + ReceiveExecutions(flt *tutusrpc.ExecutionFilter, rcvr chan<- *state.AppExecResult) (string, error) Unsubscribe(id string) error } ) @@ -188,7 +188,7 @@ func newCustomPollingBased(waiter RPCPollingBased, v *result.Version, config Pol // Wait implements Waiter interface. func (w *PollingBased) Wait(ctx context.Context, h util.Uint256, vub uint32, err error) (*state.AppExecResult, error) { - if err != nil && !errors.Is(err, neorpc.ErrAlreadyExists) { + if err != nil && !errors.Is(err, tutusrpc.ErrAlreadyExists) { return nil, err } return w.WaitAny(ctx, vub, h) @@ -261,7 +261,7 @@ func NewCustomEventBased(waiter RPCEventBased, config Config) (*EventBased, erro // Wait implements Waiter interface. func (w *EventBased) Wait(ctx context.Context, h util.Uint256, vub uint32, err error) (res *state.AppExecResult, waitErr error) { - if err != nil && !errors.Is(err, neorpc.ErrAlreadyExists) { + if err != nil && !errors.Is(err, tutusrpc.ErrAlreadyExists) { return nil, err } return w.WaitAny(ctx, vub, h) @@ -280,7 +280,7 @@ func (w *EventBased) WaitAny(ctx context.Context, vub uint32, hashes ...util.Uin // Execution event preceded the block event, thus wait until the VUB-th block to be sure. since := vub - blocksID, err := w.ws.ReceiveHeadersOfAddedBlocks(&neorpc.BlockFilter{Since: &since}, hRcvr) + blocksID, err := w.ws.ReceiveHeadersOfAddedBlocks(&tutusrpc.BlockFilter{Since: &since}, hRcvr) if err != nil { wsWaitErr = fmt.Errorf("failed to subscribe for new headers: %w", err) } else { @@ -298,7 +298,7 @@ func (w *EventBased) WaitAny(ctx context.Context, vub uint32, hashes ...util.Uin if wsWaitErr == nil { trig := trigger.Application for _, h := range hashes { - txsID, err := w.ws.ReceiveExecutions(&neorpc.ExecutionFilter{Container: &h}, aerRcvr) + txsID, err := w.ws.ReceiveExecutions(&tutusrpc.ExecutionFilter{Container: &h}, aerRcvr) if err != nil { wsWaitErr = fmt.Errorf("failed to subscribe for execution results: %w", err) break diff --git a/pkg/rpcclient/waiter/waiter_test.go b/pkg/rpcclient/waiter/waiter_test.go index b259e5b..dfefb8f 100644 --- a/pkg/rpcclient/waiter/waiter_test.go +++ b/pkg/rpcclient/waiter/waiter_test.go @@ -12,8 +12,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/block" "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/rpcclient" "github.com/tutus-one/tutus-chain/pkg/rpcclient/actor" "github.com/tutus-one/tutus-chain/pkg/rpcclient/waiter" @@ -90,19 +90,19 @@ type AwaitableRPCClient struct { var _ = waiter.RPCEventBased(&AwaitableRPCClient{}) -func (c *AwaitableRPCClient) ReceiveBlocks(flt *neorpc.BlockFilter, rcvr chan<- *block.Block) (string, error) { +func (c *AwaitableRPCClient) ReceiveBlocks(flt *tutusrpc.BlockFilter, rcvr chan<- *block.Block) (string, error) { c.chLock.Lock() defer c.chLock.Unlock() c.subBlockCh = rcvr return "1", nil } -func (c *AwaitableRPCClient) ReceiveExecutions(flt *neorpc.ExecutionFilter, rcvr chan<- *state.AppExecResult) (string, error) { +func (c *AwaitableRPCClient) ReceiveExecutions(flt *tutusrpc.ExecutionFilter, rcvr chan<- *state.AppExecResult) (string, error) { c.chLock.Lock() defer c.chLock.Unlock() c.subTxCh = rcvr return "2", nil } -func (c *AwaitableRPCClient) ReceiveHeadersOfAddedBlocks(flt *neorpc.BlockFilter, rcvr chan<- *block.Header) (string, error) { +func (c *AwaitableRPCClient) ReceiveHeadersOfAddedBlocks(flt *tutusrpc.BlockFilter, rcvr chan<- *block.Header) (string, error) { c.chLock.Lock() defer c.chLock.Unlock() c.subHeaderCh = rcvr diff --git a/pkg/rpcclient/wsclient.go b/pkg/rpcclient/wsclient.go index c955883..ca7e4e6 100644 --- a/pkg/rpcclient/wsclient.go +++ b/pkg/rpcclient/wsclient.go @@ -14,9 +14,9 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/block" "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" - "github.com/tutus-one/tutus-chain/pkg/neorpc/rpcevent" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/rpcevent" ) // WSClient is a websocket-enabled RPC client that can be used with appropriate @@ -64,7 +64,7 @@ type WSClient struct { wsOpts WSOptions readerDone chan struct{} writerDone chan struct{} - requests chan *neorpc.Request + requests chan *tutusrpc.Request shutdown chan struct{} closeCalled atomic.Bool @@ -83,7 +83,7 @@ type WSClient struct { subscriptionsOrderLock sync.Mutex respLock sync.RWMutex - respChannels map[uint64]chan *neorpc.Response + respChannels map[uint64]chan *tutusrpc.Response } // WSOptions defines options for the web-socket RPC client. It contains a @@ -120,17 +120,17 @@ type notificationReceiver interface { // blockReceiver stores information about block events subscriber. type blockReceiver struct { - filter *neorpc.BlockFilter + filter *tutusrpc.BlockFilter ch chan<- *block.Block } -// EventID implements neorpc.Comparator interface. -func (r *blockReceiver) EventID() neorpc.EventID { - return neorpc.BlockEventID +// EventID implements tutusrpc.Comparator interface. +func (r *blockReceiver) EventID() tutusrpc.EventID { + return tutusrpc.BlockEventID } -// Filter implements neorpc.Comparator interface. -func (r *blockReceiver) Filter() neorpc.SubscriptionFilter { +// Filter implements tutusrpc.Comparator interface. +func (r *blockReceiver) Filter() tutusrpc.SubscriptionFilter { if r.filter == nil { return nil } @@ -167,17 +167,17 @@ func (r *blockReceiver) Close() { // headerOfAddedBlockReceiver stores information about header of added block events subscriber. type headerOfAddedBlockReceiver struct { - filter *neorpc.BlockFilter + filter *tutusrpc.BlockFilter ch chan<- *block.Header } -// EventID implements neorpc.Comparator interface. -func (r *headerOfAddedBlockReceiver) EventID() neorpc.EventID { - return neorpc.HeaderOfAddedBlockEventID +// EventID implements tutusrpc.Comparator interface. +func (r *headerOfAddedBlockReceiver) EventID() tutusrpc.EventID { + return tutusrpc.HeaderOfAddedBlockEventID } -// Filter implements neorpc.Comparator interface. -func (r *headerOfAddedBlockReceiver) Filter() neorpc.SubscriptionFilter { +// Filter implements tutusrpc.Comparator interface. +func (r *headerOfAddedBlockReceiver) Filter() tutusrpc.SubscriptionFilter { if r.filter == nil { return nil } @@ -213,17 +213,17 @@ func (r *headerOfAddedBlockReceiver) Close() { // txReceiver stores information about transaction events subscriber. type txReceiver struct { - filter *neorpc.TxFilter + filter *tutusrpc.TxFilter ch chan<- *transaction.Transaction } -// EventID implements neorpc.Comparator interface. -func (r *txReceiver) EventID() neorpc.EventID { - return neorpc.TransactionEventID +// EventID implements tutusrpc.Comparator interface. +func (r *txReceiver) EventID() tutusrpc.EventID { + return tutusrpc.TransactionEventID } -// Filter implements neorpc.Comparator interface. -func (r *txReceiver) Filter() neorpc.SubscriptionFilter { +// Filter implements tutusrpc.Comparator interface. +func (r *txReceiver) Filter() tutusrpc.SubscriptionFilter { if r.filter == nil { return nil } @@ -260,17 +260,17 @@ func (r *txReceiver) Close() { // executionNotificationReceiver stores information about execution notifications subscriber. type executionNotificationReceiver struct { - filter *neorpc.NotificationFilter + filter *tutusrpc.NotificationFilter ch chan<- *state.ContainedNotificationEvent } -// EventID implements neorpc.Comparator interface. -func (r *executionNotificationReceiver) EventID() neorpc.EventID { - return neorpc.NotificationEventID +// EventID implements tutusrpc.Comparator interface. +func (r *executionNotificationReceiver) EventID() tutusrpc.EventID { + return tutusrpc.NotificationEventID } -// Filter implements neorpc.Comparator interface. -func (r *executionNotificationReceiver) Filter() neorpc.SubscriptionFilter { +// Filter implements tutusrpc.Comparator interface. +func (r *executionNotificationReceiver) Filter() tutusrpc.SubscriptionFilter { if r.filter == nil { return nil } @@ -307,17 +307,17 @@ func (r *executionNotificationReceiver) Close() { // executionReceiver stores information about application execution results subscriber. type executionReceiver struct { - filter *neorpc.ExecutionFilter + filter *tutusrpc.ExecutionFilter ch chan<- *state.AppExecResult } -// EventID implements neorpc.Comparator interface. -func (r *executionReceiver) EventID() neorpc.EventID { - return neorpc.ExecutionEventID +// EventID implements tutusrpc.Comparator interface. +func (r *executionReceiver) EventID() tutusrpc.EventID { + return tutusrpc.ExecutionEventID } -// Filter implements neorpc.Comparator interface. -func (r *executionReceiver) Filter() neorpc.SubscriptionFilter { +// Filter implements tutusrpc.Comparator interface. +func (r *executionReceiver) Filter() tutusrpc.SubscriptionFilter { if r.filter == nil { return nil } @@ -354,17 +354,17 @@ func (r *executionReceiver) Close() { // notaryRequestReceiver stores information about notary requests subscriber. type notaryRequestReceiver struct { - filter *neorpc.NotaryRequestFilter + filter *tutusrpc.NotaryRequestFilter ch chan<- *result.NotaryRequestEvent } -// EventID implements neorpc.Comparator interface. -func (r *notaryRequestReceiver) EventID() neorpc.EventID { - return neorpc.NotaryRequestEventID +// EventID implements tutusrpc.Comparator interface. +func (r *notaryRequestReceiver) EventID() tutusrpc.EventID { + return tutusrpc.NotaryRequestEventID } -// Filter implements neorpc.Comparator interface. -func (r *notaryRequestReceiver) Filter() neorpc.SubscriptionFilter { +// Filter implements tutusrpc.Comparator interface. +func (r *notaryRequestReceiver) Filter() tutusrpc.SubscriptionFilter { if r.filter == nil { return nil } @@ -401,17 +401,17 @@ func (r *notaryRequestReceiver) Close() { // mempoolEventReceiver stores information about mempool events subscriber. type mempoolEventReceiver struct { - filter *neorpc.MempoolEventFilter + filter *tutusrpc.MempoolEventFilter ch chan<- *result.MempoolEvent } -// EventID implements neorpc.Comparator interface. -func (r *mempoolEventReceiver) EventID() neorpc.EventID { - return neorpc.MempoolEventID +// EventID implements tutusrpc.Comparator interface. +func (r *mempoolEventReceiver) EventID() tutusrpc.EventID { + return tutusrpc.MempoolEventID } -// Filter implements neorpc.Comparator interface. -func (r *mempoolEventReceiver) Filter() neorpc.SubscriptionFilter { +// Filter implements tutusrpc.Comparator interface. +func (r *mempoolEventReceiver) Filter() tutusrpc.SubscriptionFilter { if r.filter == nil { return nil } @@ -450,12 +450,12 @@ func (r *mempoolEventReceiver) Close() { // Value can be one of *block.Block, *state.AppExecResult, *state.ContainedNotificationEvent // *transaction.Transaction or *subscriptions.NotaryRequestEvent based on Type. type Notification struct { - Type neorpc.EventID + Type tutusrpc.EventID Value any } // EventID implements Container interface and returns notification ID. -func (n Notification) EventID() neorpc.EventID { +func (n Notification) EventID() tutusrpc.EventID { return n.Type } @@ -468,7 +468,7 @@ func (n Notification) EventPayload() any { // requestResponse is a combined type for request and response since we can get // any of them here. type requestResponse struct { - neorpc.Response + tutusrpc.Response Method string `json:"method"` RawParams []json.RawMessage `json:"params,omitzero"` } @@ -513,7 +513,7 @@ func NewWS(ctx context.Context, endpoint string, opts WSOptions) (*WSClient, err } if err != nil { if resp != nil && resp.Body != nil { - var srvErr neorpc.HeaderAndError + var srvErr tutusrpc.HeaderAndError dec := json.NewDecoder(resp.Body) decErr := dec.Decode(&srvErr) @@ -531,8 +531,8 @@ func NewWS(ctx context.Context, endpoint string, opts WSOptions) (*WSClient, err shutdown: make(chan struct{}), readerDone: make(chan struct{}), writerDone: make(chan struct{}), - respChannels: make(map[uint64]chan *neorpc.Response), - requests: make(chan *neorpc.Request), + respChannels: make(map[uint64]chan *tutusrpc.Response), + requests: make(chan *tutusrpc.Request), subscriptions: make(map[string]notificationReceiver), receivers: make(map[any][]string), } @@ -590,20 +590,20 @@ readloop: break readloop } if rr.ID == nil && rr.Method != "" { - event, err := neorpc.GetEventIDFromString(rr.Method) + event, err := tutusrpc.GetEventIDFromString(rr.Method) if err != nil { // Bad event received. connCloseErr = fmt.Errorf("failed to perse event ID from string %s: %w", rr.Method, err) break readloop } - if event != neorpc.MissedEventID && len(rr.RawParams) != 1 { + if event != tutusrpc.MissedEventID && len(rr.RawParams) != 1 { // Bad event received. connCloseErr = fmt.Errorf("bad event received: %s / %d", event, len(rr.RawParams)) break readloop } ntf := Notification{Type: event} switch event { - case neorpc.BlockEventID: + case tutusrpc.BlockEventID: sr, err := c.stateRootInHeader() if err != nil { // Client is not initialized. @@ -611,15 +611,15 @@ readloop: break readloop } ntf.Value = block.New(sr) - case neorpc.TransactionEventID: + case tutusrpc.TransactionEventID: ntf.Value = &transaction.Transaction{} - case neorpc.NotificationEventID: + case tutusrpc.NotificationEventID: ntf.Value = new(state.ContainedNotificationEvent) - case neorpc.ExecutionEventID: + case tutusrpc.ExecutionEventID: ntf.Value = new(state.AppExecResult) - case neorpc.NotaryRequestEventID: + case tutusrpc.NotaryRequestEventID: ntf.Value = new(result.NotaryRequestEvent) - case neorpc.HeaderOfAddedBlockEventID: + case tutusrpc.HeaderOfAddedBlockEventID: sr, err := c.stateRootInHeader() if err != nil { // Client is not initialized. @@ -627,16 +627,16 @@ readloop: break readloop } ntf.Value = &block.New(sr).Header - case neorpc.MempoolEventID: + case tutusrpc.MempoolEventID: ntf.Value = new(result.MempoolEvent) - case neorpc.MissedEventID: + case tutusrpc.MissedEventID: // No value. default: // Bad event received. connCloseErr = fmt.Errorf("unknown event received: %d", event) break readloop } - if event != neorpc.MissedEventID { + if event != tutusrpc.MissedEventID { err = json.Unmarshal(rr.RawParams[0], ntf.Value) if err != nil { // Bad event received. @@ -741,7 +741,7 @@ writeloop: } func (c *WSClient) notifySubscribers(ntf Notification) { - if ntf.Type == neorpc.MissedEventID { + if ntf.Type == tutusrpc.MissedEventID { c.subscriptionsLock.Lock() for rcvr, ids := range c.receivers { c.subscriptions[ids[0]].Close() @@ -775,7 +775,7 @@ func (c *WSClient) unregisterRespChannel(id uint64) { } } -func (c *WSClient) getResponseChannel(id uint64) chan *neorpc.Response { +func (c *WSClient) getResponseChannel(id uint64) chan *tutusrpc.Response { c.respLock.RLock() defer c.respLock.RUnlock() return c.respChannels[id] @@ -794,8 +794,8 @@ func (c *WSClient) closeErrOrConnLost() error { return err } -func (c *WSClient) makeWsRequest(r *neorpc.Request) (*neorpc.Response, error) { - ch := make(chan *neorpc.Response) +func (c *WSClient) makeWsRequest(r *tutusrpc.Request) (*tutusrpc.Response, error) { + ch := make(chan *tutusrpc.Response) c.respLock.Lock() select { case <-c.readerDone: @@ -854,7 +854,7 @@ func (c *WSClient) performSubscription(params []any, rcvr notificationReceiver) // ReceiveBlocks registers provided channel as a receiver for the new block events. // Events can be filtered by the given BlockFilter, nil value doesn't add any filter. // See WSClient comments for generic Receive* behaviour details. -func (c *WSClient) ReceiveBlocks(flt *neorpc.BlockFilter, rcvr chan<- *block.Block) (string, error) { +func (c *WSClient) ReceiveBlocks(flt *tutusrpc.BlockFilter, rcvr chan<- *block.Block) (string, error) { if rcvr == nil { return "", ErrNilNotificationReceiver } @@ -874,10 +874,10 @@ func (c *WSClient) ReceiveBlocks(flt *neorpc.BlockFilter, rcvr chan<- *block.Blo } // ReceiveHeadersOfAddedBlocks registers provided channel as a receiver for new -// block's header events. Events can be filtered by the given [neorpc.BlockFilter], +// block's header events. Events can be filtered by the given [tutusrpc.BlockFilter], // nil value doesn't add any filter. See WSClient comments for generic // Receive* behaviour details. -func (c *WSClient) ReceiveHeadersOfAddedBlocks(flt *neorpc.BlockFilter, rcvr chan<- *block.Header) (string, error) { +func (c *WSClient) ReceiveHeadersOfAddedBlocks(flt *tutusrpc.BlockFilter, rcvr chan<- *block.Header) (string, error) { if rcvr == nil { return "", ErrNilNotificationReceiver } @@ -899,7 +899,7 @@ func (c *WSClient) ReceiveHeadersOfAddedBlocks(flt *neorpc.BlockFilter, rcvr cha // ReceiveTransactions registers provided channel as a receiver for new transaction // events. Events can be filtered by the given TxFilter, nil value doesn't add any // filter. See WSClient comments for generic Receive* behaviour details. -func (c *WSClient) ReceiveTransactions(flt *neorpc.TxFilter, rcvr chan<- *transaction.Transaction) (string, error) { +func (c *WSClient) ReceiveTransactions(flt *tutusrpc.TxFilter, rcvr chan<- *transaction.Transaction) (string, error) { if rcvr == nil { return "", ErrNilNotificationReceiver } @@ -918,7 +918,7 @@ func (c *WSClient) ReceiveTransactions(flt *neorpc.TxFilter, rcvr chan<- *transa // ReceiveExecutionNotifications registers provided channel as a receiver for execution // events. Events can be filtered by the given NotificationFilter, nil value doesn't add // any filter. See WSClient comments for generic Receive* behaviour details. -func (c *WSClient) ReceiveExecutionNotifications(flt *neorpc.NotificationFilter, rcvr chan<- *state.ContainedNotificationEvent) (string, error) { +func (c *WSClient) ReceiveExecutionNotifications(flt *tutusrpc.NotificationFilter, rcvr chan<- *state.ContainedNotificationEvent) (string, error) { if rcvr == nil { return "", ErrNilNotificationReceiver } @@ -938,7 +938,7 @@ func (c *WSClient) ReceiveExecutionNotifications(flt *neorpc.NotificationFilter, // application execution result events generated during transaction execution. // Events can be filtered by the given ExecutionFilter, nil value doesn't add any filter. // See WSClient comments for generic Receive* behaviour details. -func (c *WSClient) ReceiveExecutions(flt *neorpc.ExecutionFilter, rcvr chan<- *state.AppExecResult) (string, error) { +func (c *WSClient) ReceiveExecutions(flt *tutusrpc.ExecutionFilter, rcvr chan<- *state.AppExecResult) (string, error) { if rcvr == nil { return "", ErrNilNotificationReceiver } @@ -961,7 +961,7 @@ func (c *WSClient) ReceiveExecutions(flt *neorpc.ExecutionFilter, rcvr chan<- *s // [mempoolevent.Type] and denotes whether notary request was added to or removed from // the notary request pool. nil value doesn't add any filter. See WSClient comments // for generic Receive* behaviour details. -func (c *WSClient) ReceiveNotaryRequests(flt *neorpc.NotaryRequestFilter, rcvr chan<- *result.NotaryRequestEvent) (string, error) { +func (c *WSClient) ReceiveNotaryRequests(flt *tutusrpc.NotaryRequestFilter, rcvr chan<- *result.NotaryRequestEvent) (string, error) { if rcvr == nil { return "", ErrNilNotificationReceiver } @@ -983,7 +983,7 @@ func (c *WSClient) ReceiveNotaryRequests(flt *neorpc.NotaryRequestFilter, rcvr c // corresponds to one of the transaction’s signers, and type corresponds to the // [mempoolevent.Type] and denotes whether the transaction was added to or removed // from the mempool. See WSClient comments for generic Receive* behaviour details. -func (c *WSClient) ReceiveMempoolEvents(flt *neorpc.MempoolEventFilter, rcvr chan<- *result.MempoolEvent) (string, error) { +func (c *WSClient) ReceiveMempoolEvents(flt *tutusrpc.MempoolEventFilter, rcvr chan<- *result.MempoolEvent) (string, error) { if rcvr == nil { return "", ErrNilNotificationReceiver } diff --git a/pkg/rpcclient/wsclient_test.go b/pkg/rpcclient/wsclient_test.go index f8b1b0b..6200d1a 100644 --- a/pkg/rpcclient/wsclient_test.go +++ b/pkg/rpcclient/wsclient_test.go @@ -20,8 +20,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/mempoolevent" "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/network/payload" "github.com/tutus-one/tutus-chain/pkg/services/rpcsrv/params" "github.com/tutus-one/tutus-chain/pkg/smartcontract" @@ -214,18 +214,18 @@ func TestWSClientEvents(t *testing.T) { wsc.subscriptions["4"] = &executionReceiver{ch: aerCh1} wsc.receivers[chan<- *state.AppExecResult(aerCh1)] = []string{"4"} - wsc.subscriptions["5"] = &executionReceiver{filter: &neorpc.ExecutionFilter{State: &halt}, ch: aerCh2} + wsc.subscriptions["5"] = &executionReceiver{filter: &tutusrpc.ExecutionFilter{State: &halt}, ch: aerCh2} wsc.receivers[chan<- *state.AppExecResult(aerCh2)] = []string{"5"} - wsc.subscriptions["6"] = &executionReceiver{filter: &neorpc.ExecutionFilter{State: &fault}, ch: aerCh3} + wsc.subscriptions["6"] = &executionReceiver{filter: &tutusrpc.ExecutionFilter{State: &fault}, ch: aerCh3} wsc.receivers[chan<- *state.AppExecResult(aerCh3)] = []string{"6"} added := mempoolevent.TransactionAdded removed := mempoolevent.TransactionRemoved wsc.subscriptions["7"] = &mempoolEventReceiver{ch: memAllCh} wsc.receivers[chan<- *result.MempoolEvent(memAllCh)] = []string{"7"} - wsc.subscriptions["8"] = &mempoolEventReceiver{filter: &neorpc.MempoolEventFilter{Type: &added}, ch: memAddedCh} + wsc.subscriptions["8"] = &mempoolEventReceiver{filter: &tutusrpc.MempoolEventFilter{Type: &added}, ch: memAddedCh} wsc.receivers[chan<- *result.MempoolEvent(memAddedCh)] = []string{"8"} - wsc.subscriptions["9"] = &mempoolEventReceiver{filter: &neorpc.MempoolEventFilter{Type: &removed}, ch: memRemovedCh} + wsc.subscriptions["9"] = &mempoolEventReceiver{filter: &tutusrpc.MempoolEventFilter{Type: &removed}, ch: memRemovedCh} wsc.receivers[chan<- *result.MempoolEvent(memRemovedCh)] = []string{"9"} // MissedEvent must close the channels above. @@ -418,8 +418,8 @@ func TestWSExecutionVMStateCheck(t *testing.T) { wsc.getNextRequestID = getTestRequestID require.NoError(t, wsc.Init()) filter := "NONE" - _, err = wsc.ReceiveExecutions(&neorpc.ExecutionFilter{State: &filter}, make(chan *state.AppExecResult)) - require.ErrorIs(t, err, neorpc.ErrInvalidSubscriptionFilter) + _, err = wsc.ReceiveExecutions(&tutusrpc.ExecutionFilter{State: &filter}, make(chan *state.AppExecResult)) + require.ErrorIs(t, err, tutusrpc.ErrInvalidSubscriptionFilter) wsc.Close() } @@ -431,8 +431,8 @@ func TestWSExecutionNotificationNameCheck(t *testing.T) { wsc.getNextRequestID = getTestRequestID require.NoError(t, wsc.Init()) filter := "notification_from_execution_with_long_name" - _, err = wsc.ReceiveExecutionNotifications(&neorpc.NotificationFilter{Name: &filter}, make(chan *state.ContainedNotificationEvent)) - require.ErrorIs(t, err, neorpc.ErrInvalidSubscriptionFilter) + _, err = wsc.ReceiveExecutionNotifications(&tutusrpc.NotificationFilter{Name: &filter}, make(chan *state.ContainedNotificationEvent)) + require.ErrorIs(t, err, tutusrpc.ErrInvalidSubscriptionFilter) wsc.Close() } @@ -445,12 +445,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { {"block header primary", func(t *testing.T, wsc *WSClient) { primary := byte(3) - _, err := wsc.ReceiveHeadersOfAddedBlocks(&neorpc.BlockFilter{Primary: &primary}, make(chan *block.Header)) + _, err := wsc.ReceiveHeadersOfAddedBlocks(&tutusrpc.BlockFilter{Primary: &primary}, make(chan *block.Header)) require.NoError(t, err) }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.BlockFilter) + filt := new(tutusrpc.BlockFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, byte(3), *filt.Primary) require.Equal(t, (*uint32)(nil), filt.Since) @@ -460,12 +460,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { {"header since", func(t *testing.T, wsc *WSClient) { var since uint32 = 3 - _, err := wsc.ReceiveHeadersOfAddedBlocks(&neorpc.BlockFilter{Since: &since}, make(chan *block.Header)) + _, err := wsc.ReceiveHeadersOfAddedBlocks(&tutusrpc.BlockFilter{Since: &since}, make(chan *block.Header)) require.NoError(t, err) }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.BlockFilter) + filt := new(tutusrpc.BlockFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, (*byte)(nil), filt.Primary) require.Equal(t, uint32(3), *filt.Since) @@ -475,12 +475,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { {"header till", func(t *testing.T, wsc *WSClient) { var till uint32 = 3 - _, err := wsc.ReceiveHeadersOfAddedBlocks(&neorpc.BlockFilter{Till: &till}, make(chan *block.Header)) + _, err := wsc.ReceiveHeadersOfAddedBlocks(&tutusrpc.BlockFilter{Till: &till}, make(chan *block.Header)) require.NoError(t, err) }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.BlockFilter) + filt := new(tutusrpc.BlockFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, (*byte)(nil), filt.Primary) require.Equal(t, (*uint32)(nil), filt.Since) @@ -494,7 +494,7 @@ func TestWSFilteredSubscriptions(t *testing.T) { primary = byte(2) till uint32 = 5 ) - _, err := wsc.ReceiveHeadersOfAddedBlocks(&neorpc.BlockFilter{ + _, err := wsc.ReceiveHeadersOfAddedBlocks(&tutusrpc.BlockFilter{ Primary: &primary, Since: &since, Till: &till, @@ -503,7 +503,7 @@ func TestWSFilteredSubscriptions(t *testing.T) { }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.BlockFilter) + filt := new(tutusrpc.BlockFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, byte(2), *filt.Primary) require.Equal(t, uint32(3), *filt.Since) @@ -513,12 +513,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { {"blocks primary", func(t *testing.T, wsc *WSClient) { primary := byte(3) - _, err := wsc.ReceiveBlocks(&neorpc.BlockFilter{Primary: &primary}, make(chan *block.Block)) + _, err := wsc.ReceiveBlocks(&tutusrpc.BlockFilter{Primary: &primary}, make(chan *block.Block)) require.NoError(t, err) }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.BlockFilter) + filt := new(tutusrpc.BlockFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, byte(3), *filt.Primary) require.Equal(t, (*uint32)(nil), filt.Since) @@ -528,12 +528,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { {"blocks since", func(t *testing.T, wsc *WSClient) { var since uint32 = 3 - _, err := wsc.ReceiveBlocks(&neorpc.BlockFilter{Since: &since}, make(chan *block.Block)) + _, err := wsc.ReceiveBlocks(&tutusrpc.BlockFilter{Since: &since}, make(chan *block.Block)) require.NoError(t, err) }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.BlockFilter) + filt := new(tutusrpc.BlockFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, (*byte)(nil), filt.Primary) require.Equal(t, uint32(3), *filt.Since) @@ -543,12 +543,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { {"blocks till", func(t *testing.T, wsc *WSClient) { var till uint32 = 3 - _, err := wsc.ReceiveBlocks(&neorpc.BlockFilter{Till: &till}, make(chan *block.Block)) + _, err := wsc.ReceiveBlocks(&tutusrpc.BlockFilter{Till: &till}, make(chan *block.Block)) require.NoError(t, err) }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.BlockFilter) + filt := new(tutusrpc.BlockFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, (*byte)(nil), filt.Primary) require.Equal(t, (*uint32)(nil), filt.Since) @@ -562,7 +562,7 @@ func TestWSFilteredSubscriptions(t *testing.T) { primary = byte(2) till uint32 = 5 ) - _, err := wsc.ReceiveBlocks(&neorpc.BlockFilter{ + _, err := wsc.ReceiveBlocks(&tutusrpc.BlockFilter{ Primary: &primary, Since: &since, Till: &till, @@ -571,7 +571,7 @@ func TestWSFilteredSubscriptions(t *testing.T) { }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.BlockFilter) + filt := new(tutusrpc.BlockFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, byte(2), *filt.Primary) require.Equal(t, uint32(3), *filt.Since) @@ -581,12 +581,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { {"transactions sender", func(t *testing.T, wsc *WSClient) { sender := util.Uint160{1, 2, 3, 4, 5} - _, err := wsc.ReceiveTransactions(&neorpc.TxFilter{Sender: &sender}, make(chan *transaction.Transaction)) + _, err := wsc.ReceiveTransactions(&tutusrpc.TxFilter{Sender: &sender}, make(chan *transaction.Transaction)) require.NoError(t, err) }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.TxFilter) + filt := new(tutusrpc.TxFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, util.Uint160{1, 2, 3, 4, 5}, *filt.Sender) require.Nil(t, filt.Signer) @@ -595,12 +595,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { {"transactions signer", func(t *testing.T, wsc *WSClient) { signer := util.Uint160{0, 42} - _, err := wsc.ReceiveTransactions(&neorpc.TxFilter{Signer: &signer}, make(chan *transaction.Transaction)) + _, err := wsc.ReceiveTransactions(&tutusrpc.TxFilter{Signer: &signer}, make(chan *transaction.Transaction)) require.NoError(t, err) }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.TxFilter) + filt := new(tutusrpc.TxFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Nil(t, filt.Sender) require.Equal(t, util.Uint160{0, 42}, *filt.Signer) @@ -610,12 +610,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { func(t *testing.T, wsc *WSClient) { sender := util.Uint160{1, 2, 3, 4, 5} signer := util.Uint160{0, 42} - _, err := wsc.ReceiveTransactions(&neorpc.TxFilter{Sender: &sender, Signer: &signer}, make(chan *transaction.Transaction)) + _, err := wsc.ReceiveTransactions(&tutusrpc.TxFilter{Sender: &sender, Signer: &signer}, make(chan *transaction.Transaction)) require.NoError(t, err) }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.TxFilter) + filt := new(tutusrpc.TxFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, util.Uint160{1, 2, 3, 4, 5}, *filt.Sender) require.Equal(t, util.Uint160{0, 42}, *filt.Signer) @@ -624,12 +624,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { {"notifications contract hash", func(t *testing.T, wsc *WSClient) { contract := util.Uint160{1, 2, 3, 4, 5} - _, err := wsc.ReceiveExecutionNotifications(&neorpc.NotificationFilter{Contract: &contract}, make(chan *state.ContainedNotificationEvent)) + _, err := wsc.ReceiveExecutionNotifications(&tutusrpc.NotificationFilter{Contract: &contract}, make(chan *state.ContainedNotificationEvent)) require.NoError(t, err) }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.NotificationFilter) + filt := new(tutusrpc.NotificationFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, util.Uint160{1, 2, 3, 4, 5}, *filt.Contract) require.Nil(t, filt.Name) @@ -639,12 +639,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { {"notifications name", func(t *testing.T, wsc *WSClient) { name := "my_pretty_notification" - _, err := wsc.ReceiveExecutionNotifications(&neorpc.NotificationFilter{Name: &name}, make(chan *state.ContainedNotificationEvent)) + _, err := wsc.ReceiveExecutionNotifications(&tutusrpc.NotificationFilter{Name: &name}, make(chan *state.ContainedNotificationEvent)) require.NoError(t, err) }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.NotificationFilter) + filt := new(tutusrpc.NotificationFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, "my_pretty_notification", *filt.Name) require.Nil(t, filt.Contract) @@ -655,12 +655,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { func(t *testing.T, wsc *WSClient) { contract := util.Uint160{1, 2, 3, 4, 5} name := "my_pretty_notification" - _, err := wsc.ReceiveExecutionNotifications(&neorpc.NotificationFilter{Contract: &contract, Name: &name}, make(chan *state.ContainedNotificationEvent)) + _, err := wsc.ReceiveExecutionNotifications(&tutusrpc.NotificationFilter{Contract: &contract, Name: &name}, make(chan *state.ContainedNotificationEvent)) require.NoError(t, err) }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.NotificationFilter) + filt := new(tutusrpc.NotificationFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, util.Uint160{1, 2, 3, 4, 5}, *filt.Contract) require.Equal(t, "my_pretty_notification", *filt.Name) @@ -673,12 +673,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { name := "my_pretty_notification" prms, err := smartcontract.NewParametersFromValues(1, "2", []byte{3}) require.NoError(t, err) - _, err = wsc.ReceiveExecutionNotifications(&neorpc.NotificationFilter{Contract: &contract, Name: &name, Parameters: prms}, make(chan *state.ContainedNotificationEvent)) + _, err = wsc.ReceiveExecutionNotifications(&tutusrpc.NotificationFilter{Contract: &contract, Name: &name, Parameters: prms}, make(chan *state.ContainedNotificationEvent)) require.NoError(t, err) }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.NotificationFilter) + filt := new(tutusrpc.NotificationFilter) prms, err := smartcontract.NewParametersFromValues(1, "2", []byte{3}) require.NoError(t, err) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) @@ -690,12 +690,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { {"executions state", func(t *testing.T, wsc *WSClient) { vmstate := "FAULT" - _, err := wsc.ReceiveExecutions(&neorpc.ExecutionFilter{State: &vmstate}, make(chan *state.AppExecResult)) + _, err := wsc.ReceiveExecutions(&tutusrpc.ExecutionFilter{State: &vmstate}, make(chan *state.AppExecResult)) require.NoError(t, err) }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.ExecutionFilter) + filt := new(tutusrpc.ExecutionFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, "FAULT", *filt.State) require.Equal(t, (*util.Uint256)(nil), filt.Container) @@ -704,12 +704,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { {"executions container", func(t *testing.T, wsc *WSClient) { container := util.Uint256{1, 2, 3} - _, err := wsc.ReceiveExecutions(&neorpc.ExecutionFilter{Container: &container}, make(chan *state.AppExecResult)) + _, err := wsc.ReceiveExecutions(&tutusrpc.ExecutionFilter{Container: &container}, make(chan *state.AppExecResult)) require.NoError(t, err) }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.ExecutionFilter) + filt := new(tutusrpc.ExecutionFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, (*string)(nil), filt.State) require.Equal(t, util.Uint256{1, 2, 3}, *filt.Container) @@ -719,12 +719,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { func(t *testing.T, wsc *WSClient) { vmstate := "FAULT" container := util.Uint256{1, 2, 3} - _, err := wsc.ReceiveExecutions(&neorpc.ExecutionFilter{State: &vmstate, Container: &container}, make(chan *state.AppExecResult)) + _, err := wsc.ReceiveExecutions(&tutusrpc.ExecutionFilter{State: &vmstate, Container: &container}, make(chan *state.AppExecResult)) require.NoError(t, err) }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.ExecutionFilter) + filt := new(tutusrpc.ExecutionFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, "FAULT", *filt.State) require.Equal(t, util.Uint256{1, 2, 3}, *filt.Container) @@ -734,12 +734,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { "notary request sender", func(t *testing.T, wsc *WSClient) { sender := util.Uint160{1, 2, 3, 4, 5} - _, err := wsc.ReceiveNotaryRequests(&neorpc.NotaryRequestFilter{Sender: &sender}, make(chan *result.NotaryRequestEvent)) + _, err := wsc.ReceiveNotaryRequests(&tutusrpc.NotaryRequestFilter{Sender: &sender}, make(chan *result.NotaryRequestEvent)) require.NoError(t, err) }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.NotaryRequestFilter) + filt := new(tutusrpc.NotaryRequestFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, util.Uint160{1, 2, 3, 4, 5}, *filt.Sender) require.Nil(t, filt.Signer) @@ -750,12 +750,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { "notary request signer", func(t *testing.T, wsc *WSClient) { signer := util.Uint160{0, 42} - _, err := wsc.ReceiveNotaryRequests(&neorpc.NotaryRequestFilter{Signer: &signer}, make(chan *result.NotaryRequestEvent)) + _, err := wsc.ReceiveNotaryRequests(&tutusrpc.NotaryRequestFilter{Signer: &signer}, make(chan *result.NotaryRequestEvent)) require.NoError(t, err) }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.NotaryRequestFilter) + filt := new(tutusrpc.NotaryRequestFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Nil(t, filt.Sender) require.Equal(t, util.Uint160{0, 42}, *filt.Signer) @@ -766,12 +766,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { "notary request type", func(t *testing.T, wsc *WSClient) { mempoolType := mempoolevent.TransactionAdded - _, err := wsc.ReceiveNotaryRequests(&neorpc.NotaryRequestFilter{Type: &mempoolType}, make(chan *result.NotaryRequestEvent)) + _, err := wsc.ReceiveNotaryRequests(&tutusrpc.NotaryRequestFilter{Type: &mempoolType}, make(chan *result.NotaryRequestEvent)) require.NoError(t, err) }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.NotaryRequestFilter) + filt := new(tutusrpc.NotaryRequestFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, mempoolevent.TransactionAdded, *filt.Type) require.Nil(t, filt.Sender) @@ -783,12 +783,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { sender := util.Uint160{1, 2, 3, 4, 5} signer := util.Uint160{0, 42} mempoolType := mempoolevent.TransactionAdded - _, err := wsc.ReceiveNotaryRequests(&neorpc.NotaryRequestFilter{Type: &mempoolType, Signer: &signer, Sender: &sender}, make(chan *result.NotaryRequestEvent)) + _, err := wsc.ReceiveNotaryRequests(&tutusrpc.NotaryRequestFilter{Type: &mempoolType, Signer: &signer, Sender: &sender}, make(chan *result.NotaryRequestEvent)) require.NoError(t, err) }, func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.NotaryRequestFilter) + filt := new(tutusrpc.NotaryRequestFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Equal(t, util.Uint160{1, 2, 3, 4, 5}, *filt.Sender) require.Equal(t, util.Uint160{0, 42}, *filt.Signer) @@ -799,12 +799,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { name: "mempool event type", clientCode: func(t *testing.T, wsc *WSClient) { typ := mempoolevent.TransactionAdded - _, err := wsc.ReceiveMempoolEvents(&neorpc.MempoolEventFilter{Type: &typ}, make(chan *result.MempoolEvent)) + _, err := wsc.ReceiveMempoolEvents(&tutusrpc.MempoolEventFilter{Type: &typ}, make(chan *result.MempoolEvent)) require.NoError(t, err) }, serverCode: func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.MempoolEventFilter) + filt := new(tutusrpc.MempoolEventFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.NotNil(t, filt.Type) require.Equal(t, mempoolevent.TransactionAdded, *filt.Type) @@ -816,12 +816,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { name: "mempool event sender", clientCode: func(t *testing.T, wsc *WSClient) { sender := util.Uint160{1, 2, 3, 4, 5} - _, err := wsc.ReceiveMempoolEvents(&neorpc.MempoolEventFilter{Sender: &sender}, make(chan *result.MempoolEvent)) + _, err := wsc.ReceiveMempoolEvents(&tutusrpc.MempoolEventFilter{Sender: &sender}, make(chan *result.MempoolEvent)) require.NoError(t, err) }, serverCode: func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.MempoolEventFilter) + filt := new(tutusrpc.MempoolEventFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Nil(t, filt.Type) require.Equal(t, util.Uint160{1, 2, 3, 4, 5}, *filt.Sender) @@ -832,12 +832,12 @@ func TestWSFilteredSubscriptions(t *testing.T) { name: "mempool event signer", clientCode: func(t *testing.T, wsc *WSClient) { signer := util.Uint160{0, 42} - _, err := wsc.ReceiveMempoolEvents(&neorpc.MempoolEventFilter{Signer: &signer}, make(chan *result.MempoolEvent)) + _, err := wsc.ReceiveMempoolEvents(&tutusrpc.MempoolEventFilter{Signer: &signer}, make(chan *result.MempoolEvent)) require.NoError(t, err) }, serverCode: func(t *testing.T, p *params.Params) { param := p.Value(1) - filt := new(neorpc.MempoolEventFilter) + filt := new(tutusrpc.MempoolEventFilter) require.NoError(t, json.Unmarshal(param.RawMessage, filt)) require.Nil(t, filt.Type) require.Nil(t, filt.Sender) diff --git a/pkg/services/notary/core_test.go b/pkg/services/notary/core_test.go index c4f4e51..001c6cb 100644 --- a/pkg/services/notary/core_test.go +++ b/pkg/services/notary/core_test.go @@ -21,8 +21,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/crypto/hash" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" "github.com/tutus-one/tutus-chain/pkg/io" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/network" "github.com/tutus-one/tutus-chain/pkg/network/payload" "github.com/tutus-one/tutus-chain/pkg/services/notary" diff --git a/pkg/services/oracle/filter.go b/pkg/services/oracle/filter.go index bcf4ced..67ed3ee 100644 --- a/pkg/services/oracle/filter.go +++ b/pkg/services/oracle/filter.go @@ -5,7 +5,7 @@ import ( "errors" "unicode/utf8" - json "github.com/nspcc-dev/go-ordered-json" + json "github.com/tutus-one/tutus-ordered-json" "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/services/oracle/jsonpath" ) diff --git a/pkg/services/oracle/jsonpath/jsonpath.go b/pkg/services/oracle/jsonpath/jsonpath.go index 90667c0..af2b70f 100644 --- a/pkg/services/oracle/jsonpath/jsonpath.go +++ b/pkg/services/oracle/jsonpath/jsonpath.go @@ -4,7 +4,7 @@ import ( "strconv" "strings" - json "github.com/nspcc-dev/go-ordered-json" + json "github.com/tutus-one/tutus-ordered-json" ) type ( diff --git a/pkg/services/oracle/jsonpath/jsonpath_test.go b/pkg/services/oracle/jsonpath/jsonpath_test.go index e537fb1..439a474 100644 --- a/pkg/services/oracle/jsonpath/jsonpath_test.go +++ b/pkg/services/oracle/jsonpath/jsonpath_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - json "github.com/nspcc-dev/go-ordered-json" + json "github.com/tutus-one/tutus-ordered-json" "github.com/stretchr/testify/require" ) diff --git a/pkg/services/oracle/oracle_test.go b/pkg/services/oracle/oracle_test.go index 0b81d35..cb1ddb6 100644 --- a/pkg/services/oracle/oracle_test.go +++ b/pkg/services/oracle/oracle_test.go @@ -25,8 +25,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" "github.com/tutus-one/tutus-chain/pkg/interop/native/roles" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/services/oracle" "github.com/tutus-one/tutus-chain/pkg/smartcontract/manifest" "github.com/tutus-one/tutus-chain/pkg/util" diff --git a/pkg/services/rpcsrv/client_test.go b/pkg/services/rpcsrv/client_test.go index ab3608a..4a16703 100644 --- a/pkg/services/rpcsrv/client_test.go +++ b/pkg/services/rpcsrv/client_test.go @@ -36,15 +36,15 @@ import ( "github.com/tutus-one/tutus-chain/pkg/crypto/keys" "github.com/tutus-one/tutus-chain/pkg/encoding/bigint" "github.com/tutus-one/tutus-chain/pkg/io" - "github.com/tutus-one/tutus-chain/pkg/neorpc" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/network" "github.com/tutus-one/tutus-chain/pkg/rpcclient" "github.com/tutus-one/tutus-chain/pkg/rpcclient/actor" "github.com/tutus-one/tutus-chain/pkg/rpcclient/gas" "github.com/tutus-one/tutus-chain/pkg/rpcclient/invoker" "github.com/tutus-one/tutus-chain/pkg/rpcclient/management" - "github.com/tutus-one/tutus-chain/pkg/rpcclient/neo" + "github.com/tutus-one/tutus-chain/pkg/rpcclient/tutus" "github.com/tutus-one/tutus-chain/pkg/rpcclient/nep11" "github.com/tutus-one/tutus-chain/pkg/rpcclient/nep17" "github.com/tutus-one/tutus-chain/pkg/rpcclient/nep24" @@ -415,7 +415,7 @@ func TestClientNEOContract(t *testing.T) { t.Cleanup(c.Close) require.NoError(t, c.Init()) - neoR := neo.NewReader(invoker.New(c, nil)) + neoR := tutus.NewReader(invoker.New(c, nil)) sym, err := neoR.Symbol() require.NoError(t, err) @@ -489,7 +489,7 @@ func TestClientNEOContract(t *testing.T) { require.NoError(t, err) - neoC := neo.New(act) + neoC := tutus.New(act) txgpb, err := neoC.SetGasPerBlockUnsigned(10 * 1_0000_0000) require.NoError(t, err) @@ -514,7 +514,7 @@ func TestClientNEOContract(t *testing.T) { act0, err := actor.NewSimple(c, wallet.NewAccountFromPrivateKey(testchain.PrivateKey(0))) require.NoError(t, err) - neo0 := neo.New(act0) + neo0 := tutus.New(act0) txreg, err := neo0.RegisterCandidateTransaction(testchain.PrivateKey(0).PublicKey()) require.NoError(t, err) @@ -956,7 +956,7 @@ func TestNotaryActor(t *testing.T) { Account: multiAcc, }}, acc) require.NoError(t, err) - neoW := neo.New(nact) + neoW := tutus.New(nact) _, _, _, err = nact.Notarize(neoW.SetRegisterPriceTransaction(1_0000_0000)) require.NoError(t, err) } @@ -997,7 +997,7 @@ func TestGetRawNotaryPoolAndTransaction(t *testing.T) { Account: multiAcc, }}, acc) require.NoError(t, err) - neoW := neo.New(nact) + neoW := tutus.New(nact) // Send the 1st notary request tx1, err = neoW.SetRegisterPriceTransaction(1_0000_0000) require.NoError(t, err) @@ -1036,7 +1036,7 @@ func TestGetRawNotaryPoolAndTransaction(t *testing.T) { t.Run("unknown transaction", func(t *testing.T) { _, err := c.GetRawNotaryTransaction(util.Uint256{0, 0, 0}) require.Error(t, err) - require.ErrorIs(t, err, neorpc.ErrUnknownTransaction) + require.ErrorIs(t, err, tutusrpc.ErrUnknownTransaction) }) _ = tx1.Size() _ = tx2.Size() @@ -1072,7 +1072,7 @@ func TestGetRawNotaryPoolAndTransaction(t *testing.T) { t.Run("unknown transaction", func(t *testing.T) { _, err := c.GetRawNotaryTransactionVerbose(util.Uint256{0, 0, 0}) require.Error(t, err) - require.ErrorIs(t, err, neorpc.ErrUnknownTransaction) + require.ErrorIs(t, err, tutusrpc.ErrUnknownTransaction) }) t.Run("transactions from pool", func(t *testing.T) { mainTx1, err := c.GetRawNotaryTransactionVerbose(mainHash1) @@ -1309,7 +1309,7 @@ func TestClient_NEP11_ND(t *testing.T) { t.Run("TotalSupply", func(t *testing.T) { s, err := n11.TotalSupply() require.NoError(t, err) - require.EqualValues(t, big.NewInt(1), s) // the only `neo.com` of acc0 + require.EqualValues(t, big.NewInt(1), s) // the only `tutus.com` of acc0 }) t.Run("Symbol", func(t *testing.T) { sym, err := n11.Symbol() @@ -1333,7 +1333,7 @@ func TestClient_NEP11_ND(t *testing.T) { require.EqualValues(t, big.NewInt(1), b) }) t.Run("OwnerOf", func(t *testing.T) { - b, err := n11.OwnerOf([]byte("neo.com")) + b, err := n11.OwnerOf([]byte("tutus.com")) require.NoError(t, err) require.EqualValues(t, acc, b) }) @@ -1343,28 +1343,28 @@ func TestClient_NEP11_ND(t *testing.T) { items, err := iter.Next(config.DefaultMaxIteratorResultItems) require.NoError(t, err) require.Equal(t, 1, len(items)) - require.Equal(t, [][]byte{[]byte("neo.com")}, items) + require.Equal(t, [][]byte{[]byte("tutus.com")}, items) require.NoError(t, iter.Terminate()) }) t.Run("TokensExpanded", func(t *testing.T) { items, err := n11.TokensExpanded(config.DefaultMaxIteratorResultItems) require.NoError(t, err) - require.Equal(t, [][]byte{[]byte("neo.com")}, items) + require.Equal(t, [][]byte{[]byte("tutus.com")}, items) }) t.Run("Properties", func(t *testing.T) { - p, err := n11.Properties([]byte("neo.com")) + p, err := n11.Properties([]byte("tutus.com")) require.NoError(t, err) - blockRegisterDomain, err := chain.GetBlock(chain.GetHeaderHash(14)) // `neo.com` domain was registered in 14th block + blockRegisterDomain, err := chain.GetBlock(chain.GetHeaderHash(14)) // `tutus.com` domain was registered in 14th block require.NoError(t, err) require.Equal(t, 1, len(blockRegisterDomain.Transactions)) expected := stackitem.NewMap() - expected.Add(stackitem.Make([]byte("name")), stackitem.Make([]byte("neo.com"))) + expected.Add(stackitem.Make([]byte("name")), stackitem.Make([]byte("tutus.com"))) expected.Add(stackitem.Make([]byte("expiration")), stackitem.Make(blockRegisterDomain.Timestamp+365*24*3600*1000)) // expiration formula expected.Add(stackitem.Make([]byte("admin")), stackitem.Null{}) require.EqualValues(t, expected, p) }) t.Run("Transfer", func(t *testing.T) { - _, _, err := n11.Transfer(testchain.PrivateKeyByID(1).GetScriptHash(), []byte("neo.com"), nil) + _, _, err := n11.Transfer(testchain.PrivateKeyByID(1).GetScriptHash(), []byte("tutus.com"), nil) require.NoError(t, err) }) } @@ -1462,7 +1462,7 @@ func TestClient_NNS(t *testing.T) { nnc := nns.NewReader(invoker.New(c, nil), nnsHash) t.Run("IsAvailable, false", func(t *testing.T) { - b, err := nnc.IsAvailable("neo.com") + b, err := nnc.IsAvailable("tutus.com") require.NoError(t, err) require.Equal(t, false, b) }) @@ -1472,7 +1472,7 @@ func TestClient_NNS(t *testing.T) { require.Equal(t, true, b) }) t.Run("Resolve, good", func(t *testing.T) { - b, err := nnc.Resolve("neo.com", nns.A) + b, err := nnc.Resolve("tutus.com", nns.A) require.NoError(t, err) require.Equal(t, "1.2.3.4", b) }) @@ -1485,23 +1485,23 @@ func TestClient_NNS(t *testing.T) { require.Error(t, err) }) t.Run("GetAllRecords, good", func(t *testing.T) { - iter, err := nnc.GetAllRecords("neo.com") + iter, err := nnc.GetAllRecords("tutus.com") require.NoError(t, err) arr, err := iter.Next(config.DefaultMaxIteratorResultItems) require.NoError(t, err) require.Equal(t, 1, len(arr)) require.Equal(t, nns.RecordState{ - Name: "neo.com", + Name: "tutus.com", Type: nns.A, Data: "1.2.3.4", }, arr[0]) }) t.Run("GetAllRecordsExpanded, good", func(t *testing.T) { - rss, err := nnc.GetAllRecordsExpanded("neo.com", 42) + rss, err := nnc.GetAllRecordsExpanded("tutus.com", 42) require.NoError(t, err) require.Equal(t, []nns.RecordState{ { - Name: "neo.com", + Name: "tutus.com", Type: nns.A, Data: "1.2.3.4", }, @@ -1627,7 +1627,7 @@ func TestClient_IteratorSessions(t *testing.T) { ok, err = c.TerminateSession(sID) require.Error(t, err) - require.ErrorIs(t, err, neorpc.ErrUnknownSession) + require.ErrorIs(t, err, tutusrpc.ErrUnknownSession) require.False(t, ok) // session has already been terminated. }) t.Run("automatically", func(t *testing.T) { @@ -1651,7 +1651,7 @@ func TestClient_IteratorSessions(t *testing.T) { ok, err := c.TerminateSession(sID) require.Error(t, err) - require.ErrorIs(t, err, neorpc.ErrUnknownSession) + require.ErrorIs(t, err, tutusrpc.ErrUnknownSession) require.False(t, ok) // session has already been terminated. }) }) @@ -1898,7 +1898,7 @@ func TestClient_Wait(t *testing.T) { go func() { var err error if tx != nil { - // Send one more time to ensure [neorpc.ErrAlreadyExists] is properly handled by Waiter. + // Send one more time to ensure [tutusrpc.ErrAlreadyExists] is properly handled by Waiter. h, vub, err = act.Send(tx) } aer, err := act.Wait(context.Background(), h, vub, err) @@ -2011,7 +2011,7 @@ func testSubClientWait(t *testing.T, local bool) { for s := range rpcSrv.subscribers { var count int for _, f := range s.feeds { - if f.event != neorpc.InvalidEventID { + if f.event != tutusrpc.InvalidEventID { count++ } } @@ -2050,7 +2050,7 @@ func testSubClientWait(t *testing.T, local bool) { } for s := range rpcSrv.subscribers { for _, f := range s.feeds { - if f.event != neorpc.InvalidEventID { + if f.event != tutusrpc.InvalidEventID { return false } } @@ -2173,9 +2173,9 @@ func testSubClientWaitWithMissedEvent(t *testing.T, local bool) { // Accept the next block, but subscriber will get no events because it's overflown. require.NoError(t, chain.AddBlock(b1)) - overNotification := neorpc.Notification{ - JSONRPC: neorpc.JSONRPCVersion, - Event: neorpc.MissedEventID, + overNotification := tutusrpc.Notification{ + JSONRPC: tutusrpc.JSONRPCVersion, + Event: tutusrpc.MissedEventID, Payload: make([]any, 0), } overEvent, err := json.Marshal(overNotification) @@ -2238,19 +2238,19 @@ func TestWSClient_SubscriptionsCompat(t *testing.T) { ntfCh = make(chan *state.ContainedNotificationEvent) aerCh = make(chan *state.AppExecResult) memCh = make(chan *result.MempoolEvent) - bFlt *neorpc.BlockFilter - txFlt *neorpc.TxFilter - ntfFlt *neorpc.NotificationFilter - aerFlt *neorpc.ExecutionFilter - memFlt *neorpc.MempoolEventFilter + bFlt *tutusrpc.BlockFilter + txFlt *tutusrpc.TxFilter + ntfFlt *tutusrpc.NotificationFilter + aerFlt *tutusrpc.ExecutionFilter + memFlt *tutusrpc.MempoolEventFilter err error ) if filtered { - bFlt = &neorpc.BlockFilter{Primary: &primary} - txFlt = &neorpc.TxFilter{Sender: &sender} - ntfFlt = &neorpc.NotificationFilter{Name: &ntfName} - aerFlt = &neorpc.ExecutionFilter{State: &st} - memFlt = &neorpc.MempoolEventFilter{Type: &typ} + bFlt = &tutusrpc.BlockFilter{Primary: &primary} + txFlt = &tutusrpc.TxFilter{Sender: &sender} + ntfFlt = &tutusrpc.NotificationFilter{Name: &ntfName} + aerFlt = &tutusrpc.ExecutionFilter{State: &st} + memFlt = &tutusrpc.MempoolEventFilter{Type: &typ} } bID, err = c.ReceiveBlocks(bFlt, blockCh) require.NoError(t, err) @@ -2542,7 +2542,7 @@ func TestClient_GetStorageHistoric(t *testing.T) { earlyRoot, err := chain.GetStateRoot(15) // there's no `aa10` value in Rubles contract by the moment of block #15 require.NoError(t, err) _, err = c.GetStorageByHashHistoric(earlyRoot.Root, h, key) - require.ErrorIs(t, neorpc.ErrUnknownStorageItem, err) + require.ErrorIs(t, tutusrpc.ErrUnknownStorageItem, err) } func TestClient_GetVersion_Hardforks(t *testing.T) { @@ -2623,13 +2623,13 @@ func TestGetBlockNotifications(t *testing.T) { require.NotEmpty(t, bn) }) t.Run("empty filter", func(t *testing.T) { - bn, err := c.GetBlockNotifications(chain.GetHeaderHash(1), &neorpc.NotificationFilter{}) + bn, err := c.GetBlockNotifications(chain.GetHeaderHash(1), &tutusrpc.NotificationFilter{}) require.NoError(t, err) require.NotEmpty(t, bn) }) t.Run("bad filter", func(t *testing.T) { badName := "Transfer1" - bn, err := c.GetBlockNotifications(chain.GetHeaderHash(1), &neorpc.NotificationFilter{ + bn, err := c.GetBlockNotifications(chain.GetHeaderHash(1), &tutusrpc.NotificationFilter{ Name: &badName, }) require.NoError(t, err) @@ -2637,7 +2637,7 @@ func TestGetBlockNotifications(t *testing.T) { }) t.Run("good", func(t *testing.T) { name := "Transfer" - bn, err := c.GetBlockNotifications(chain.GetHeaderHash(1), &neorpc.NotificationFilter{ + bn, err := c.GetBlockNotifications(chain.GetHeaderHash(1), &tutusrpc.NotificationFilter{ Name: &name, }) require.NoError(t, err) diff --git a/pkg/services/rpcsrv/error.go b/pkg/services/rpcsrv/error.go index a4ab7d5..d2f6c33 100644 --- a/pkg/services/rpcsrv/error.go +++ b/pkg/services/rpcsrv/error.go @@ -1,25 +1,25 @@ package rpcsrv import ( - "github.com/tutus-one/tutus-chain/pkg/neorpc" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc" ) // abstractResult is an interface which represents either single JSON-RPC 2.0 response // or batch JSON-RPC 2.0 response. type abstractResult interface { - RunForErrors(f func(jsonErr *neorpc.Error)) + RunForErrors(f func(jsonErr *tutusrpc.Error)) } // abstract represents abstract JSON-RPC 2.0 response. It is used as a server-side response // representation. type abstract struct { - neorpc.Header - Error *neorpc.Error `json:"error,omitzero"` + tutusrpc.Header + Error *tutusrpc.Error `json:"error,omitzero"` Result any `json:"result,omitzero"` } // RunForErrors implements abstractResult interface. -func (a abstract) RunForErrors(f func(jsonErr *neorpc.Error)) { +func (a abstract) RunForErrors(f func(jsonErr *tutusrpc.Error)) { if a.Error != nil { f(a.Error) } @@ -29,7 +29,7 @@ func (a abstract) RunForErrors(f func(jsonErr *neorpc.Error)) { type abstractBatch []abstract // RunForErrors implements abstractResult interface. -func (ab abstractBatch) RunForErrors(f func(jsonErr *neorpc.Error)) { +func (ab abstractBatch) RunForErrors(f func(jsonErr *tutusrpc.Error)) { for _, a := range ab { a.RunForErrors(f) } diff --git a/pkg/services/rpcsrv/notification_comparator.go b/pkg/services/rpcsrv/notification_comparator.go index 44097ca..7229b6c 100644 --- a/pkg/services/rpcsrv/notification_comparator.go +++ b/pkg/services/rpcsrv/notification_comparator.go @@ -2,24 +2,24 @@ package rpcsrv import ( "github.com/tutus-one/tutus-chain/pkg/core/state" - "github.com/tutus-one/tutus-chain/pkg/neorpc" - "github.com/tutus-one/tutus-chain/pkg/neorpc/rpcevent" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/rpcevent" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/vmstate" ) // notificationEventComparator is a comparator for notification events. type notificationEventComparator struct { - filter neorpc.SubscriptionFilter + filter tutusrpc.SubscriptionFilter } // EventID returns the event ID for the notification event comparator. -func (s notificationEventComparator) EventID() neorpc.EventID { - return neorpc.NotificationEventID +func (s notificationEventComparator) EventID() tutusrpc.EventID { + return tutusrpc.NotificationEventID } // Filter returns the filter for the notification event comparator. -func (c notificationEventComparator) Filter() neorpc.SubscriptionFilter { +func (c notificationEventComparator) Filter() tutusrpc.SubscriptionFilter { return c.filter } @@ -29,8 +29,8 @@ type notificationEventContainer struct { } // EventID returns the event ID for the notification event container. -func (c notificationEventContainer) EventID() neorpc.EventID { - return neorpc.NotificationEventID +func (c notificationEventContainer) EventID() tutusrpc.EventID { + return tutusrpc.NotificationEventID } // EventPayload returns the payload for the notification event container. @@ -38,7 +38,7 @@ func (c notificationEventContainer) EventPayload() any { return c.ntf } -func processAppExecResults(aers []state.AppExecResult, filter *neorpc.NotificationFilter) []state.ContainedNotificationEvent { +func processAppExecResults(aers []state.AppExecResult, filter *tutusrpc.NotificationFilter) []state.ContainedNotificationEvent { var notifications []state.ContainedNotificationEvent for _, aer := range aers { if aer.VMState == vmstate.Halt { @@ -48,7 +48,7 @@ func processAppExecResults(aers []state.AppExecResult, filter *neorpc.Notificati return notifications } -func filterEvents(events []state.NotificationEvent, container util.Uint256, filter *neorpc.NotificationFilter) []state.ContainedNotificationEvent { +func filterEvents(events []state.NotificationEvent, container util.Uint256, filter *tutusrpc.NotificationFilter) []state.ContainedNotificationEvent { var notifications []state.ContainedNotificationEvent for _, evt := range events { ntf := state.ContainedNotificationEvent{ diff --git a/pkg/services/rpcsrv/params/param.go b/pkg/services/rpcsrv/params/param.go index 8363441..5c5e3ec 100644 --- a/pkg/services/rpcsrv/params/param.go +++ b/pkg/services/rpcsrv/params/param.go @@ -15,7 +15,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/block" "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/encoding/address" - "github.com/tutus-one/tutus-chain/pkg/neorpc" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/util" ) @@ -404,13 +404,13 @@ func (p *Param) GetBytesBase64() ([]byte, error) { return base64.StdEncoding.DecodeString(s) } -// GetSignerWithWitness returns a neorpc.SignerWithWitness value of the parameter. -func (p *Param) GetSignerWithWitness() (neorpc.SignerWithWitness, error) { +// GetSignerWithWitness returns a tutusrpc.SignerWithWitness value of the parameter. +func (p *Param) GetSignerWithWitness() (tutusrpc.SignerWithWitness, error) { // This one doesn't need to be cached, it's used only once. - c := neorpc.SignerWithWitness{} + c := tutusrpc.SignerWithWitness{} err := json.Unmarshal(p.RawMessage, &c) if err != nil { - return neorpc.SignerWithWitness{}, fmt.Errorf("not a signer: %w", err) + return tutusrpc.SignerWithWitness{}, fmt.Errorf("not a signer: %w", err) } return c, nil } diff --git a/pkg/services/rpcsrv/params/param_test.go b/pkg/services/rpcsrv/params/param_test.go index a444451..5c65414 100644 --- a/pkg/services/rpcsrv/params/param_test.go +++ b/pkg/services/rpcsrv/params/param_test.go @@ -12,7 +12,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/encoding/address" - "github.com/tutus-one/tutus-chain/pkg/neorpc" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/stretchr/testify/assert" @@ -155,7 +155,7 @@ func TestParam_UnmarshalJSON(t *testing.T) { require.NoError(t, err) expectedAcc, err := util.Uint160DecodeStringLE("cadb3dc2faa3ef14a13b619c9a43124755aa2569") require.NoError(t, err) - require.Equal(t, neorpc.SignerWithWitness{Signer: transaction.Signer{Account: expectedAcc}}, actual) + require.Equal(t, tutusrpc.SignerWithWitness{Signer: transaction.Signer{Account: expectedAcc}}, actual) }, expectedRawMessage: []byte(`{"account": "0xcadb3dc2faa3ef14a13b619c9a43124755aa2569"}`), }, @@ -165,7 +165,7 @@ func TestParam_UnmarshalJSON(t *testing.T) { require.NoError(t, err) expectedAcc, err := address.StringToUint160("NYxb4fSZVKAz8YsgaPK2WkT3KcAE9b3Vag") require.NoError(t, err) - require.Equal(t, neorpc.SignerWithWitness{Signer: transaction.Signer{Account: expectedAcc, Scopes: transaction.Global}}, actual) + require.Equal(t, tutusrpc.SignerWithWitness{Signer: transaction.Signer{Account: expectedAcc, Scopes: transaction.Global}}, actual) }, expectedRawMessage: []byte(`{"account": "NYxb4fSZVKAz8YsgaPK2WkT3KcAE9b3Vag", "scopes": "Global"}`), }, @@ -244,12 +244,12 @@ func TestGetWitness(t *testing.T) { testCases := []struct { raw string - expected neorpc.SignerWithWitness + expected tutusrpc.SignerWithWitness shouldFail bool }{ { raw: `{"account": "0xcadb3dc2faa3ef14a13b619c9a43124755aa2569"}`, - expected: neorpc.SignerWithWitness{ + expected: tutusrpc.SignerWithWitness{ Signer: transaction.Signer{ Account: accountHash, Scopes: transaction.None, @@ -258,7 +258,7 @@ func TestGetWitness(t *testing.T) { }, { raw: `{"account": "NYxb4fSZVKAz8YsgaPK2WkT3KcAE9b3Vag", "scopes": "Global"}`, - expected: neorpc.SignerWithWitness{ + expected: tutusrpc.SignerWithWitness{ Signer: transaction.Signer{ Account: addrHash, Scopes: transaction.Global, @@ -267,7 +267,7 @@ func TestGetWitness(t *testing.T) { }, { raw: `{"account": "0xcadb3dc2faa3ef14a13b619c9a43124755aa2569", "scopes": "Global"}`, - expected: neorpc.SignerWithWitness{ + expected: tutusrpc.SignerWithWitness{ Signer: transaction.Signer{ Account: accountHash, Scopes: transaction.Global, @@ -276,7 +276,7 @@ func TestGetWitness(t *testing.T) { }, { raw: `{"account": "0xcadb3dc2faa3ef14a13b619c9a43124755aa2569", "scopes": 128}`, - expected: neorpc.SignerWithWitness{ + expected: tutusrpc.SignerWithWitness{ Signer: transaction.Signer{ Account: accountHash, Scopes: transaction.Global, @@ -285,7 +285,7 @@ func TestGetWitness(t *testing.T) { }, { raw: `{"account": "0xcadb3dc2faa3ef14a13b619c9a43124755aa2569", "scopes": 0}`, - expected: neorpc.SignerWithWitness{ + expected: tutusrpc.SignerWithWitness{ Signer: transaction.Signer{ Account: accountHash, Scopes: transaction.None, @@ -294,7 +294,7 @@ func TestGetWitness(t *testing.T) { }, { raw: `{"account": "0xcadb3dc2faa3ef14a13b619c9a43124755aa2569", "scopes": 1}`, - expected: neorpc.SignerWithWitness{ + expected: tutusrpc.SignerWithWitness{ Signer: transaction.Signer{ Account: accountHash, Scopes: transaction.CalledByEntry, @@ -303,7 +303,7 @@ func TestGetWitness(t *testing.T) { }, { raw: `{"account": "0xcadb3dc2faa3ef14a13b619c9a43124755aa2569", "scopes": 17}`, - expected: neorpc.SignerWithWitness{ + expected: tutusrpc.SignerWithWitness{ Signer: transaction.Signer{ Account: accountHash, Scopes: transaction.CalledByEntry | transaction.CustomContracts, @@ -505,7 +505,7 @@ func TestParamGetBytesBase64(t *testing.T) { } func TestParamGetSigner(t *testing.T) { - c := neorpc.SignerWithWitness{ + c := tutusrpc.SignerWithWitness{ Signer: transaction.Signer{ Account: util.Uint160{1, 2, 3, 4}, Scopes: transaction.Global, diff --git a/pkg/services/rpcsrv/params/types.go b/pkg/services/rpcsrv/params/types.go index d250b4f..e924397 100644 --- a/pkg/services/rpcsrv/params/types.go +++ b/pkg/services/rpcsrv/params/types.go @@ -7,7 +7,7 @@ import ( "fmt" "io" - "github.com/tutus-one/tutus-chain/pkg/neorpc" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc" ) const ( @@ -105,6 +105,6 @@ func NewRequest() *Request { // NewIn creates a new In struct. func NewIn() *In { return &In{ - JSONRPC: neorpc.JSONRPCVersion, + JSONRPC: tutusrpc.JSONRPCVersion, } } diff --git a/pkg/services/rpcsrv/server.go b/pkg/services/rpcsrv/server.go index 98a00f9..1e4ff93 100644 --- a/pkg/services/rpcsrv/server.go +++ b/pkg/services/rpcsrv/server.go @@ -39,9 +39,9 @@ import ( "github.com/tutus-one/tutus-chain/pkg/crypto/keys" "github.com/tutus-one/tutus-chain/pkg/encoding/address" "github.com/tutus-one/tutus-chain/pkg/io" - "github.com/tutus-one/tutus-chain/pkg/neorpc" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" - "github.com/tutus-one/tutus-chain/pkg/neorpc/rpcevent" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/rpcevent" "github.com/tutus-one/tutus-chain/pkg/network" "github.com/tutus-one/tutus-chain/pkg/network/payload" "github.com/tutus-one/tutus-chain/pkg/services/oracle/broadcaster" @@ -217,7 +217,7 @@ const ( defaultSessionPoolSize = 20 ) -var rpcHandlers = map[string]func(*Server, params.Params) (any, *neorpc.Error){ +var rpcHandlers = map[string]func(*Server, params.Params) (any, *tutusrpc.Error){ "calculatenetworkfee": (*Server).calculateNetworkFee, "findstates": (*Server).findStates, "findstorage": (*Server).findStorage, @@ -273,7 +273,7 @@ var rpcHandlers = map[string]func(*Server, params.Params) (any, *neorpc.Error){ "verifyproof": (*Server).verifyProof, } -var rpcWsHandlers = map[string]func(*Server, params.Params, *subscriber) (any, *neorpc.Error){ +var rpcWsHandlers = map[string]func(*Server, params.Params, *subscriber) (any, *tutusrpc.Error){ "subscribe": (*Server).subscribe, "unsubscribe": (*Server).unsubscribe, } @@ -518,7 +518,7 @@ func (s *Server) handleHTTPRequest(w http.ResponseWriter, httpRequest *http.Requ s.writeHTTPErrorResponse( params.NewIn(), w, - neorpc.NewInternalServerError("websocket users limit reached"), + tutusrpc.NewInternalServerError("websocket users limit reached"), ) return } @@ -549,14 +549,14 @@ func (s *Server) handleHTTPRequest(w http.ResponseWriter, httpRequest *http.Requ s.writeHTTPErrorResponse( params.NewIn(), w, - neorpc.NewInvalidParamsError(fmt.Sprintf("invalid method '%s', please retry with 'POST'", httpRequest.Method)), + tutusrpc.NewInvalidParamsError(fmt.Sprintf("invalid method '%s', please retry with 'POST'", httpRequest.Method)), ) return } err := req.DecodeData(httpRequest.Body) if err != nil { - s.writeHTTPErrorResponse(params.NewIn(), w, neorpc.NewParseError(err.Error())) + s.writeHTTPErrorResponse(params.NewIn(), w, tutusrpc.NewParseError(err.Error())) return } @@ -566,14 +566,14 @@ func (s *Server) handleHTTPRequest(w http.ResponseWriter, httpRequest *http.Requ // RegisterLocal performs local client registration. Events channel will be // closed by server once context is done or server is closed. -func (s *Server) RegisterLocal(ctx context.Context, events chan<- neorpc.Notification) func(*neorpc.Request) (*neorpc.Response, error) { +func (s *Server) RegisterLocal(ctx context.Context, events chan<- tutusrpc.Notification) func(*tutusrpc.Request) (*tutusrpc.Response, error) { subChan := make(chan intEvent, notificationBufSize) subscr := &subscriber{writer: subChan, feeds: make([]feed, s.config.MaxWebSocketFeeds)} s.subsLock.Lock() s.subscribers[subscr] = true s.subsLock.Unlock() go s.handleLocalNotifications(ctx, events, subChan, subscr) - return func(req *neorpc.Request) (*neorpc.Response, error) { + return func(req *tutusrpc.Request) (*tutusrpc.Response, error) { return s.handleInternal(req, subscr) } } @@ -592,12 +592,12 @@ func (s *Server) handleRequest(req *params.Request, sub *subscriber) abstractRes } // handleInternal is an experimental interface to handle client requests directly. -func (s *Server) handleInternal(req *neorpc.Request, sub *subscriber) (*neorpc.Response, error) { +func (s *Server) handleInternal(req *tutusrpc.Request, sub *subscriber) (*tutusrpc.Response, error) { var ( res any - rpcRes = &neorpc.Response{ - HeaderAndError: neorpc.HeaderAndError{ - Header: neorpc.Header{ + rpcRes = &tutusrpc.Response{ + HeaderAndError: tutusrpc.HeaderAndError{ + Header: tutusrpc.Header{ JSONRPC: req.JSONRPC, ID: json.RawMessage(strconv.FormatUint(req.ID, 10)), }, @@ -616,7 +616,7 @@ func (s *Server) handleInternal(req *neorpc.Request, sub *subscriber) (*neorpc.R start := time.Now() defer func() { addReqTimeMetric(req.Method, time.Since(start)) }() - rpcRes.Error = neorpc.NewMethodNotFoundError(fmt.Sprintf("method %q not supported", req.Method)) + rpcRes.Error = tutusrpc.NewMethodNotFoundError(fmt.Sprintf("method %q not supported", req.Method)) handler, ok := rpcHandlers[req.Method] if ok { res, rpcRes.Error = handler(s, reqParams) @@ -638,9 +638,9 @@ func (s *Server) handleInternal(req *neorpc.Request, sub *subscriber) (*neorpc.R func (s *Server) handleIn(req *params.In, sub *subscriber) abstract { var res any - var resErr *neorpc.Error - if req.JSONRPC != neorpc.JSONRPCVersion { - return s.packResponse(req, nil, neorpc.NewInvalidParamsError(fmt.Sprintf("problem parsing JSON: invalid version, expected 2.0 got '%s'", req.JSONRPC))) + var resErr *tutusrpc.Error + if req.JSONRPC != tutusrpc.JSONRPCVersion { + return s.packResponse(req, nil, tutusrpc.NewInvalidParamsError(fmt.Sprintf("problem parsing JSON: invalid version, expected 2.0 got '%s'", req.JSONRPC))) } reqParams := params.Params(req.RawParams) @@ -652,7 +652,7 @@ func (s *Server) handleIn(req *params.In, sub *subscriber) abstract { start := time.Now() defer func() { addReqTimeMetric(req.Method, time.Since(start)) }() - resErr = neorpc.NewMethodNotFoundError(fmt.Sprintf("method %q not supported", req.Method)) + resErr = tutusrpc.NewMethodNotFoundError(fmt.Sprintf("method %q not supported", req.Method)) handler, ok := rpcHandlers[req.Method] if ok { res, resErr = handler(s, reqParams) @@ -665,7 +665,7 @@ func (s *Server) handleIn(req *params.In, sub *subscriber) abstract { return s.packResponse(req, res, resErr) } -func (s *Server) handleLocalNotifications(ctx context.Context, events chan<- neorpc.Notification, subChan <-chan intEvent, subscr *subscriber) { +func (s *Server) handleLocalNotifications(ctx context.Context, events chan<- tutusrpc.Notification, subChan <-chan intEvent, subscr *subscriber) { eventloop: for { select { @@ -753,7 +753,7 @@ requestloop: break } res := s.handleRequest(req, subscr) - res.RunForErrors(func(jsonErr *neorpc.Error) { + res.RunForErrors(func(jsonErr *tutusrpc.Error) { s.logRequestError(req, jsonErr) }) select { @@ -773,36 +773,36 @@ func (s *Server) dropSubscriber(subscr *subscriber) { s.subsLock.Unlock() s.subsCounterLock.Lock() for _, e := range subscr.feeds { - if e.event != neorpc.InvalidEventID { + if e.event != tutusrpc.InvalidEventID { s.unsubscribeFromChannel(e.event) } } s.subsCounterLock.Unlock() } -func (s *Server) getBestBlockHash(_ params.Params) (any, *neorpc.Error) { +func (s *Server) getBestBlockHash(_ params.Params) (any, *tutusrpc.Error) { return "0x" + s.chain.CurrentBlockHash().StringLE(), nil } -func (s *Server) getBlockCount(_ params.Params) (any, *neorpc.Error) { +func (s *Server) getBlockCount(_ params.Params) (any, *tutusrpc.Error) { return s.chain.BlockHeight() + 1, nil } -func (s *Server) getBlockHeaderCount(_ params.Params) (any, *neorpc.Error) { +func (s *Server) getBlockHeaderCount(_ params.Params) (any, *tutusrpc.Error) { return s.chain.HeaderHeight() + 1, nil } -func (s *Server) getConnectionCount(_ params.Params) (any, *neorpc.Error) { +func (s *Server) getConnectionCount(_ params.Params) (any, *tutusrpc.Error) { return s.coreServer.PeerCount(), nil } -func (s *Server) blockHashFromParam(param *params.Param) (util.Uint256, *neorpc.Error) { +func (s *Server) blockHashFromParam(param *params.Param) (util.Uint256, *tutusrpc.Error) { var ( hash util.Uint256 err error ) if param == nil { - return hash, neorpc.ErrInvalidParams + return hash, tutusrpc.ErrInvalidParams } if hash, err = param.GetUint256(); err != nil { @@ -828,7 +828,7 @@ func (s *Server) fillBlockMetadata(obj io.Serializable, h *block.Header) result. return res } -func (s *Server) getBlock(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) getBlock(reqParams params.Params) (any, *tutusrpc.Error) { param := reqParams.Value(0) hash, respErr := s.blockHashFromParam(param) if respErr != nil { @@ -837,7 +837,7 @@ func (s *Server) getBlock(reqParams params.Params) (any, *neorpc.Error) { block, err := s.chain.GetBlock(hash) if err != nil { - return nil, neorpc.WrapErrorWithData(neorpc.ErrUnknownBlock, err.Error()) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrUnknownBlock, err.Error()) } if v, _ := reqParams.Value(1).GetBoolean(); v { @@ -852,7 +852,7 @@ func (s *Server) getBlock(reqParams params.Params) (any, *neorpc.Error) { return writer.Bytes(), nil } -func (s *Server) getBlockHash(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) getBlockHash(reqParams params.Params) (any, *tutusrpc.Error) { num, err := s.blockHeightFromParam(reqParams.Value(0)) if err != nil { return nil, err @@ -861,10 +861,10 @@ func (s *Server) getBlockHash(reqParams params.Params) (any, *neorpc.Error) { return s.chain.GetHeaderHash(num), nil } -func (s *Server) getVersion(_ params.Params) (any, *neorpc.Error) { +func (s *Server) getVersion(_ params.Params) (any, *tutusrpc.Error) { port, err := s.coreServer.Port(nil) // any port will suite if err != nil { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("cannot fetch tcp port: %s", err)) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("cannot fetch tcp port: %s", err)) } cfg := s.chain.GetConfig() @@ -878,7 +878,7 @@ func (s *Server) getVersion(_ params.Params) (any, *neorpc.Error) { } standbyCommittee, err := keys.NewPublicKeysFromStrings(cfg.StandbyCommittee) if err != nil { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("cannot fetch standbyCommittee: %s", err)) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("cannot fetch standbyCommittee: %s", err)) } return &result.Version{ TCPPort: port, @@ -916,7 +916,7 @@ func (s *Server) getVersion(_ params.Params) (any, *neorpc.Error) { }, nil } -func (s *Server) getPeers(_ params.Params) (any, *neorpc.Error) { +func (s *Server) getPeers(_ params.Params) (any, *tutusrpc.Error) { peers := result.NewGetPeers() peers.AddUnconnected(s.coreServer.UnconnectedPeers()) peers.AddConnected(s.coreServer.ConnectedPeers()) @@ -924,7 +924,7 @@ func (s *Server) getPeers(_ params.Params) (any, *neorpc.Error) { return peers, nil } -func (s *Server) getRawMempool(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) getRawMempool(reqParams params.Params) (any, *tutusrpc.Error) { verbose, _ := reqParams.Value(0).GetBoolean() mp := s.chain.GetMemPool() txes := mp.GetVerifiedTransactions() @@ -942,10 +942,10 @@ func (s *Server) getRawMempool(reqParams params.Params) (any, *neorpc.Error) { }, nil } -func (s *Server) validateAddress(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) validateAddress(reqParams params.Params) (any, *tutusrpc.Error) { param, err := reqParams.Value(0).GetString() if err != nil { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } return result.ValidateAddress{ @@ -955,21 +955,21 @@ func (s *Server) validateAddress(reqParams params.Params) (any, *neorpc.Error) { } // calculateNetworkFee calculates network fee for the transaction. -func (s *Server) calculateNetworkFee(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) calculateNetworkFee(reqParams params.Params) (any, *tutusrpc.Error) { if len(reqParams) < 1 { - return 0, neorpc.ErrInvalidParams + return 0, tutusrpc.ErrInvalidParams } byteTx, err := reqParams[0].GetBytesBase64() if err != nil { - return 0, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, err.Error()) + return 0, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, err.Error()) } tx, err := transaction.NewTransactionFromBytes(byteTx) if err != nil { - return 0, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, err.Error()) + return 0, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, err.Error()) } hashablePart, err := tx.EncodeHashableFields() if err != nil { - return 0, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("failed to compute tx size: %s", err)) + return 0, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, fmt.Sprintf("failed to compute tx size: %s", err)) } size := len(hashablePart) + io.GetVarSize(len(tx.Signers)) var ( @@ -984,11 +984,11 @@ func (s *Server) calculateNetworkFee(reqParams params.Params) (any, *neorpc.Erro if len(w.VerificationScript) == 0 { // Contract-based verification cs := s.chain.GetContractState(signer.Account) if cs == nil { - return 0, neorpc.WrapErrorWithData(neorpc.ErrInvalidVerificationFunction, fmt.Sprintf("signer %d (%s) has no verification script and no deployed contract", i, address.Uint160ToString(signer.Account))) + return 0, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidVerificationFunction, fmt.Sprintf("signer %d (%s) has no verification script and no deployed contract", i, address.Uint160ToString(signer.Account))) } md := cs.Manifest.ABI.GetMethod(manifest.MethodVerify, -1) if md == nil || md.ReturnType != smartcontract.BoolType { - return 0, neorpc.WrapErrorWithData(neorpc.ErrInvalidVerificationFunction, fmt.Sprintf("signer %d has no verify method in deployed contract", i)) + return 0, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidVerificationFunction, fmt.Sprintf("signer %d has no verify method in deployed contract", i)) } paramz = md.Parameters // Might as well have none params and it's OK. } else { // Regular signature verification. @@ -1006,13 +1006,13 @@ func (s *Server) calculateNetworkFee(reqParams params.Params) (any, *neorpc.Erro p.Type.EncodeDefaultValue(inv.BinWriter) } if inv.Err != nil { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to create dummy invocation script (signer %d): %s", i, inv.Err.Error())) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("failed to create dummy invocation script (signer %d): %s", i, inv.Err.Error())) } w.InvocationScript = inv.Bytes() } gasConsumed, err := s.chain.VerifyWitness(signer.Account, tx, &w, gasLimit) if err != nil && !errors.Is(err, core.ErrInvalidSignature) { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidSignature, fmt.Sprintf("witness %d: %s", i, err)) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidSignature, fmt.Sprintf("witness %d: %s", i, err)) } gasLimit -= gasConsumed netFee += gasConsumed @@ -1023,27 +1023,27 @@ func (s *Server) calculateNetworkFee(reqParams params.Params) (any, *neorpc.Erro } // getApplicationLog returns the contract log based on the specified txid or blockid. -func (s *Server) getApplicationLog(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) getApplicationLog(reqParams params.Params) (any, *tutusrpc.Error) { hash, err := reqParams.Value(0).GetUint256() if err != nil { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } trig := trigger.All if len(reqParams) > 1 { trigString, err := reqParams.Value(1).GetString() if err != nil { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } trig, err = trigger.FromString(trigString) if err != nil { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } } appExecResults, err := s.chain.GetAppExecResults(hash, trigger.All) if err != nil { - return nil, neorpc.WrapErrorWithData(neorpc.ErrUnknownScriptContainer, fmt.Sprintf("failed to locate application log: %s", err)) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrUnknownScriptContainer, fmt.Sprintf("failed to locate application log: %s", err)) } return result.NewApplicationLog(hash, appExecResults, trig), nil } @@ -1072,10 +1072,10 @@ func (s *Server) getNEP11Tokens(h util.Uint160, acc util.Uint160, bw *io.BufBinW return vals, sym, int(dec.Int64()), nil } -func (s *Server) getNEP11Balances(ps params.Params) (any, *neorpc.Error) { +func (s *Server) getNEP11Balances(ps params.Params) (any, *tutusrpc.Error) { u, err := ps.Value(0).GetUint160FromAddressOrHex() if err != nil { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } bs := &result.NEP11Balances{ @@ -1084,7 +1084,7 @@ func (s *Server) getNEP11Balances(ps params.Params) (any, *neorpc.Error) { } lastUpdated, err := s.chain.GetTokenLastUpdated(u) if err != nil { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("Failed to get NEP-11 last updated block: %s", err.Error())) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("Failed to get NEP-11 last updated block: %s", err.Error())) } var count int stateSyncPoint := lastUpdated[math.MinInt32] @@ -1107,7 +1107,7 @@ contract_loop: if !ok { cfg := s.chain.GetConfig() if !cfg.P2PStateExchangeExtensions && cfg.RemoveUntraceableBlocks { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to get LastUpdatedBlock for balance of %s token: internal database inconsistency", cs.Hash.StringLE())) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("failed to get LastUpdatedBlock for balance of %s token: internal database inconsistency", cs.Hash.StringLE())) } lub = stateSyncPoint } @@ -1161,18 +1161,18 @@ func (s *Server) invokeNEP11Properties(h util.Uint160, id []byte, bw *io.BufBinW return item.Value().([]stackitem.MapElement), nil } -func (s *Server) getNEP11Properties(ps params.Params) (any, *neorpc.Error) { +func (s *Server) getNEP11Properties(ps params.Params) (any, *tutusrpc.Error) { asset, err := ps.Value(0).GetUint160FromAddressOrHex() if err != nil { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } token, err := ps.Value(1).GetBytesHex() if err != nil { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } props, err := s.invokeNEP11Properties(asset, token, nil) if err != nil { - return nil, neorpc.WrapErrorWithData(neorpc.ErrExecutionFailed, fmt.Sprintf("Failed to get NEP-11 properties: %s", err.Error())) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrExecutionFailed, fmt.Sprintf("Failed to get NEP-11 properties: %s", err.Error())) } res := make(map[string]any) for _, kv := range props { @@ -1197,10 +1197,10 @@ func (s *Server) getNEP11Properties(ps params.Params) (any, *neorpc.Error) { return res, nil } -func (s *Server) getNEP17Balances(ps params.Params) (any, *neorpc.Error) { +func (s *Server) getNEP17Balances(ps params.Params) (any, *tutusrpc.Error) { u, err := ps.Value(0).GetUint160FromAddressOrHex() if err != nil { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } bs := &result.NEP17Balances{ @@ -1209,7 +1209,7 @@ func (s *Server) getNEP17Balances(ps params.Params) (any, *neorpc.Error) { } lastUpdated, err := s.chain.GetTokenLastUpdated(u) if err != nil { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("Failed to get NEP-17 last updated block: %s", err.Error())) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("Failed to get NEP-17 last updated block: %s", err.Error())) } stateSyncPoint := lastUpdated[math.MinInt32] bw := io.NewBufBinWriter() @@ -1229,7 +1229,7 @@ func (s *Server) getNEP17Balances(ps params.Params) (any, *neorpc.Error) { if !ok { cfg := s.chain.GetConfig() if !cfg.P2PStateExchangeExtensions && cfg.RemoveUntraceableBlocks { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to get LastUpdatedBlock for balance of %s token: internal database inconsistency", cs.Hash.StringLE())) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("failed to get LastUpdatedBlock for balance of %s token: internal database inconsistency", cs.Hash.StringLE())) } lub = stateSyncPoint } @@ -1376,23 +1376,23 @@ func getTimestampsAndLimit(ps params.Params, index int) (uint64, uint64, int, in return start, end, limit, page, nil } -func (s *Server) getNEP11Transfers(ps params.Params) (any, *neorpc.Error) { +func (s *Server) getNEP11Transfers(ps params.Params) (any, *tutusrpc.Error) { return s.getTokenTransfers(ps, true) } -func (s *Server) getNEP17Transfers(ps params.Params) (any, *neorpc.Error) { +func (s *Server) getNEP17Transfers(ps params.Params) (any, *tutusrpc.Error) { return s.getTokenTransfers(ps, false) } -func (s *Server) getTokenTransfers(ps params.Params, isNEP11 bool) (any, *neorpc.Error) { +func (s *Server) getTokenTransfers(ps params.Params, isNEP11 bool) (any, *tutusrpc.Error) { u, err := ps.Value(0).GetUint160FromAddressOrHex() if err != nil { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } start, end, limit, page, err := getTimestampsAndLimit(ps, 1) if err != nil { - return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("malformed timestamps/limit: %s", err)) + return nil, tutusrpc.NewInvalidParamsError(fmt.Sprintf("malformed timestamps/limit: %s", err)) } bs := &tokenTransfers{ @@ -1480,7 +1480,7 @@ func (s *Server) getTokenTransfers(ps params.Params, isNEP11 bool) (any, *neorpc }) } if err != nil { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("invalid transfer log: %s", err)) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("invalid transfer log: %s", err)) } return bs, nil } @@ -1498,16 +1498,16 @@ func (s *Server) getHash(contractID int32, cache map[int32]util.Uint160) (util.U return h, nil } -func (s *Server) contractIDFromParam(param *params.Param, root ...util.Uint256) (int32, *neorpc.Error) { +func (s *Server) contractIDFromParam(param *params.Param, root ...util.Uint256) (int32, *tutusrpc.Error) { var result int32 if param == nil { - return 0, neorpc.ErrInvalidParams + return 0, tutusrpc.ErrInvalidParams } if scriptHash, err := param.GetUint160FromHex(); err == nil { if len(root) == 0 { cs := s.chain.GetContractState(scriptHash) if cs == nil { - return 0, neorpc.ErrUnknownContract + return 0, tutusrpc.ErrUnknownContract } result = cs.ID } else { @@ -1520,10 +1520,10 @@ func (s *Server) contractIDFromParam(param *params.Param, root ...util.Uint256) } else { id, err := param.GetInt() if err != nil { - return 0, neorpc.ErrInvalidParams + return 0, tutusrpc.ErrInvalidParams } if err := checkInt32(id); err != nil { - return 0, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, err.Error()) + return 0, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, err.Error()) } result = int32(id) } @@ -1531,14 +1531,14 @@ func (s *Server) contractIDFromParam(param *params.Param, root ...util.Uint256) } // contractScriptHashFromParam returns the contract script hash by hex contract hash, address, id or native contract name. -func (s *Server) contractScriptHashFromParam(param *params.Param) (util.Uint160, *neorpc.Error) { +func (s *Server) contractScriptHashFromParam(param *params.Param) (util.Uint160, *tutusrpc.Error) { var result util.Uint160 if param == nil { - return result, neorpc.ErrInvalidParams + return result, tutusrpc.ErrInvalidParams } nameOrHashOrIndex, err := param.GetString() if err != nil { - return result, neorpc.ErrInvalidParams + return result, tutusrpc.ErrInvalidParams } result, err = param.GetUint160FromAddressOrHex() if err == nil { @@ -1550,14 +1550,14 @@ func (s *Server) contractScriptHashFromParam(param *params.Param) (util.Uint160, } id, err := strconv.Atoi(nameOrHashOrIndex) if err != nil { - return result, neorpc.NewInvalidParamsError(fmt.Sprintf("Invalid contract identifier (name/hash/index is expected) : %s", err.Error())) + return result, tutusrpc.NewInvalidParamsError(fmt.Sprintf("Invalid contract identifier (name/hash/index is expected) : %s", err.Error())) } if err := checkInt32(id); err != nil { - return result, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, err.Error()) + return result, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, err.Error()) } result, err = s.chain.GetContractScriptHash(int32(id)) if err != nil { - return result, neorpc.ErrUnknownContract + return result, tutusrpc.ErrUnknownContract } return result, nil } @@ -1571,21 +1571,21 @@ func makeStorageKey(id int32, key []byte) []byte { var errKeepOnlyLatestState = errors.New("'KeepOnlyLatestState' setting is enabled") -func (s *Server) getProof(ps params.Params) (any, *neorpc.Error) { +func (s *Server) getProof(ps params.Params) (any, *tutusrpc.Error) { if s.chain.GetConfig().KeepOnlyLatestState { - return nil, neorpc.WrapErrorWithData(neorpc.ErrUnsupportedState, fmt.Sprintf("'getproof' is not supported: %s", errKeepOnlyLatestState)) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrUnsupportedState, fmt.Sprintf("'getproof' is not supported: %s", errKeepOnlyLatestState)) } root, err := ps.Value(0).GetUint256() if err != nil { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } sc, err := ps.Value(1).GetUint160FromHex() if err != nil { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } key, err := ps.Value(2).GetBytesBase64() if err != nil { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } cs, respErr := s.getHistoricalContractState(root, sc) if respErr != nil { @@ -1595,9 +1595,9 @@ func (s *Server) getProof(ps params.Params) (any, *neorpc.Error) { proof, err := s.chain.GetStateModule().GetStateProof(root, skey) if err != nil { if errors.Is(err, mpt.ErrNotFound) { - return nil, neorpc.ErrUnknownStorageItem + return nil, tutusrpc.ErrUnknownStorageItem } - return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to get proof: %s", err)) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("failed to get proof: %s", err)) } return &result.ProofWithKey{ Key: skey, @@ -1605,43 +1605,43 @@ func (s *Server) getProof(ps params.Params) (any, *neorpc.Error) { }, nil } -func (s *Server) verifyProof(ps params.Params) (any, *neorpc.Error) { +func (s *Server) verifyProof(ps params.Params) (any, *tutusrpc.Error) { if s.chain.GetConfig().KeepOnlyLatestState { - return nil, neorpc.WrapErrorWithData(neorpc.ErrUnsupportedState, fmt.Sprintf("'verifyproof' is not supported: %s", errKeepOnlyLatestState)) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrUnsupportedState, fmt.Sprintf("'verifyproof' is not supported: %s", errKeepOnlyLatestState)) } root, err := ps.Value(0).GetUint256() if err != nil { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } proofStr, err := ps.Value(1).GetString() if err != nil { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } var p result.ProofWithKey if err := p.FromString(proofStr); err != nil { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } vp := new(result.VerifyProof) val, ok := mpt.VerifyProof(root, p.Key, p.Proof) if !ok { - return nil, neorpc.ErrInvalidProof + return nil, tutusrpc.ErrInvalidProof } vp.Value = val return vp, nil } -func (s *Server) getState(ps params.Params) (any, *neorpc.Error) { +func (s *Server) getState(ps params.Params) (any, *tutusrpc.Error) { root, respErr := s.getStateRootFromParam(ps.Value(0)) if respErr != nil { return nil, respErr } csHash, err := ps.Value(1).GetUint160FromHex() if err != nil { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, "invalid contract hash") + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, "invalid contract hash") } key, err := ps.Value(2).GetBytesBase64() if err != nil { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, "invalid key") + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, "invalid key") } cs, respErr := s.getHistoricalContractState(root, csHash) if respErr != nil { @@ -1651,25 +1651,25 @@ func (s *Server) getState(ps params.Params) (any, *neorpc.Error) { res, err := s.chain.GetStateModule().GetState(root, sKey) if err != nil { if errors.Is(err, mpt.ErrNotFound) { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("invalid key: %s", err.Error())) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, fmt.Sprintf("invalid key: %s", err.Error())) } - return nil, neorpc.NewInternalServerError(fmt.Sprintf("Failed to get historical item state: %s", err.Error())) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("Failed to get historical item state: %s", err.Error())) } return res, nil } -func (s *Server) findStates(ps params.Params) (any, *neorpc.Error) { +func (s *Server) findStates(ps params.Params) (any, *tutusrpc.Error) { root, respErr := s.getStateRootFromParam(ps.Value(0)) if respErr != nil { return nil, respErr } csHash, err := ps.Value(1).GetUint160FromHex() if err != nil { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("invalid contract hash: %s", err)) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, fmt.Sprintf("invalid contract hash: %s", err)) } prefix, err := ps.Value(2).GetBytesBase64() if err != nil { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("invalid prefix: %s", err)) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, fmt.Sprintf("invalid prefix: %s", err)) } var ( key []byte @@ -1678,11 +1678,11 @@ func (s *Server) findStates(ps params.Params) (any, *neorpc.Error) { if len(ps) > 3 { key, err = ps.Value(3).GetBytesBase64() if err != nil { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("invalid key: %s", err)) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, fmt.Sprintf("invalid key: %s", err)) } if len(key) > 0 { if !bytes.HasPrefix(key, prefix) { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, "key doesn't match prefix") + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, "key doesn't match prefix") } key = key[len(prefix):] } else { @@ -1693,7 +1693,7 @@ func (s *Server) findStates(ps params.Params) (any, *neorpc.Error) { if len(ps) > 4 { count, err = ps.Value(4).GetInt() if err != nil { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("invalid count: %s", err)) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, fmt.Sprintf("invalid count: %s", err)) } count = min(count, s.config.MaxFindResultItems) } @@ -1704,7 +1704,7 @@ func (s *Server) findStates(ps params.Params) (any, *neorpc.Error) { pKey := makeStorageKey(cs.ID, prefix) kvs, err := s.chain.GetStateModule().FindStates(root, pKey, key, count+1) // +1 to define result truncation if err != nil && !errors.Is(err, mpt.ErrNotFound) { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to find state items: %s", err)) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("failed to find state items: %s", err)) } res := result.FindStates{} if len(kvs) == count+1 { @@ -1714,7 +1714,7 @@ func (s *Server) findStates(ps params.Params) (any, *neorpc.Error) { if len(kvs) > 0 { proof, err := s.chain.GetStateModule().GetStateProof(root, kvs[0].Key) if err != nil { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to get first proof: %s", err)) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("failed to get first proof: %s", err)) } res.FirstProof = &result.ProofWithKey{ Key: kvs[0].Key, @@ -1724,7 +1724,7 @@ func (s *Server) findStates(ps params.Params) (any, *neorpc.Error) { if len(kvs) > 1 { proof, err := s.chain.GetStateModule().GetStateProof(root, kvs[len(kvs)-1].Key) if err != nil { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to get last proof: %s", err)) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("failed to get last proof: %s", err)) } res.LastProof = &result.ProofWithKey{ Key: kvs[len(kvs)-1].Key, @@ -1744,24 +1744,24 @@ func (s *Server) findStates(ps params.Params) (any, *neorpc.Error) { // getStateRootFromParam retrieves state root hash from the provided parameter // (only util.Uint256 serialized representation is allowed) and checks whether // MPT states are supported for the old stateroot. -func (s *Server) getStateRootFromParam(p *params.Param) (util.Uint256, *neorpc.Error) { +func (s *Server) getStateRootFromParam(p *params.Param) (util.Uint256, *tutusrpc.Error) { root, err := p.GetUint256() if err != nil { - return util.Uint256{}, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, "invalid stateroot") + return util.Uint256{}, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, "invalid stateroot") } if s.chain.GetConfig().KeepOnlyLatestState { curr, err := s.chain.GetStateModule().GetStateRoot(s.chain.BlockHeight()) if err != nil { - return util.Uint256{}, neorpc.NewInternalServerError(fmt.Sprintf("failed to get current stateroot: %s", err)) + return util.Uint256{}, tutusrpc.NewInternalServerError(fmt.Sprintf("failed to get current stateroot: %s", err)) } if !curr.Root.Equals(root) { - return util.Uint256{}, neorpc.WrapErrorWithData(neorpc.ErrUnsupportedState, fmt.Sprintf("state-based methods are not supported for old states: %s", errKeepOnlyLatestState)) + return util.Uint256{}, tutusrpc.WrapErrorWithData(tutusrpc.ErrUnsupportedState, fmt.Sprintf("state-based methods are not supported for old states: %s", errKeepOnlyLatestState)) } } return root, nil } -func (s *Server) findStorage(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) findStorage(reqParams params.Params) (any, *tutusrpc.Error) { id, prefix, start, take, respErr := s.getFindStorageParams(reqParams) if respErr != nil { return nil, respErr @@ -1769,7 +1769,7 @@ func (s *Server) findStorage(reqParams params.Params) (any, *neorpc.Error) { return s.findStorageInternal(id, prefix, start, take, s.chain) } -func (s *Server) findStorageInternal(id int32, prefix []byte, start, take int, seeker ContractStorageSeeker) (any, *neorpc.Error) { +func (s *Server) findStorageInternal(id int32, prefix []byte, start, take int, seeker ContractStorageSeeker) (any, *tutusrpc.Error) { var ( i int end = start + take @@ -1796,13 +1796,13 @@ func (s *Server) findStorageInternal(id int32, prefix []byte, start, take int, s return res, nil } -func (s *Server) findStorageHistoric(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) findStorageHistoric(reqParams params.Params) (any, *tutusrpc.Error) { root, respErr := s.getStateRootFromParam(reqParams.Value(0)) if respErr != nil { return nil, respErr } if len(reqParams) < 2 { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } id, prefix, start, take, respErr := s.getFindStorageParams(reqParams[1:], root) if respErr != nil { @@ -1826,9 +1826,9 @@ func (s mptStorageSeeker) SeekStorage(id int32, prefix []byte, cont func(k, v [] s.module.SeekStates(s.root, key, cont) } -func (s *Server) getFindStorageParams(reqParams params.Params, root ...util.Uint256) (int32, []byte, int, int, *neorpc.Error) { +func (s *Server) getFindStorageParams(reqParams params.Params, root ...util.Uint256) (int32, []byte, int, int, *tutusrpc.Error) { if len(reqParams) < 2 { - return 0, nil, 0, 0, neorpc.ErrInvalidParams + return 0, nil, 0, 0, tutusrpc.ErrInvalidParams } id, respErr := s.contractIDFromParam(reqParams.Value(0), root...) if respErr != nil { @@ -1837,34 +1837,34 @@ func (s *Server) getFindStorageParams(reqParams params.Params, root ...util.Uint prefix, err := reqParams.Value(1).GetBytesBase64() if err != nil { - return 0, nil, 0, 0, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("invalid prefix: %s", err)) + return 0, nil, 0, 0, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, fmt.Sprintf("invalid prefix: %s", err)) } var skip int if len(reqParams) > 2 { skip, err = reqParams.Value(2).GetInt() if err != nil { - return 0, nil, 0, 0, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("invalid start: %s", err)) + return 0, nil, 0, 0, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, fmt.Sprintf("invalid start: %s", err)) } } return id, prefix, skip, s.config.MaxFindStorageResultItems, nil } -func (s *Server) getHistoricalContractState(root util.Uint256, csHash util.Uint160) (*state.Contract, *neorpc.Error) { +func (s *Server) getHistoricalContractState(root util.Uint256, csHash util.Uint160) (*state.Contract, *tutusrpc.Error) { csKey := makeStorageKey(s.chain.NativeManagementID(), native.MakeContractKey(csHash)) csBytes, err := s.chain.GetStateModule().GetState(root, csKey) if err != nil { - return nil, neorpc.WrapErrorWithData(neorpc.ErrUnknownContract, fmt.Sprintf("Failed to get historical contract state: %s", err.Error())) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrUnknownContract, fmt.Sprintf("Failed to get historical contract state: %s", err.Error())) } contract := new(state.Contract) err = stackitem.DeserializeConvertible(csBytes, contract) if err != nil { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to deserialize historical contract state: %s", err)) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("failed to deserialize historical contract state: %s", err)) } return contract, nil } -func (s *Server) getStateHeight(_ params.Params) (any, *neorpc.Error) { +func (s *Server) getStateHeight(_ params.Params) (any, *tutusrpc.Error) { var height = s.chain.BlockHeight() var stateHeight = s.chain.GetStateModule().CurrentValidatedHeight() if s.chain.GetConfig().StateRootInHeader { @@ -1876,17 +1876,17 @@ func (s *Server) getStateHeight(_ params.Params) (any, *neorpc.Error) { }, nil } -func (s *Server) getStateRoot(ps params.Params) (any, *neorpc.Error) { +func (s *Server) getStateRoot(ps params.Params) (any, *tutusrpc.Error) { p := ps.Value(0) if p == nil { - return nil, neorpc.NewInvalidParamsError("missing stateroot identifier") + return nil, tutusrpc.NewInvalidParamsError("missing stateroot identifier") } var rt *state.MPTRoot var h util.Uint256 height, err := p.GetIntStrict() if err == nil { if err := checkUint32(height); err != nil { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, err.Error()) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, err.Error()) } rt, err = s.chain.GetStateModule().GetStateRoot(uint32(height)) } else if h, err = p.GetUint256(); err == nil { @@ -1897,12 +1897,12 @@ func (s *Server) getStateRoot(ps params.Params) (any, *neorpc.Error) { } } if err != nil { - return nil, neorpc.ErrUnknownStateRoot + return nil, tutusrpc.ErrUnknownStateRoot } return rt, nil } -func (s *Server) getStorage(ps params.Params) (any, *neorpc.Error) { +func (s *Server) getStorage(ps params.Params) (any, *tutusrpc.Error) { id, rErr := s.contractIDFromParam(ps.Value(0)) if rErr != nil { return nil, rErr @@ -1910,24 +1910,24 @@ func (s *Server) getStorage(ps params.Params) (any, *neorpc.Error) { key, err := ps.Value(1).GetBytesBase64() if err != nil { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } item := s.chain.GetStorageItem(id, key) if item == nil { - return "", neorpc.ErrUnknownStorageItem + return "", tutusrpc.ErrUnknownStorageItem } return []byte(item), nil } -func (s *Server) getStorageHistoric(ps params.Params) (any, *neorpc.Error) { +func (s *Server) getStorageHistoric(ps params.Params) (any, *tutusrpc.Error) { root, respErr := s.getStateRootFromParam(ps.Value(0)) if respErr != nil { return nil, respErr } if len(ps) < 2 { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } id, rErr := s.contractIDFromParam(ps.Value(1), root) @@ -1936,29 +1936,29 @@ func (s *Server) getStorageHistoric(ps params.Params) (any, *neorpc.Error) { } key, err := ps.Value(2).GetBytesBase64() if err != nil { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } pKey := makeStorageKey(id, key) v, err := s.chain.GetStateModule().GetState(root, pKey) if err != nil && !errors.Is(err, mpt.ErrNotFound) { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to get state item: %s", err)) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("failed to get state item: %s", err)) } if v == nil { - return "", neorpc.ErrUnknownStorageItem + return "", tutusrpc.ErrUnknownStorageItem } return v, nil } -func (s *Server) getrawtransaction(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) getrawtransaction(reqParams params.Params) (any, *tutusrpc.Error) { txHash, err := reqParams.Value(0).GetUint256() if err != nil { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } tx, height, err := s.chain.GetTransaction(txHash) if err != nil { - return nil, neorpc.ErrUnknownTransaction + return nil, tutusrpc.ErrUnknownTransaction } if v, _ := reqParams.Value(1).GetBoolean(); v { res := result.TransactionOutputRaw{ @@ -1970,14 +1970,14 @@ func (s *Server) getrawtransaction(reqParams params.Params) (any, *neorpc.Error) _header := s.chain.GetHeaderHash(height) header, err := s.chain.GetHeader(_header) if err != nil { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("Failed to get header for the transaction: %s", err.Error())) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("Failed to get header for the transaction: %s", err.Error())) } aers, err := s.chain.GetAppExecResults(txHash, trigger.Application) if err != nil { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("Failed to get application log for the transaction: %s", err.Error())) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("Failed to get application log for the transaction: %s", err.Error())) } if len(aers) == 0 { - return nil, neorpc.NewInternalServerError("Inconsistent application log: application log for the transaction is empty") + return nil, tutusrpc.NewInternalServerError("Inconsistent application log: application log for the transaction is empty") } res.TransactionMetadata = result.TransactionMetadata{ Blockhash: header.Hash(), @@ -1990,15 +1990,15 @@ func (s *Server) getrawtransaction(reqParams params.Params) (any, *neorpc.Error) return tx.Bytes(), nil } -func (s *Server) getTransactionHeight(ps params.Params) (any, *neorpc.Error) { +func (s *Server) getTransactionHeight(ps params.Params) (any, *tutusrpc.Error) { h, err := ps.Value(0).GetUint256() if err != nil { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } _, height, err := s.chain.GetTransaction(h) if err != nil || height == math.MaxUint32 { - return nil, neorpc.ErrUnknownTransaction + return nil, tutusrpc.ErrUnknownTransaction } return height, nil @@ -2006,33 +2006,33 @@ func (s *Server) getTransactionHeight(ps params.Params) (any, *neorpc.Error) { // getContractState returns contract state (contract information, according to the contract script hash, // contract id or native contract name). -func (s *Server) getContractState(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) getContractState(reqParams params.Params) (any, *tutusrpc.Error) { scriptHash, err := s.contractScriptHashFromParam(reqParams.Value(0)) if err != nil { return nil, err } cs := s.chain.GetContractState(scriptHash) if cs == nil { - return nil, neorpc.ErrUnknownContract + return nil, tutusrpc.ErrUnknownContract } return cs, nil } -func (s *Server) getNativeContracts(_ params.Params) (any, *neorpc.Error) { +func (s *Server) getNativeContracts(_ params.Params) (any, *tutusrpc.Error) { return s.chain.GetNatives(), nil } // getBlockSysFee returns the system fees of the block, based on the specified index. -func (s *Server) getBlockSysFee(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) getBlockSysFee(reqParams params.Params) (any, *tutusrpc.Error) { num, err := s.blockHeightFromParam(reqParams.Value(0)) if err != nil { - return 0, neorpc.WrapErrorWithData(err, fmt.Sprintf("invalid block height: %s", err.Data)) + return 0, tutusrpc.WrapErrorWithData(err, fmt.Sprintf("invalid block height: %s", err.Data)) } headerHash := s.chain.GetHeaderHash(num) block, errBlock := s.chain.GetBlock(headerHash) if errBlock != nil { - return 0, neorpc.ErrUnknownBlock + return 0, tutusrpc.ErrUnknownBlock } var blockSysFee int64 @@ -2044,7 +2044,7 @@ func (s *Server) getBlockSysFee(reqParams params.Params) (any, *neorpc.Error) { } // getBlockHeader returns the corresponding block header information according to the specified script hash. -func (s *Server) getBlockHeader(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) getBlockHeader(reqParams params.Params) (any, *tutusrpc.Error) { param := reqParams.Value(0) hash, respErr := s.blockHashFromParam(param) if respErr != nil { @@ -2054,7 +2054,7 @@ func (s *Server) getBlockHeader(reqParams params.Params) (any, *neorpc.Error) { verbose, _ := reqParams.Value(1).GetBoolean() h, err := s.chain.GetHeader(hash) if err != nil { - return nil, neorpc.ErrUnknownBlock + return nil, tutusrpc.ErrUnknownBlock } if verbose { @@ -2068,16 +2068,16 @@ func (s *Server) getBlockHeader(reqParams params.Params) (any, *neorpc.Error) { buf := io.NewBufBinWriter() h.EncodeBinary(buf.BinWriter) if buf.Err != nil { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("encoding error: %s", buf.Err)) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("encoding error: %s", buf.Err)) } return buf.Bytes(), nil } // getUnclaimedGas returns unclaimed GAS amount of the specified address. -func (s *Server) getUnclaimedGas(ps params.Params) (any, *neorpc.Error) { +func (s *Server) getUnclaimedGas(ps params.Params) (any, *tutusrpc.Error) { u, err := ps.Value(0).GetUint160FromAddressOrHex() if err != nil { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } neo, _ := s.chain.GetGoverningTokenBalance(u) @@ -2088,7 +2088,7 @@ func (s *Server) getUnclaimedGas(ps params.Params) (any, *neorpc.Error) { } gas, err := s.chain.CalculateClaimable(u, s.chain.BlockHeight()+1) // +1 as in C#, for the next block. if err != nil { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("Can't calculate claimable: %s", err.Error())) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("Can't calculate claimable: %s", err.Error())) } return result.UnclaimedGas{ Address: u, @@ -2097,16 +2097,16 @@ func (s *Server) getUnclaimedGas(ps params.Params) (any, *neorpc.Error) { } // getCandidates returns the current list of candidates with their active/inactive voting status. -func (s *Server) getCandidates(_ params.Params) (any, *neorpc.Error) { +func (s *Server) getCandidates(_ params.Params) (any, *tutusrpc.Error) { var validators keys.PublicKeys validators, err := s.chain.GetNextBlockValidators() if err != nil { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("Can't get next block validators: %s", err.Error())) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("Can't get next block validators: %s", err.Error())) } enrollments, err := s.chain.GetEnrollments() if err != nil { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("Can't get enrollments: %s", err.Error())) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("Can't get enrollments: %s", err.Error())) } var res = make([]result.Candidate, 0, len(enrollments)) for _, v := range enrollments { @@ -2120,14 +2120,14 @@ func (s *Server) getCandidates(_ params.Params) (any, *neorpc.Error) { } // getNextBlockValidators returns validators for the next block with voting status. -func (s *Server) getNextBlockValidators(_ params.Params) (any, *neorpc.Error) { +func (s *Server) getNextBlockValidators(_ params.Params) (any, *tutusrpc.Error) { validators, err := s.chain.GetNextBlockValidators() if err != nil { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("Can't get next block validators: %s", err.Error())) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("Can't get next block validators: %s", err.Error())) } enrollments, err := s.chain.GetEnrollments() if err != nil { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("Can't get enrollments: %s", err.Error())) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("Can't get enrollments: %s", err.Error())) } enrollmentVotes := make(map[keys.PublicKey]int64) for _, e := range enrollments { @@ -2148,16 +2148,16 @@ func (s *Server) getNextBlockValidators(_ params.Params) (any, *neorpc.Error) { } // getCommittee returns the current list of NEO committee members. -func (s *Server) getCommittee(_ params.Params) (any, *neorpc.Error) { +func (s *Server) getCommittee(_ params.Params) (any, *tutusrpc.Error) { keys, err := s.chain.GetCommittee() if err != nil { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("can't get committee members: %s", err)) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("can't get committee members: %s", err)) } return keys, nil } // invokeFunction implements the `invokeFunction` RPC call. -func (s *Server) invokeFunction(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) invokeFunction(reqParams params.Params) (any, *tutusrpc.Error) { tx, verbose, respErr := s.getInvokeFunctionParams(reqParams) if respErr != nil { return nil, respErr @@ -2166,13 +2166,13 @@ func (s *Server) invokeFunction(reqParams params.Params) (any, *neorpc.Error) { } // invokeFunctionHistoric implements the `invokeFunctionHistoric` RPC call. -func (s *Server) invokeFunctionHistoric(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) invokeFunctionHistoric(reqParams params.Params) (any, *tutusrpc.Error) { nextH, respErr := s.getHistoricParams(reqParams) if respErr != nil { return nil, respErr } if len(reqParams) < 2 { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } tx, verbose, respErr := s.getInvokeFunctionParams(reqParams[1:]) if respErr != nil { @@ -2181,9 +2181,9 @@ func (s *Server) invokeFunctionHistoric(reqParams params.Params) (any, *neorpc.E return s.runScriptInVM(trigger.Application, tx.Script, util.Uint160{}, tx, nil, &nextH, verbose) } -func (s *Server) getInvokeFunctionParams(reqParams params.Params) (*transaction.Transaction, bool, *neorpc.Error) { +func (s *Server) getInvokeFunctionParams(reqParams params.Params) (*transaction.Transaction, bool, *tutusrpc.Error) { if len(reqParams) < 2 { - return nil, false, neorpc.ErrInvalidParams + return nil, false, tutusrpc.ErrInvalidParams } scriptHash, responseErr := s.contractScriptHashFromParam(reqParams.Value(0)) if responseErr != nil { @@ -2191,7 +2191,7 @@ func (s *Server) getInvokeFunctionParams(reqParams params.Params) (*transaction. } method, err := reqParams[1].GetString() if err != nil { - return nil, false, neorpc.ErrInvalidParams + return nil, false, tutusrpc.ErrInvalidParams } var invparams *params.Param if len(reqParams) > 2 { @@ -2201,7 +2201,7 @@ func (s *Server) getInvokeFunctionParams(reqParams params.Params) (*transaction. if len(reqParams) > 3 { signers, _, err := reqParams[3].GetSignersWithWitnesses() if err != nil { - return nil, false, neorpc.ErrInvalidParams + return nil, false, tutusrpc.ErrInvalidParams } tx.Signers = signers } @@ -2209,7 +2209,7 @@ func (s *Server) getInvokeFunctionParams(reqParams params.Params) (*transaction. if len(reqParams) > 4 { verbose, err = reqParams[4].GetBoolean() if err != nil { - return nil, false, neorpc.ErrInvalidParams + return nil, false, tutusrpc.ErrInvalidParams } } if len(tx.Signers) == 0 { @@ -2217,14 +2217,14 @@ func (s *Server) getInvokeFunctionParams(reqParams params.Params) (*transaction. } script, err := params.CreateFunctionInvocationScript(scriptHash, method, invparams) if err != nil { - return nil, false, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("can't create invocation script: %s", err)) + return nil, false, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, fmt.Sprintf("can't create invocation script: %s", err)) } tx.Script = script return tx, verbose, nil } // invokescript implements the `invokescript` RPC call. -func (s *Server) invokescript(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) invokescript(reqParams params.Params) (any, *tutusrpc.Error) { tx, verbose, respErr := s.getInvokeScriptParams(reqParams) if respErr != nil { return nil, respErr @@ -2233,13 +2233,13 @@ func (s *Server) invokescript(reqParams params.Params) (any, *neorpc.Error) { } // invokescripthistoric implements the `invokescripthistoric` RPC call. -func (s *Server) invokescripthistoric(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) invokescripthistoric(reqParams params.Params) (any, *tutusrpc.Error) { nextH, respErr := s.getHistoricParams(reqParams) if respErr != nil { return nil, respErr } if len(reqParams) < 2 { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } tx, verbose, respErr := s.getInvokeScriptParams(reqParams[1:]) if respErr != nil { @@ -2248,17 +2248,17 @@ func (s *Server) invokescripthistoric(reqParams params.Params) (any, *neorpc.Err return s.runScriptInVM(trigger.Application, tx.Script, util.Uint160{}, tx, nil, &nextH, verbose) } -func (s *Server) getInvokeScriptParams(reqParams params.Params) (*transaction.Transaction, bool, *neorpc.Error) { +func (s *Server) getInvokeScriptParams(reqParams params.Params) (*transaction.Transaction, bool, *tutusrpc.Error) { script, err := reqParams.Value(0).GetBytesBase64() if err != nil { - return nil, false, neorpc.ErrInvalidParams + return nil, false, tutusrpc.ErrInvalidParams } tx := &transaction.Transaction{} if len(reqParams) > 1 { signers, witnesses, err := reqParams[1].GetSignersWithWitnesses() if err != nil { - return nil, false, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, err.Error()) + return nil, false, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, err.Error()) } tx.Signers = signers tx.Scripts = witnesses @@ -2267,7 +2267,7 @@ func (s *Server) getInvokeScriptParams(reqParams params.Params) (*transaction.Tr if len(reqParams) > 2 { verbose, err = reqParams[2].GetBoolean() if err != nil { - return nil, false, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, err.Error()) + return nil, false, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, err.Error()) } } if len(tx.Signers) == 0 { @@ -2277,26 +2277,26 @@ func (s *Server) getInvokeScriptParams(reqParams params.Params) (*transaction.Tr return tx, verbose, nil } -func (s *Server) fakeTxFromParam(p *params.Param) (*transaction.Transaction, *neorpc.Error) { +func (s *Server) fakeTxFromParam(p *params.Param) (*transaction.Transaction, *tutusrpc.Error) { tx, err := p.GetFakeTx() if err != nil { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("failed to unmarshal fake transaction: %s", err)) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, fmt.Sprintf("failed to unmarshal fake transaction: %s", err)) } if len(tx.Script) == 0 { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, "transaction script is mandatory") + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, "transaction script is mandatory") } return tx, nil } -func (s *Server) fakeBlockFromParam(p *params.Param) (*block.Block, *neorpc.Error) { +func (s *Server) fakeBlockFromParam(p *params.Param) (*block.Block, *tutusrpc.Error) { base, err := s.chain.GetFakeNextBlock(s.chain.BlockHeight() + 1) if err != nil { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to mock block execution container: %s", err)) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("failed to mock block execution container: %s", err)) } if p != nil && !p.IsNull() { h, err := p.GetFakeHeader() if err != nil { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("failed to unmarshal fake block: %s", err)) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, fmt.Sprintf("failed to unmarshal fake block: %s", err)) } // Override allowed base parameters with some sanity checks. @@ -2331,9 +2331,9 @@ func (s *Server) fakeBlockFromParam(p *params.Param) (*block.Block, *neorpc.Erro } // invokeContainedScript implements the `invokecontainedscript` RPC call. -func (s *Server) invokeContainedScript(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) invokeContainedScript(reqParams params.Params) (any, *tutusrpc.Error) { if len(reqParams) < 1 { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } tx, respErr := s.fakeTxFromParam(reqParams.Value(0)) if respErr != nil { @@ -2350,21 +2350,21 @@ func (s *Server) invokeContainedScript(reqParams params.Params) (any, *neorpc.Er if len(reqParams) > 2 { t, err := reqParams[2].GetString() if err != nil { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("invalid trigger parameter: %s", err)) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, fmt.Sprintf("invalid trigger parameter: %s", err)) } trig, err = trigger.FromString(t) if err != nil { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("failed to parse trigger: %s", err)) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, fmt.Sprintf("failed to parse trigger: %s", err)) } if trig != trigger.Application && trig != trigger.Verification { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("unsupported trigger: expected %s or %s, got %s", trigger.Application, trigger.Verification, trig)) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, fmt.Sprintf("unsupported trigger: expected %s or %s, got %s", trigger.Application, trigger.Verification, trig)) } } if len(reqParams) > 3 { var err error verbose, err = reqParams[3].GetBoolean() if err != nil { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("invalid verbose parameter: %s", err)) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, fmt.Sprintf("invalid verbose parameter: %s", err)) } } @@ -2372,7 +2372,7 @@ func (s *Server) invokeContainedScript(reqParams params.Params) (any, *neorpc.Er } // invokeContractVerify implements the `invokecontractverify` RPC call. -func (s *Server) invokeContractVerify(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) invokeContractVerify(reqParams params.Params) (any, *tutusrpc.Error) { scriptHash, tx, invocationScript, respErr := s.getInvokeContractVerifyParams(reqParams) if respErr != nil { return nil, respErr @@ -2381,13 +2381,13 @@ func (s *Server) invokeContractVerify(reqParams params.Params) (any, *neorpc.Err } // invokeContractVerifyHistoric implements the `invokecontractverifyhistoric` RPC call. -func (s *Server) invokeContractVerifyHistoric(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) invokeContractVerifyHistoric(reqParams params.Params) (any, *tutusrpc.Error) { nextH, respErr := s.getHistoricParams(reqParams) if respErr != nil { return nil, respErr } if len(reqParams) < 2 { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } scriptHash, tx, invocationScript, respErr := s.getInvokeContractVerifyParams(reqParams[1:]) if respErr != nil { @@ -2396,7 +2396,7 @@ func (s *Server) invokeContractVerifyHistoric(reqParams params.Params) (any, *ne return s.runScriptInVM(trigger.Verification, invocationScript, scriptHash, tx, nil, &nextH, false) } -func (s *Server) getInvokeContractVerifyParams(reqParams params.Params) (util.Uint160, *transaction.Transaction, []byte, *neorpc.Error) { +func (s *Server) getInvokeContractVerifyParams(reqParams params.Params) (util.Uint160, *transaction.Transaction, []byte, *tutusrpc.Error) { scriptHash, responseErr := s.contractScriptHashFromParam(reqParams.Value(0)) if responseErr != nil { return util.Uint160{}, nil, nil, responseErr @@ -2406,12 +2406,12 @@ func (s *Server) getInvokeContractVerifyParams(reqParams params.Params) (util.Ui if len(reqParams) > 1 { args, err := reqParams[1].GetArray() // second `invokecontractverify` parameter is an array of arguments for `verify` method if err != nil { - return util.Uint160{}, nil, nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, err.Error()) + return util.Uint160{}, nil, nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, err.Error()) } if len(args) > 0 { err := params.ExpandArrayIntoScript(bw.BinWriter, args) if err != nil { - return util.Uint160{}, nil, nil, neorpc.NewInternalServerError(fmt.Sprintf("can't create witness invocation script: %s", err)) + return util.Uint160{}, nil, nil, tutusrpc.NewInternalServerError(fmt.Sprintf("can't create witness invocation script: %s", err)) } } } @@ -2421,7 +2421,7 @@ func (s *Server) getInvokeContractVerifyParams(reqParams params.Params) (util.Ui if len(reqParams) > 2 { signers, witnesses, err := reqParams[2].GetSignersWithWitnesses() if err != nil { - return util.Uint160{}, nil, nil, neorpc.ErrInvalidParams + return util.Uint160{}, nil, nil, tutusrpc.ErrInvalidParams } tx.Signers = signers tx.Scripts = witnesses @@ -2436,24 +2436,24 @@ func (s *Server) getInvokeContractVerifyParams(reqParams params.Params) (util.Ui // a fake next block to perform the historic call. It also checks that // specified stateroot is stored at the specified height for further request // handling consistency. -func (s *Server) getHistoricParams(reqParams params.Params) (uint32, *neorpc.Error) { +func (s *Server) getHistoricParams(reqParams params.Params) (uint32, *tutusrpc.Error) { if s.chain.GetConfig().KeepOnlyLatestState { - return 0, neorpc.WrapErrorWithData(neorpc.ErrUnsupportedState, fmt.Sprintf("only latest state is supported: %s", errKeepOnlyLatestState)) + return 0, tutusrpc.WrapErrorWithData(tutusrpc.ErrUnsupportedState, fmt.Sprintf("only latest state is supported: %s", errKeepOnlyLatestState)) } if len(reqParams) < 1 { - return 0, neorpc.ErrInvalidParams + return 0, tutusrpc.ErrInvalidParams } height, respErr := s.blockHeightFromParam(reqParams.Value(0)) if respErr != nil { hash, err := reqParams.Value(0).GetUint256() if err != nil { - return 0, neorpc.NewInvalidParamsError(fmt.Sprintf("invalid block hash or index or stateroot hash: %s", err)) + return 0, tutusrpc.NewInvalidParamsError(fmt.Sprintf("invalid block hash or index or stateroot hash: %s", err)) } b, err := s.chain.GetBlock(hash) if err != nil { stateH, err := s.chain.GetStateModule().GetLatestStateHeight(hash) if err != nil { - return 0, neorpc.NewInvalidParamsError(fmt.Sprintf("unknown block or stateroot: %s", err)) + return 0, tutusrpc.NewInvalidParamsError(fmt.Sprintf("unknown block or stateroot: %s", err)) } height = stateH } else { @@ -2463,7 +2463,7 @@ func (s *Server) getHistoricParams(reqParams params.Params) (uint32, *neorpc.Err return height + 1, nil } -func (s *Server) prepareInvocationContext(t trigger.Type, script []byte, contractScriptHash util.Uint160, tx *transaction.Transaction, b *block.Block, nextH *uint32, verbose bool) (*interop.Context, *neorpc.Error) { +func (s *Server) prepareInvocationContext(t trigger.Type, script []byte, contractScriptHash util.Uint160, tx *transaction.Transaction, b *block.Block, nextH *uint32, verbose bool) (*interop.Context, *tutusrpc.Error) { var ( err error ic *interop.Context @@ -2471,12 +2471,12 @@ func (s *Server) prepareInvocationContext(t trigger.Type, script []byte, contrac if nextH == nil { ic, err = s.chain.GetTestVM(t, tx, b) if err != nil { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to create test VM: %s", err)) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("failed to create test VM: %s", err)) } } else { ic, err = s.chain.GetTestHistoricVM(t, tx, *nextH) if err != nil { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to create historic VM: %s", err)) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("failed to create historic VM: %s", err)) } } if verbose { @@ -2495,11 +2495,11 @@ func (s *Server) prepareInvocationContext(t trigger.Type, script []byte, contrac if err != nil { switch { case errors.Is(err, core.ErrUnknownVerificationContract): - return nil, neorpc.WrapErrorWithData(neorpc.ErrUnknownContract, err.Error()) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrUnknownContract, err.Error()) case errors.Is(err, core.ErrInvalidVerificationContract): - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidVerificationFunction, err.Error()) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidVerificationFunction, err.Error()) default: - return nil, neorpc.NewInternalServerError(fmt.Sprintf("can't prepare verification VM: %s", err)) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("can't prepare verification VM: %s", err)) } } } else { @@ -2514,7 +2514,7 @@ func (s *Server) prepareInvocationContext(t trigger.Type, script []byte, contrac // trigger (it pushes `verify` arguments on stack before verification). If block // is specified, it will be used to set up execution container parameters. In case // of contract verification contractScriptHash should be specified. -func (s *Server) runScriptInVM(t trigger.Type, script []byte, contractScriptHash util.Uint160, tx *transaction.Transaction, b *block.Block, nextH *uint32, verbose bool) (*result.Invoke, *neorpc.Error) { +func (s *Server) runScriptInVM(t trigger.Type, script []byte, contractScriptHash util.Uint160, tx *transaction.Transaction, b *block.Block, nextH *uint32, verbose bool) (*result.Invoke, *tutusrpc.Error) { ic, respErr := s.prepareInvocationContext(t, script, contractScriptHash, tx, b, nextH, verbose) if respErr != nil { return nil, respErr @@ -2556,7 +2556,7 @@ func (s *Server) runScriptInVM(t trigger.Type, script []byte, contractScriptHash if len(s.sessions) >= s.config.SessionPoolSize { ic.Finalize() s.sessionsLock.Unlock() - return nil, neorpc.NewInternalServerError("max session capacity reached") + return nil, tutusrpc.NewInternalServerError("max session capacity reached") } s.sessions[sessionID] = sess s.sessionsLock.Unlock() @@ -2646,34 +2646,34 @@ func (s *Server) registerOrDumpIterator(item stackitem.Item) (stackitem.Item, uu return stackitem.NewInterop(resIterator), iterID, curr } -func (s *Server) traverseIterator(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) traverseIterator(reqParams params.Params) (any, *tutusrpc.Error) { if !s.config.SessionEnabled { - return nil, neorpc.ErrSessionsDisabled + return nil, tutusrpc.ErrSessionsDisabled } sID, err := reqParams.Value(0).GetUUID() if err != nil { - return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("invalid session ID: %s", err)) + return nil, tutusrpc.NewInvalidParamsError(fmt.Sprintf("invalid session ID: %s", err)) } iID, err := reqParams.Value(1).GetUUID() if err != nil { - return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("invalid iterator ID: %s", err)) + return nil, tutusrpc.NewInvalidParamsError(fmt.Sprintf("invalid iterator ID: %s", err)) } count, err := reqParams.Value(2).GetInt() if err != nil { - return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("invalid iterator items count: %s", err)) + return nil, tutusrpc.NewInvalidParamsError(fmt.Sprintf("invalid iterator items count: %s", err)) } if err := checkInt32(count); err != nil { - return nil, neorpc.NewInvalidParamsError("invalid iterator items count: not an int32") + return nil, tutusrpc.NewInvalidParamsError("invalid iterator items count: not an int32") } if count > s.config.MaxIteratorResultItems { - return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("iterator items count (%d) is out of range (%d at max)", count, s.config.MaxIteratorResultItems)) + return nil, tutusrpc.NewInvalidParamsError(fmt.Sprintf("iterator items count (%d) is out of range (%d at max)", count, s.config.MaxIteratorResultItems)) } s.sessionsLock.Lock() session, ok := s.sessions[sID.String()] if !ok { s.sessionsLock.Unlock() - return nil, neorpc.ErrUnknownSession + return nil, tutusrpc.ErrUnknownSession } session.timer.Reset(s.config.SessionLifetime) s.sessionsLock.Unlock() @@ -2702,33 +2702,33 @@ func (s *Server) traverseIterator(reqParams params.Params) (any, *neorpc.Error) } } if !found { - return nil, neorpc.ErrUnknownIterator + return nil, tutusrpc.ErrUnknownIterator } result := make([]json.RawMessage, len(iVals)) for j := range iVals { result[j], err = stackitem.ToJSONWithTypes(iVals[j]) if err != nil { - return nil, neorpc.NewInternalServerError(fmt.Sprintf("failed to marshal iterator value: %s", err)) + return nil, tutusrpc.NewInternalServerError(fmt.Sprintf("failed to marshal iterator value: %s", err)) } } return result, nil } -func (s *Server) terminateSession(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) terminateSession(reqParams params.Params) (any, *tutusrpc.Error) { if !s.config.SessionEnabled { - return nil, neorpc.ErrSessionsDisabled + return nil, tutusrpc.ErrSessionsDisabled } sID, err := reqParams.Value(0).GetUUID() if err != nil { - return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("invalid session ID: %s", err)) + return nil, tutusrpc.NewInvalidParamsError(fmt.Sprintf("invalid session ID: %s", err)) } strSID := sID.String() s.sessionsLock.Lock() defer s.sessionsLock.Unlock() session, ok := s.sessions[strSID] if !ok { - return nil, neorpc.ErrUnknownSession + return nil, tutusrpc.ErrUnknownSession } session.timer.Stop() // cancel session's finalizer. session.finalize() @@ -2737,75 +2737,75 @@ func (s *Server) terminateSession(reqParams params.Params) (any, *neorpc.Error) } // submitBlock broadcasts a raw block over the Neo network. -func (s *Server) submitBlock(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) submitBlock(reqParams params.Params) (any, *tutusrpc.Error) { blockBytes, err := reqParams.Value(0).GetBytesBase64() if err != nil { - return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("missing parameter or not a base64: %s", err)) + return nil, tutusrpc.NewInvalidParamsError(fmt.Sprintf("missing parameter or not a base64: %s", err)) } b := block.New(s.stateRootEnabled) r := io.NewBinReaderFromBuf(blockBytes) b.DecodeBinary(r) if r.Err != nil { - return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("can't decode block: %s", r.Err)) + return nil, tutusrpc.NewInvalidParamsError(fmt.Sprintf("can't decode block: %s", r.Err)) } return getRelayResult(s.chain.AddBlock(b), b.Hash()) } // submitNotaryRequest broadcasts P2PNotaryRequest over the Neo network. -func (s *Server) submitNotaryRequest(ps params.Params) (any, *neorpc.Error) { +func (s *Server) submitNotaryRequest(ps params.Params) (any, *tutusrpc.Error) { if !s.chain.P2PSigExtensionsEnabled() { - return nil, neorpc.NewInternalServerError("P2PSignatureExtensions are disabled") + return nil, tutusrpc.NewInternalServerError("P2PSignatureExtensions are disabled") } bytePayload, err := ps.Value(0).GetBytesBase64() if err != nil { - return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("not a base64: %s", err)) + return nil, tutusrpc.NewInvalidParamsError(fmt.Sprintf("not a base64: %s", err)) } r, err := payload.NewP2PNotaryRequestFromBytes(bytePayload) if err != nil { - return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("can't decode notary payload: %s", err)) + return nil, tutusrpc.NewInvalidParamsError(fmt.Sprintf("can't decode notary payload: %s", err)) } return getRelayResult(s.coreServer.RelayP2PNotaryRequest(r), r.FallbackTransaction.Hash()) } // getRelayResult returns successful relay result or an error. -func getRelayResult(err error, hash util.Uint256) (any, *neorpc.Error) { +func getRelayResult(err error, hash util.Uint256) (any, *tutusrpc.Error) { switch { case err == nil: return result.RelayResult{ Hash: hash, }, nil case errors.Is(err, core.ErrTxExpired): - return nil, neorpc.WrapErrorWithData(neorpc.ErrExpiredTransaction, err.Error()) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrExpiredTransaction, err.Error()) case errors.Is(err, core.ErrAlreadyExists): - return nil, neorpc.WrapErrorWithData(neorpc.ErrAlreadyExists, err.Error()) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrAlreadyExists, err.Error()) case errors.Is(err, core.ErrAlreadyInPool): - return nil, neorpc.WrapErrorWithData(neorpc.ErrAlreadyInPool, err.Error()) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrAlreadyInPool, err.Error()) case errors.Is(err, core.ErrOOM): - return nil, neorpc.WrapErrorWithData(neorpc.ErrMempoolCapReached, err.Error()) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrMempoolCapReached, err.Error()) case errors.Is(err, core.ErrPolicy): - return nil, neorpc.WrapErrorWithData(neorpc.ErrPolicyFailed, err.Error()) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrPolicyFailed, err.Error()) case errors.Is(err, core.ErrInvalidScript): - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidScript, err.Error()) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidScript, err.Error()) case errors.Is(err, core.ErrTxTooBig): - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidSize, err.Error()) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidSize, err.Error()) case errors.Is(err, core.ErrTxSmallNetworkFee): - return nil, neorpc.WrapErrorWithData(neorpc.ErrInsufficientNetworkFee, err.Error()) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInsufficientNetworkFee, err.Error()) case errors.Is(err, core.ErrInvalidAttribute): - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidAttribute, err.Error()) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidAttribute, err.Error()) case errors.Is(err, core.ErrInsufficientFunds), errors.Is(err, core.ErrMemPoolConflict): - return nil, neorpc.WrapErrorWithData(neorpc.ErrInsufficientFunds, err.Error()) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInsufficientFunds, err.Error()) case errors.Is(err, core.ErrInvalidSignature): - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidSignature, err.Error()) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidSignature, err.Error()) default: - return nil, neorpc.WrapErrorWithData(neorpc.ErrVerificationFailed, err.Error()) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrVerificationFailed, err.Error()) } } -func (s *Server) submitOracleResponse(ps params.Params) (any, *neorpc.Error) { +func (s *Server) submitOracleResponse(ps params.Params) (any, *tutusrpc.Error) { oraclePtr := s.oracle.Load() if oraclePtr == nil { - return nil, neorpc.ErrOracleDisabled + return nil, tutusrpc.ErrOracleDisabled } oracle := oraclePtr.(OracleHandler) var pub *keys.PublicKey @@ -2814,113 +2814,113 @@ func (s *Server) submitOracleResponse(ps params.Params) (any, *neorpc.Error) { pub, err = keys.NewPublicKeyFromBytes(pubBytes, elliptic.P256()) } if err != nil { - return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("public key is missing: %s", err)) + return nil, tutusrpc.NewInvalidParamsError(fmt.Sprintf("public key is missing: %s", err)) } reqID, err := ps.Value(1).GetInt() if err != nil { - return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("request ID is missing: %s", err)) + return nil, tutusrpc.NewInvalidParamsError(fmt.Sprintf("request ID is missing: %s", err)) } txSig, err := ps.Value(2).GetBytesBase64() if err != nil { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("tx signature is missing: %s", err)) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, fmt.Sprintf("tx signature is missing: %s", err)) } msgSig, err := ps.Value(3).GetBytesBase64() if err != nil { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("msg signature is missing: %s", err)) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, fmt.Sprintf("msg signature is missing: %s", err)) } data := broadcaster.GetMessage(pubBytes, uint64(reqID), txSig) if !pub.Verify(msgSig, hash.Sha256(data).BytesBE()) { - return nil, neorpc.ErrInvalidSignature + return nil, tutusrpc.ErrInvalidSignature } oracle.AddResponse(pub, uint64(reqID), txSig) return json.RawMessage([]byte("{}")), nil } -func (s *Server) sendrawtransaction(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) sendrawtransaction(reqParams params.Params) (any, *tutusrpc.Error) { if len(reqParams) < 1 { - return nil, neorpc.NewInvalidParamsError("not enough parameters") + return nil, tutusrpc.NewInvalidParamsError("not enough parameters") } byteTx, err := reqParams[0].GetBytesBase64() if err != nil { - return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("not a base64: %s", err)) + return nil, tutusrpc.NewInvalidParamsError(fmt.Sprintf("not a base64: %s", err)) } tx, err := transaction.NewTransactionFromBytes(byteTx) if err != nil { - return nil, neorpc.NewInvalidParamsError(fmt.Sprintf("can't decode transaction: %s", err)) + return nil, tutusrpc.NewInvalidParamsError(fmt.Sprintf("can't decode transaction: %s", err)) } return getRelayResult(s.coreServer.RelayTxn(tx), tx.Hash()) } // subscribe handles subscription requests from websocket clients. -func (s *Server) subscribe(reqParams params.Params, sub *subscriber) (any, *neorpc.Error) { +func (s *Server) subscribe(reqParams params.Params, sub *subscriber) (any, *tutusrpc.Error) { streamName, err := reqParams.Value(0).GetString() if err != nil { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } - event, err := neorpc.GetEventIDFromString(streamName) - if err != nil || event == neorpc.MissedEventID { - return nil, neorpc.ErrInvalidParams + event, err := tutusrpc.GetEventIDFromString(streamName) + if err != nil || event == tutusrpc.MissedEventID { + return nil, tutusrpc.ErrInvalidParams } - if event == neorpc.NotaryRequestEventID && !s.chain.P2PSigExtensionsEnabled() { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, "P2PSigExtensions are disabled") + if event == tutusrpc.NotaryRequestEventID && !s.chain.P2PSigExtensionsEnabled() { + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, "P2PSigExtensions are disabled") } // Optional filter. - var filter neorpc.SubscriptionFilter + var filter tutusrpc.SubscriptionFilter if p := reqParams.Value(1); p != nil { param := *p jd := json.NewDecoder(bytes.NewReader(param.RawMessage)) jd.DisallowUnknownFields() switch event { - case neorpc.BlockEventID, neorpc.HeaderOfAddedBlockEventID: - flt := new(neorpc.BlockFilter) + case tutusrpc.BlockEventID, tutusrpc.HeaderOfAddedBlockEventID: + flt := new(tutusrpc.BlockFilter) err = jd.Decode(flt) filter = *flt - case neorpc.TransactionEventID: - flt := new(neorpc.TxFilter) + case tutusrpc.TransactionEventID: + flt := new(tutusrpc.TxFilter) err = jd.Decode(flt) filter = *flt - case neorpc.NotaryRequestEventID: - flt := new(neorpc.NotaryRequestFilter) + case tutusrpc.NotaryRequestEventID: + flt := new(tutusrpc.NotaryRequestFilter) err = jd.Decode(flt) filter = *flt - case neorpc.NotificationEventID: - flt := new(neorpc.NotificationFilter) + case tutusrpc.NotificationEventID: + flt := new(tutusrpc.NotificationFilter) err = jd.Decode(flt) filter = *flt - case neorpc.ExecutionEventID: - flt := new(neorpc.ExecutionFilter) + case tutusrpc.ExecutionEventID: + flt := new(tutusrpc.ExecutionFilter) err = jd.Decode(flt) filter = *flt - case neorpc.MempoolEventID: + case tutusrpc.MempoolEventID: if !s.config.MempoolSubscriptionsEnabled { - return nil, neorpc.NewInternalServerError("mempool subscriptions are disabled") + return nil, tutusrpc.NewInternalServerError("mempool subscriptions are disabled") } - flt := new(neorpc.MempoolEventFilter) + flt := new(tutusrpc.MempoolEventFilter) err = jd.Decode(flt) filter = *flt default: } if err != nil { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, err.Error()) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, err.Error()) } } if filter != nil { err = filter.IsValid() if err != nil { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, err.Error()) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, err.Error()) } } s.subsLock.Lock() var id int for ; id < len(sub.feeds); id++ { - if sub.feeds[id].event == neorpc.InvalidEventID { + if sub.feeds[id].event == tutusrpc.InvalidEventID { break } } if id == len(sub.feeds) { s.subsLock.Unlock() - return nil, neorpc.NewInternalServerError("maximum number of subscriptions is reached") + return nil, tutusrpc.NewInternalServerError("maximum number of subscriptions is reached") } sub.feeds[id].event = event sub.feeds[id].filter = filter @@ -2930,7 +2930,7 @@ func (s *Server) subscribe(reqParams params.Params, sub *subscriber) (any, *neor select { case <-s.shutdown: s.subsCounterLock.Unlock() - return nil, neorpc.NewInternalServerError("server is shutting down") + return nil, tutusrpc.NewInternalServerError("server is shutting down") default: } s.subscribeToChannel(event) @@ -2941,39 +2941,39 @@ func (s *Server) subscribe(reqParams params.Params, sub *subscriber) (any, *neor // subscribeToChannel subscribes RPC server to appropriate chain events if // it's not yet subscribed for them. It's supposed to be called with s.subsCounterLock // taken by the caller. -func (s *Server) subscribeToChannel(event neorpc.EventID) { +func (s *Server) subscribeToChannel(event tutusrpc.EventID) { switch event { - case neorpc.BlockEventID: + case tutusrpc.BlockEventID: if s.blockSubs == 0 { s.chain.SubscribeForBlocks(s.blockCh) } s.blockSubs++ - case neorpc.TransactionEventID: + case tutusrpc.TransactionEventID: if s.transactionSubs == 0 { s.chain.SubscribeForTransactions(s.transactionCh) } s.transactionSubs++ - case neorpc.NotificationEventID: + case tutusrpc.NotificationEventID: if s.notificationSubs == 0 { s.chain.SubscribeForNotifications(s.notificationCh) } s.notificationSubs++ - case neorpc.ExecutionEventID: + case tutusrpc.ExecutionEventID: if s.executionSubs == 0 { s.chain.SubscribeForExecutions(s.executionCh) } s.executionSubs++ - case neorpc.NotaryRequestEventID: + case tutusrpc.NotaryRequestEventID: if s.notaryRequestSubs == 0 { s.coreServer.SubscribeForNotaryRequests(s.notaryRequestCh) } s.notaryRequestSubs++ - case neorpc.HeaderOfAddedBlockEventID: + case tutusrpc.HeaderOfAddedBlockEventID: if s.blockHeaderSubs == 0 { s.chain.SubscribeForHeadersOfAddedBlocks(s.blockHeaderCh) } s.blockHeaderSubs++ - case neorpc.MempoolEventID: + case tutusrpc.MempoolEventID: if s.mempoolEventSubs == 0 { s.chain.GetMemPool().SubscribeForTransactions(s.mempoolEventCh) } @@ -2983,18 +2983,18 @@ func (s *Server) subscribeToChannel(event neorpc.EventID) { } // unsubscribe handles unsubscription requests from websocket clients. -func (s *Server) unsubscribe(reqParams params.Params, sub *subscriber) (any, *neorpc.Error) { +func (s *Server) unsubscribe(reqParams params.Params, sub *subscriber) (any, *tutusrpc.Error) { id, err := reqParams.Value(0).GetInt() if err != nil || id < 0 { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } s.subsLock.Lock() - if len(sub.feeds) <= id || sub.feeds[id].event == neorpc.InvalidEventID { + if len(sub.feeds) <= id || sub.feeds[id].event == tutusrpc.InvalidEventID { s.subsLock.Unlock() - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } event := sub.feeds[id].event - sub.feeds[id].event = neorpc.InvalidEventID + sub.feeds[id].event = tutusrpc.InvalidEventID sub.feeds[id].filter = nil s.subsLock.Unlock() @@ -3007,39 +3007,39 @@ func (s *Server) unsubscribe(reqParams params.Params, sub *subscriber) (any, *ne // unsubscribeFromChannel unsubscribes RPC server from appropriate chain events // if there are no other subscribers for it. It must be called with s.subsConutersLock // holding by the caller. -func (s *Server) unsubscribeFromChannel(event neorpc.EventID) { +func (s *Server) unsubscribeFromChannel(event tutusrpc.EventID) { switch event { - case neorpc.BlockEventID: + case tutusrpc.BlockEventID: s.blockSubs-- if s.blockSubs == 0 { s.chain.UnsubscribeFromBlocks(s.blockCh) } - case neorpc.TransactionEventID: + case tutusrpc.TransactionEventID: s.transactionSubs-- if s.transactionSubs == 0 { s.chain.UnsubscribeFromTransactions(s.transactionCh) } - case neorpc.NotificationEventID: + case tutusrpc.NotificationEventID: s.notificationSubs-- if s.notificationSubs == 0 { s.chain.UnsubscribeFromNotifications(s.notificationCh) } - case neorpc.ExecutionEventID: + case tutusrpc.ExecutionEventID: s.executionSubs-- if s.executionSubs == 0 { s.chain.UnsubscribeFromExecutions(s.executionCh) } - case neorpc.NotaryRequestEventID: + case tutusrpc.NotaryRequestEventID: s.notaryRequestSubs-- if s.notaryRequestSubs == 0 { s.coreServer.UnsubscribeFromNotaryRequests(s.notaryRequestCh) } - case neorpc.HeaderOfAddedBlockEventID: + case tutusrpc.HeaderOfAddedBlockEventID: s.blockHeaderSubs-- if s.blockHeaderSubs == 0 { s.chain.UnsubscribeFromHeadersOfAddedBlocks(s.blockHeaderCh) } - case neorpc.MempoolEventID: + case tutusrpc.MempoolEventID: s.mempoolEventSubs-- if s.mempoolEventSubs == 0 { s.chain.GetMemPool().UnsubscribeFromTransactions(s.mempoolEventCh) @@ -3051,9 +3051,9 @@ func (s *Server) unsubscribeFromChannel(event neorpc.EventID) { // handleSubEvents processes Server subscriptions until Shutdown. Upon // completion signals to subEventCh channel. func (s *Server) handleSubEvents() { - var overflowEvent = neorpc.Notification{ - JSONRPC: neorpc.JSONRPCVersion, - Event: neorpc.MissedEventID, + var overflowEvent = tutusrpc.Notification{ + JSONRPC: tutusrpc.JSONRPCVersion, + Event: tutusrpc.MissedEventID, Payload: make([]any, 0), } b, err := json.Marshal(overflowEvent) @@ -3068,8 +3068,8 @@ func (s *Server) handleSubEvents() { } chloop: for { - var resp = neorpc.Notification{ - JSONRPC: neorpc.JSONRPCVersion, + var resp = tutusrpc.Notification{ + JSONRPC: tutusrpc.JSONRPCVersion, Payload: make([]any, 1), } var msg *websocket.PreparedMessage @@ -3077,28 +3077,28 @@ chloop: case <-s.shutdown: break chloop case b := <-s.blockCh: - resp.Event = neorpc.BlockEventID + resp.Event = tutusrpc.BlockEventID resp.Payload[0] = b case execution := <-s.executionCh: - resp.Event = neorpc.ExecutionEventID + resp.Event = tutusrpc.ExecutionEventID resp.Payload[0] = execution case notification := <-s.notificationCh: - resp.Event = neorpc.NotificationEventID + resp.Event = tutusrpc.NotificationEventID resp.Payload[0] = notification case tx := <-s.transactionCh: - resp.Event = neorpc.TransactionEventID + resp.Event = tutusrpc.TransactionEventID resp.Payload[0] = tx case e := <-s.notaryRequestCh: - resp.Event = neorpc.NotaryRequestEventID + resp.Event = tutusrpc.NotaryRequestEventID resp.Payload[0] = &result.NotaryRequestEvent{ Type: e.Type, NotaryRequest: e.Data.(*payload.P2PNotaryRequest), } case header := <-s.blockHeaderCh: - resp.Event = neorpc.HeaderOfAddedBlockEventID + resp.Event = tutusrpc.HeaderOfAddedBlockEventID resp.Payload[0] = header case memEvent := <-s.mempoolEventCh: - resp.Event = neorpc.MempoolEventID + resp.Event = tutusrpc.MempoolEventID resp.Payload[0] = &result.MempoolEvent{ Type: memEvent.Type, Tx: memEvent.Tx, @@ -3188,21 +3188,21 @@ drainloop: close(s.subEventsToExitCh) } -func (s *Server) blockHeightFromParam(param *params.Param) (uint32, *neorpc.Error) { +func (s *Server) blockHeightFromParam(param *params.Param) (uint32, *tutusrpc.Error) { num, err := param.GetInt() if err != nil { - return 0, neorpc.ErrInvalidParams + return 0, tutusrpc.ErrInvalidParams } if num < 0 || int64(num) > int64(s.chain.BlockHeight()) { - return 0, neorpc.WrapErrorWithData(neorpc.ErrUnknownHeight, fmt.Sprintf("param at index %d should be greater than or equal to 0 and less than or equal to current block height, got: %d", 0, num)) + return 0, tutusrpc.WrapErrorWithData(tutusrpc.ErrUnknownHeight, fmt.Sprintf("param at index %d should be greater than or equal to 0 and less than or equal to current block height, got: %d", 0, num)) } return uint32(num), nil } -func (s *Server) packResponse(r *params.In, result any, respErr *neorpc.Error) abstract { +func (s *Server) packResponse(r *params.In, result any, respErr *tutusrpc.Error) abstract { resp := abstract{ - Header: neorpc.Header{ + Header: tutusrpc.Header{ JSONRPC: r.JSONRPC, ID: r.RawID, }, @@ -3216,7 +3216,7 @@ func (s *Server) packResponse(r *params.In, result any, respErr *neorpc.Error) a } // logRequestError is a request error logger. -func (s *Server) logRequestError(r *params.Request, jsonErr *neorpc.Error) { +func (s *Server) logRequestError(r *params.Request, jsonErr *tutusrpc.Error) { logFields := []zap.Field{ zap.Int64("code", jsonErr.Code), } @@ -3232,7 +3232,7 @@ func (s *Server) logRequestError(r *params.Request, jsonErr *neorpc.Error) { logText := "Error encountered with rpc request" switch jsonErr.Code { - case neorpc.InternalServerErrorCode: + case tutusrpc.InternalServerErrorCode: s.log.Error(logText, logFields...) default: s.log.Info(logText, logFields...) @@ -3240,7 +3240,7 @@ func (s *Server) logRequestError(r *params.Request, jsonErr *neorpc.Error) { } // writeHTTPErrorResponse writes an error response to the ResponseWriter. -func (s *Server) writeHTTPErrorResponse(r *params.In, w http.ResponseWriter, jsonErr *neorpc.Error) { +func (s *Server) writeHTTPErrorResponse(r *params.In, w http.ResponseWriter, jsonErr *tutusrpc.Error) { resp := s.packResponse(r, nil, jsonErr) s.writeHTTPServerResponse(¶ms.Request{In: r}, w, resp) } @@ -3252,7 +3252,7 @@ func setCORSOriginHeaders(h http.Header) { func (s *Server) writeHTTPServerResponse(r *params.Request, w http.ResponseWriter, resp abstractResult) { // Errors can happen in many places and we can only catch ALL of them here. - resp.RunForErrors(func(jsonErr *neorpc.Error) { + resp.RunForErrors(func(jsonErr *tutusrpc.Error) { s.logRequestError(r, jsonErr) }) w.Header().Set("Content-Type", "application/json; charset=utf-8") @@ -3305,9 +3305,9 @@ func (s *Server) Addresses() []string { return res } -func (s *Server) getRawNotaryPool(_ params.Params) (any, *neorpc.Error) { +func (s *Server) getRawNotaryPool(_ params.Params) (any, *tutusrpc.Error) { if !s.chain.P2PSigExtensionsEnabled() { - return nil, neorpc.NewInternalServerError("P2PSignatureExtensions are disabled") + return nil, tutusrpc.NewInternalServerError("P2PSignatureExtensions are disabled") } nrp := s.coreServer.GetNotaryPool() res := &result.RawNotaryPool{Hashes: make(map[util.Uint256][]util.Uint256)} @@ -3323,14 +3323,14 @@ func (s *Server) getRawNotaryPool(_ params.Params) (any, *neorpc.Error) { return res, nil } -func (s *Server) getRawNotaryTransaction(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) getRawNotaryTransaction(reqParams params.Params) (any, *tutusrpc.Error) { if !s.chain.P2PSigExtensionsEnabled() { - return nil, neorpc.NewInternalServerError("P2PSignatureExtensions are disabled") + return nil, tutusrpc.NewInternalServerError("P2PSignatureExtensions are disabled") } txHash, err := reqParams.Value(0).GetUint256() if err != nil { - return nil, neorpc.ErrInvalidParams + return nil, tutusrpc.ErrInvalidParams } nrp := s.coreServer.GetNotaryPool() // Try to find fallback transaction. @@ -3346,7 +3346,7 @@ func (s *Server) getRawNotaryTransaction(reqParams params.Params) (any, *neorpc. }) // The transaction was not found. if tx == nil { - return nil, neorpc.ErrUnknownTransaction + return nil, tutusrpc.ErrUnknownTransaction } } @@ -3357,55 +3357,55 @@ func (s *Server) getRawNotaryTransaction(reqParams params.Params) (any, *neorpc. } // getBlockNotifications returns notifications from a specific block with optional filtering. -func (s *Server) getBlockNotifications(reqParams params.Params) (any, *neorpc.Error) { +func (s *Server) getBlockNotifications(reqParams params.Params) (any, *tutusrpc.Error) { param := reqParams.Value(0) hash, respErr := s.blockHashFromParam(param) if respErr != nil { return nil, respErr } - var filter *neorpc.NotificationFilter + var filter *tutusrpc.NotificationFilter if len(reqParams) > 1 { var ( reader = bytes.NewBuffer([]byte(reqParams[1].RawMessage)) decoder = json.NewDecoder(reader) ) decoder.DisallowUnknownFields() - filter = new(neorpc.NotificationFilter) + filter = new(tutusrpc.NotificationFilter) err := decoder.Decode(filter) if err != nil { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("invalid filter: %s", err)) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, fmt.Sprintf("invalid filter: %s", err)) } if err := filter.IsValid(); err != nil { - return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("invalid filter: %s", err)) + return nil, tutusrpc.WrapErrorWithData(tutusrpc.ErrInvalidParams, fmt.Sprintf("invalid filter: %s", err)) } } block, err := s.chain.GetTrimmedBlock(hash) if err != nil { - return nil, neorpc.ErrUnknownBlock + return nil, tutusrpc.ErrUnknownBlock } notifications := &result.BlockNotifications{} aers, err := s.chain.GetAppExecResults(block.Hash(), trigger.OnPersist) if err != nil { - return nil, neorpc.NewInternalServerError("failed to get app exec results for onpersist") + return nil, tutusrpc.NewInternalServerError("failed to get app exec results for onpersist") } notifications.OnPersist = processAppExecResults([]state.AppExecResult{aers[0]}, filter) for _, txHash := range block.Transactions { aers, err := s.chain.GetAppExecResults(txHash.Hash(), trigger.Application) if err != nil { - return nil, neorpc.NewInternalServerError("failed to get app exec results") + return nil, tutusrpc.NewInternalServerError("failed to get app exec results") } notifications.Application = append(notifications.Application, processAppExecResults(aers, filter)...) } aers, err = s.chain.GetAppExecResults(block.Hash(), trigger.PostPersist) if err != nil { - return nil, neorpc.NewInternalServerError("failed to get app exec results for postpersist") + return nil, tutusrpc.NewInternalServerError("failed to get app exec results for postpersist") } notifications.PostPersist = processAppExecResults([]state.AppExecResult{aers[0]}, filter) diff --git a/pkg/services/rpcsrv/server_test.go b/pkg/services/rpcsrv/server_test.go index cb53501..1fafb15 100644 --- a/pkg/services/rpcsrv/server_test.go +++ b/pkg/services/rpcsrv/server_test.go @@ -40,8 +40,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/crypto/keys" "github.com/tutus-one/tutus-chain/pkg/encoding/address" "github.com/tutus-one/tutus-chain/pkg/io" - "github.com/tutus-one/tutus-chain/pkg/neorpc" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/network" "github.com/tutus-one/tutus-chain/pkg/network/payload" rpc2 "github.com/tutus-one/tutus-chain/pkg/services/oracle/broadcaster" @@ -154,7 +154,7 @@ var rpcFunctionsWithUnsupportedStatesTestCases = map[string][]rpcTestCase{ name: "unsupported state", params: `[]`, fail: true, - errCode: neorpc.ErrUnsupportedStateCode, + errCode: tutusrpc.ErrUnsupportedStateCode, }, }, "verifyproof": { @@ -162,7 +162,7 @@ var rpcFunctionsWithUnsupportedStatesTestCases = map[string][]rpcTestCase{ name: "unsupported state", params: `[]`, fail: true, - errCode: neorpc.ErrUnsupportedStateCode, + errCode: tutusrpc.ErrUnsupportedStateCode, }, }, "getstate": { @@ -170,7 +170,7 @@ var rpcFunctionsWithUnsupportedStatesTestCases = map[string][]rpcTestCase{ name: "unsupported state", params: `["0000000000000000000000000000000000000000000000000000000000000000", "` + testContractHashLE + `", "QQ=="]`, fail: true, - errCode: neorpc.ErrUnsupportedStateCode, + errCode: tutusrpc.ErrUnsupportedStateCode, }, }, "findstates": { @@ -178,7 +178,7 @@ var rpcFunctionsWithUnsupportedStatesTestCases = map[string][]rpcTestCase{ name: "unsupported state", params: `["` + block20StateRootLE + `", "0xabcdef"]`, fail: true, - errCode: neorpc.ErrUnsupportedStateCode, + errCode: tutusrpc.ErrUnsupportedStateCode, }, }, "findstoragehistoric": { @@ -186,7 +186,7 @@ var rpcFunctionsWithUnsupportedStatesTestCases = map[string][]rpcTestCase{ name: "unsupported state", params: `["` + block20StateRootLE + `", "0xabcdef"]`, fail: true, - errCode: neorpc.ErrUnsupportedStateCode, + errCode: tutusrpc.ErrUnsupportedStateCode, }, }, "invokefunctionhistoric": { @@ -194,7 +194,7 @@ var rpcFunctionsWithUnsupportedStatesTestCases = map[string][]rpcTestCase{ name: "unsupported state", params: `[]`, fail: true, - errCode: neorpc.ErrUnsupportedStateCode, + errCode: tutusrpc.ErrUnsupportedStateCode, }, }, } @@ -260,25 +260,25 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "invalid trigger (not a string)", params: `["` + genesisBlockHash + `", 1]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid address", params: `["notahash"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid tx hash", params: `["d24cc1d52b5c0216cbf3835bb5bac8ccf32639fa1ab6627ec4e2b9f33f7ec02f"]`, fail: true, - errCode: neorpc.ErrUnknownScriptContainerCode, + errCode: tutusrpc.ErrUnknownScriptContainerCode, }, }, "getcontractstate": { @@ -326,31 +326,31 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "negative, bad hash", params: `["6d1eeca891ee93de2b7a77eb91c26f3b3c04d6c3"]`, fail: true, - errCode: neorpc.ErrUnknownContractCode, + errCode: tutusrpc.ErrUnknownContractCode, }, { name: "negative, bad ID", params: `[-100]`, fail: true, - errCode: neorpc.ErrUnknownContractCode, + errCode: tutusrpc.ErrUnknownContractCode, }, { name: "negative, bad native name", params: `["unknown_native"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid hash", params: `["notahex"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, }, "getnep11balances": { @@ -358,13 +358,13 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid address", params: `["notahex"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "positive", @@ -384,25 +384,25 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid address", params: `["notahex"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "no token", params: `["` + nnsContractHash + `"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "bad token", params: `["` + nnsContractHash + `", "abcdef"]`, fail: true, - errCode: neorpc.ErrExecutionFailedCode, + errCode: tutusrpc.ErrExecutionFailedCode, }, { name: "positive", @@ -421,25 +421,25 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid address", params: `["notahex"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid timestamp", params: `["` + testchain.PrivateKeyByID(0).Address() + `", "notanumber"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid stop timestamp", params: `["` + testchain.PrivateKeyByID(0).Address() + `", "1", "blah"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "positive", @@ -453,13 +453,13 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid address", params: `["notahex"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "positive", @@ -479,55 +479,55 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid address", params: `["notahex"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid timestamp", params: `["` + testchain.PrivateKeyByID(0).Address() + `", "notanumber"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid stop timestamp", params: `["` + testchain.PrivateKeyByID(0).Address() + `", "1", "blah"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid limit", params: `["` + testchain.PrivateKeyByID(0).Address() + `", "1", "2", "0"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid limit 2", params: `["` + testchain.PrivateKeyByID(0).Address() + `", "1", "2", "bleh"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid limit 3", params: `["` + testchain.PrivateKeyByID(0).Address() + `", "1", "2", "100500"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid page", params: `["` + testchain.PrivateKeyByID(0).Address() + `", "1", "2", "3", "-1"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid page 2", params: `["` + testchain.PrivateKeyByID(0).Address() + `", "1", "2", "3", "jajaja"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "positive", @@ -547,25 +547,25 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid root", params: `["0xabcdef"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid contract", params: `["0000000000000000000000000000000000000000000000000000000000000000", "0xabcdef"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid key", params: `["0000000000000000000000000000000000000000000000000000000000000000", "` + testContractHashLE + `", "notahex"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, }, "getstate": { @@ -573,37 +573,37 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid root", params: `["0xabcdef"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid contract", params: `["0000000000000000000000000000000000000000000000000000000000000000", "0xabcdef"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid key", params: `["0000000000000000000000000000000000000000000000000000000000000000", "` + testContractHashLE + `", "notabase64%"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "unknown contract", params: `["0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000", "QQ=="]`, fail: true, - errCode: neorpc.ErrUnknownContractCode, + errCode: tutusrpc.ErrUnknownContractCode, }, { name: "unknown root/item", params: `["0000000000000000000000000000000000000000000000000000000000000000", "` + testContractHashLE + `", "QQ=="]`, fail: true, - errCode: neorpc.ErrUnknownContractCode, + errCode: tutusrpc.ErrUnknownContractCode, }, }, "findstates": { @@ -611,37 +611,37 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid root", params: `["0xabcdef"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid contract", params: `["` + block20StateRootLE + `", "0xabcdef"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid prefix", params: `["` + block20StateRootLE + `", "` + testContractHashLE + `", "notabase64%"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid key", params: `["` + block20StateRootLE + `", "` + testContractHashLE + `", "QQ==", "notabase64%"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "unknown contract/large count", params: `["` + block20StateRootLE + `", "0000000000000000000000000000000000000000", "QQ==", "QQ==", 101]`, fail: true, - errCode: neorpc.ErrUnknownContractCode, + errCode: tutusrpc.ErrUnknownContractCode, }, }, "getstateheight": { @@ -663,13 +663,13 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid hash", params: `["0x1234567890"]`, fail: true, - errCode: neorpc.ErrUnknownStateRootCode, + errCode: tutusrpc.ErrUnknownStateRootCode, }, }, "getstorage": { @@ -685,31 +685,31 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "missing key", params: fmt.Sprintf(`["%s", "dGU="]`, testContractHashLE), fail: true, - errCode: neorpc.ErrUnknownStorageItemCode, + errCode: tutusrpc.ErrUnknownStorageItemCode, }, { name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "no second parameter", params: fmt.Sprintf(`["%s"]`, testContractHashLE), fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid hash", params: `["notahex"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid key", params: fmt.Sprintf(`["%s", "notabase64$"]`, testContractHashLE), fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, }, "getstoragehistoric": { @@ -725,43 +725,43 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "missing key", params: fmt.Sprintf(`["%s", "%s", "dGU="]`, block20StateRootLE, testContractHashLE), fail: true, - errCode: neorpc.ErrUnknownStorageItemCode, + errCode: tutusrpc.ErrUnknownStorageItemCode, }, { name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "no second parameter", params: fmt.Sprintf(`["%s"]`, block20StateRootLE), fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "no third parameter", params: fmt.Sprintf(`["%s", "%s"]`, block20StateRootLE, testContractHashLE), fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid stateroot", params: `["notahex"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid hash", params: fmt.Sprintf(`["%s", "notahex"]`, block20StateRootLE), fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid key", params: fmt.Sprintf(`["%s", "%s", "notabase64$"]`, block20StateRootLE, testContractHashLE), fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, }, "findstorage": { @@ -877,31 +877,31 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "no second parameter", params: fmt.Sprintf(`["%s"]`, testContractHashLE), fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid hash", params: `["notahex"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid key", params: fmt.Sprintf(`["%s", "notabase64$"]`, testContractHashLE), fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid page", params: fmt.Sprintf(`["%s", "", "not-an-int"]`, testContractHashLE), fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, }, "findstoragehistoric": { @@ -1017,43 +1017,43 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid stateroot", params: `[12345]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "no second parameter", params: fmt.Sprintf(`["%s"]`, block20StateRootLE), fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "no third parameter", params: fmt.Sprintf(`["%s", "%s"]`, block20StateRootLE, testContractHashLE), fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid hash", params: fmt.Sprintf(`["%s", "notahex"]`, block20StateRootLE), fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid key", params: fmt.Sprintf(`["%s", "%s", "notabase64$"]`, block20StateRootLE, testContractHashLE), fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid page", params: fmt.Sprintf(`["%s", "%s", "", "not-an-int"]`, block20StateRootLE, testContractHashLE), fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, }, "getbestblockhash": { @@ -1090,31 +1090,31 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "bad params", params: `[[]]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid height", params: `[-1]`, fail: true, - errCode: neorpc.ErrUnknownHeightCode, + errCode: tutusrpc.ErrUnknownHeightCode, }, { name: "invalid hash", params: `["notahex"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "missing hash", params: `["` + util.Uint256{}.String() + `"]`, fail: true, - errCode: neorpc.ErrUnknownBlockCode, + errCode: tutusrpc.ErrUnknownBlockCode, }, }, "getblockcount": { @@ -1141,13 +1141,13 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "string height", params: `["first"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid number height", params: `[-2]`, fail: true, - errCode: neorpc.ErrUnknownHeightCode, + errCode: tutusrpc.ErrUnknownHeightCode, }, }, "getblockheader": { @@ -1155,25 +1155,25 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "invalid verbose type", params: `["9673799c5b5a294427401cb07d6cc615ada3a0d5c5bf7ed6f0f54f24abb2e2ac", true]`, fail: true, - errCode: neorpc.ErrUnknownBlockCode, + errCode: tutusrpc.ErrUnknownBlockCode, }, { name: "invalid block hash", params: `["notahash"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "unknown block", params: `["a6e526375a780335112299f2262501e5e9574c3ba61b16bbc1e282b344f6c141"]`, fail: true, - errCode: neorpc.ErrUnknownBlockCode, + errCode: tutusrpc.ErrUnknownBlockCode, }, { name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, }, "getblockheadercount": { @@ -1203,19 +1203,19 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "string height", params: `["first"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid number height", params: `[-2]`, fail: true, - errCode: neorpc.ErrUnknownHeightCode, + errCode: tutusrpc.ErrUnknownHeightCode, }, }, "getcommittee": { @@ -1270,19 +1270,19 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid hash", params: `["notahex"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "missing hash", params: `["` + util.Uint256{}.String() + `"]`, fail: true, - errCode: neorpc.ErrUnknownTransactionCode, + errCode: tutusrpc.ErrUnknownTransactionCode, }, }, "gettransactionheight": { @@ -1303,19 +1303,19 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid hash", params: `["notahex"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "missing hash", params: `["` + util.Uint256{}.String() + `"]`, fail: true, - errCode: neorpc.ErrUnknownTransactionCode, + errCode: tutusrpc.ErrUnknownTransactionCode, }, }, "getunclaimedgas": { @@ -1323,13 +1323,13 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: "[]", fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid address", params: `["invalid"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "positive", @@ -1531,25 +1531,25 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "not a string", params: `[42, "test", []]`, fail: true, - errCode: neorpc.ErrUnknownContractCode, + errCode: tutusrpc.ErrUnknownContractCode, }, { name: "not a scripthash", params: `["qwerty", "test", []]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "bad params", params: `["50befd26fdf6e4d957c11e078b24ebce6291456f", "test", [{"type": "Integer", "value": "qwerty"}]]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, }, "invokefunctionhistoric": { @@ -1650,43 +1650,43 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "no args", params: `[20]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "not a string", params: `[20, 42, "test", []]`, fail: true, - errCode: neorpc.ErrUnknownContractCode, + errCode: tutusrpc.ErrUnknownContractCode, }, { name: "not a scripthash", params: `[20,"qwerty", "test", []]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "bad params", params: `[20,"50befd26fdf6e4d957c11e078b24ebce6291456f", "test", [{"type": "Integer", "value": "qwerty"}]]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "bad height", params: `[100500,"50befd26fdf6e4d957c11e078b24ebce6291456f", "test", [{"type": "Integer", "value": 1}]]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "bad stateroot", params: `["` + util.Uint256{1, 2, 3}.StringLE() + `","50befd26fdf6e4d957c11e078b24ebce6291456f", "test", [{"type": "Integer", "value": 1}]]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, }, "invokescript": { @@ -1776,19 +1776,19 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "not a string", params: `[42]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "bas string", params: `["qwerty"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, }, "invokescripthistoric": { @@ -1890,37 +1890,37 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "no script", params: `[20]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "not a string", params: `[20,42]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "bad string", params: `[20, "qwerty"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "bad height", params: `[100500,"qwerty"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "bad stateroot", params: `["` + util.Uint256{1, 2, 3}.StringLE() + `","UcVrDUhlbGxvLCB3b3JsZCFoD05lby5SdW50aW1lLkxvZ2FsdWY="]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, }, "invokecontainedscript": { @@ -1928,19 +1928,19 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "null tx", params: `[null]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid tx", params: `["notatx"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, }, "invokecontractverify": { @@ -2036,31 +2036,31 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "invalid call args", params: fmt.Sprintf(`["%s", [{"type":"Map","value":{"key":"value"}}]]`, verifyWithArgsContractHash), fail: true, - errCode: neorpc.InternalServerErrorCode, + errCode: tutusrpc.InternalServerErrorCode, }, { name: "negative, wrong signer", params: fmt.Sprintf(`["%s", [], [{"account":"aaa"}]]`, verifyContractHash), fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "unknown contract", params: fmt.Sprintf(`["%s", []]`, util.Uint160{}.String()), fail: true, - errCode: neorpc.ErrUnknownContractCode, + errCode: tutusrpc.ErrUnknownContractCode, }, { name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "not a string", params: `[42, []]`, fail: true, - errCode: neorpc.ErrUnknownContractCode, + errCode: tutusrpc.ErrUnknownContractCode, }, }, "invokecontractverifyhistoric": { @@ -2169,25 +2169,25 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "unknown contract", params: fmt.Sprintf(`[20, "%s", []]`, util.Uint160{}.String()), fail: true, - errCode: neorpc.ErrUnknownContractCode, + errCode: tutusrpc.ErrUnknownContractCode, }, { name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "no args", params: `[20]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "not a string", params: `[20,42, []]`, fail: true, - errCode: neorpc.ErrUnknownContractCode, + errCode: tutusrpc.ErrUnknownContractCode, }, }, "sendrawtransaction": { @@ -2206,31 +2206,31 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "already in pool", params: `["AB0AAACWP5gAAAAAAEDaEgAAAAAAGAAAAAHunqIsJ+NL0BSPxBCOCPdOj1BIsoAAXgsDAOh2SBcAAAAMFBEmW7QXJQBBvgTo+iQOOPV8HlabDBTunqIsJ+NL0BSPxBCOCPdOj1BIshTAHwwIdHJhbnNmZXIMFPVj6kC8KD1NDgXEjqMFs/Kgc0DvQWJ9W1IBQgxAJ6norhWoZxp+Hj1JFhi+Z3qI9DUkLSbfsbaLSaJIqxTfdmPbNFDVK1G+oa+LWmpRp/bj9+QZM7yC+S6HXUI7rigMIQKzYiv0AXvf4xfFiu1fTHU/IGt9uJYEb6fXdLvEv3+NwkFW57Mn"]`, fail: true, - errCode: neorpc.ErrAlreadyInPoolCode, + errCode: tutusrpc.ErrAlreadyInPoolCode, }, { name: "negative", params: `["AAoAAAAxboUQOQGdOd/Cw31sP+4Z/VgJhwAAAAAAAAAA8q0FAAAAAACwBAAAAAExboUQOQGdOd/Cw31sP+4Z/VgJhwFdAwDodkgXAAAADBQgcoJ0r6/Db0OgcdMoz6PmKdnLsAwUMW6FEDkBnTnfwsN9bD/uGf1YCYcTwAwIdHJhbnNmZXIMFIl3INjNdvTwCr+jfA7diJwgj96bQWJ9W1I4AUIMQN+VMUEnEWlCHOurXSegFj4pTXx/LQUltEmHRTRIFP09bFxZHJsXI9BdQoVvQJrbCEz2esySHPr8YpEzpeteen4pDCECs2Ir9AF73+MXxYrtX0x1PyBrfbiWBG+n13S7xL9/jcILQQqQav8="]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid string", params: `["notabase64%"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid tx", params: `["AnTXkgcmF3IGNvbnRyYWNw=="]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, }, "submitblock": { @@ -2238,19 +2238,19 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "invalid base64", params: `["%%%"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "invalid block bytes", params: `["AAAAACc="]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, }, "submitoracleresponse": { @@ -2258,7 +2258,7 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: `[]`, fail: true, - errCode: neorpc.ErrOracleDisabledCode, + errCode: tutusrpc.ErrOracleDisabledCode, }, }, "submitnotaryrequest": { @@ -2266,7 +2266,7 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: `[]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, }, "validateaddress": { @@ -2295,7 +2295,7 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "no params", params: "[]", fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, }, "getblocknotifications": { @@ -2327,31 +2327,31 @@ var rpcTestCases = map[string][]rpcTestCase{ name: "invalid hash", params: `["invalid"]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "unknown block", params: `["` + util.Uint256{}.StringLE() + `"]`, fail: true, - errCode: neorpc.ErrUnknownBlockCode, + errCode: tutusrpc.ErrUnknownBlockCode, }, { name: "invalid filter", params: `["` + genesisBlockHash + `", {"contract":"invalid"}]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "filter with unknown fields", params: `["` + genesisBlockHash + `", {"invalid":"something"}]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, { name: "empty filter", params: `["` + genesisBlockHash + `", []]`, fail: true, - errCode: neorpc.InvalidParamsCode, + errCode: tutusrpc.InvalidParamsCode, }, }, } @@ -2375,7 +2375,7 @@ func TestSubmitOracle(t *testing.T) { }) req := fmt.Sprintf(rpc, "[]") body := doRPCCallOverHTTP(req, httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.ErrOracleDisabledCode) + checkErrGetResult(t, body, true, tutusrpc.ErrOracleDisabledCode) }) _, _, httpSrv := initClearServerWithServices(t, true, false, false) @@ -2388,19 +2388,19 @@ func TestSubmitOracle(t *testing.T) { checkErrGetResult(t, body, fail, errCode) } } - t.Run("MissingKey", runCase(t, true, neorpc.InvalidParamsCode)) - t.Run("InvalidKey", runCase(t, true, neorpc.InvalidParamsCode, `"1234"`)) + t.Run("MissingKey", runCase(t, true, tutusrpc.InvalidParamsCode)) + t.Run("InvalidKey", runCase(t, true, tutusrpc.InvalidParamsCode, `"1234"`)) priv, err := keys.NewPrivateKey() require.NoError(t, err) pubStr := `"` + base64.StdEncoding.EncodeToString(priv.PublicKey().Bytes()) + `"` - t.Run("InvalidReqID", runCase(t, true, neorpc.InvalidParamsCode, pubStr, `"notanumber"`)) - t.Run("InvalidTxSignature", runCase(t, true, neorpc.InvalidParamsCode, pubStr, `1`, `"qwerty"`)) + t.Run("InvalidReqID", runCase(t, true, tutusrpc.InvalidParamsCode, pubStr, `"notanumber"`)) + t.Run("InvalidTxSignature", runCase(t, true, tutusrpc.InvalidParamsCode, pubStr, `1`, `"qwerty"`)) txSig := priv.Sign([]byte{1, 2, 3}) txSigStr := `"` + base64.StdEncoding.EncodeToString(txSig) + `"` - t.Run("MissingMsgSignature", runCase(t, true, neorpc.InvalidParamsCode, pubStr, `1`, txSigStr)) - t.Run("InvalidMsgSignature", runCase(t, true, neorpc.ErrInvalidSignatureCode, pubStr, `1`, txSigStr, `"0123"`)) + t.Run("MissingMsgSignature", runCase(t, true, tutusrpc.InvalidParamsCode, pubStr, `1`, txSigStr)) + t.Run("InvalidMsgSignature", runCase(t, true, tutusrpc.ErrInvalidSignatureCode, pubStr, `1`, txSigStr, `"0123"`)) msg := rpc2.GetMessage(priv.PublicKey().Bytes(), 1, txSig) msgSigStr := `"` + base64.StdEncoding.EncodeToString(priv.Sign(msg)) + `"` @@ -2419,15 +2419,15 @@ func TestNotaryRequestRPC(t *testing.T) { }) t.Run("submitnotaryrequest", func(t *testing.T) { body := doRPCCallOverHTTP(fmt.Sprintf(rpcSubmit, "[]"), httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.InternalServerErrorCode) + checkErrGetResult(t, body, true, tutusrpc.InternalServerErrorCode) }) t.Run("getrawnotarypool", func(t *testing.T) { body := doRPCCallOverHTTP(rpcPool, httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.InternalServerErrorCode) + checkErrGetResult(t, body, true, tutusrpc.InternalServerErrorCode) }) t.Run("getrawnotarytransaction", func(t *testing.T) { body := doRPCCallOverHTTP(fmt.Sprintf(rpcTx, " ", 1), httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.InternalServerErrorCode) + checkErrGetResult(t, body, true, tutusrpc.InternalServerErrorCode) }) }) @@ -2496,9 +2496,9 @@ func TestNotaryRequestRPC(t *testing.T) { }) t.Run("submitnotaryrequest", func(t *testing.T) { - t.Run("missing request", submitNotaryRequest(t, true, neorpc.InvalidParamsCode)) - t.Run("not a base64", submitNotaryRequest(t, true, neorpc.InvalidParamsCode, `"not-a-base64$"`)) - t.Run("invalid request bytes", submitNotaryRequest(t, true, neorpc.InvalidParamsCode, `"not-a-request"`)) + t.Run("missing request", submitNotaryRequest(t, true, tutusrpc.InvalidParamsCode)) + t.Run("not a base64", submitNotaryRequest(t, true, tutusrpc.InvalidParamsCode, `"not-a-base64$"`)) + t.Run("invalid request bytes", submitNotaryRequest(t, true, tutusrpc.InvalidParamsCode, `"not-a-request"`)) t.Run("invalid request", func(t *testing.T) { mainTx := &transaction.Transaction{ Attributes: []transaction.Attribute{{Type: transaction.NotaryAssistedT, Value: &transaction.NotaryAssisted{NKeys: 1}}}, @@ -2534,7 +2534,7 @@ func TestNotaryRequestRPC(t *testing.T) { nrBytes, err := p.Bytes() require.NoError(t, err) str := fmt.Sprintf(`"%s"`, base64.StdEncoding.EncodeToString(nrBytes)) - submitNotaryRequest(t, true, neorpc.ErrVerificationFailedCode, str)(t) + submitNotaryRequest(t, true, tutusrpc.ErrVerificationFailedCode, str)(t) }) t.Run("valid request", func(t *testing.T) { sender := testchain.PrivateKeyByID(0) // owner of the deposit in testchain @@ -2550,12 +2550,12 @@ func TestNotaryRequestRPC(t *testing.T) { t.Run("invalid param", func(t *testing.T) { req := fmt.Sprintf(rpcTx, "invalid", 1) body := doRPCCallOverHTTP(req, httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.InvalidParamsCode) + checkErrGetResult(t, body, true, tutusrpc.InvalidParamsCode) }) t.Run("unknown transaction", func(t *testing.T) { req := fmt.Sprintf(rpcTx, (util.Uint256{0, 0, 0}).StringLE(), 1) body := doRPCCallOverHTTP(req, httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.ErrUnknownTransactionCode) + checkErrGetResult(t, body, true, tutusrpc.ErrUnknownTransactionCode) }) checkGetTxVerbose := func(t *testing.T, tx *transaction.Transaction) { @@ -2705,11 +2705,11 @@ func testRPCProtocol(t *testing.T, doRPCCall func(string, string, *testing.T) [] } resultRPC = `[` + resultRPC[:len(resultRPC)-1] + `]` body := doRPCCall(resultRPC, httpSrv.URL, t) - var responses []neorpc.Response + var responses []tutusrpc.Response err := json.Unmarshal(body, &responses) require.Nil(t, err) for i, tc := range cases { - var resp neorpc.Response + var resp tutusrpc.Response for _, r := range responses { if bytes.Equal(r.ID, []byte(strconv.Itoa(i))) { resp = r @@ -2824,7 +2824,7 @@ func testRPCProtocol(t *testing.T, doRPCCall func(string, string, *testing.T) [] // `testkey`-`testvalue` pair was put to the contract storage at block #3 params := fmt.Sprintf(`"%s", "%s", "%s"`, root.Root.StringLE(), testContractHashLE, base64.StdEncoding.EncodeToString([]byte("invalidkey"))) body := doRPCCall(fmt.Sprintf(rpc, params), httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.InvalidParamsCode) + checkErrGetResult(t, body, true, tutusrpc.InvalidParamsCode) }) t.Run("good: fresh state", func(t *testing.T) { root, err := e.chain.GetStateModule().GetStateRoot(16) @@ -3129,7 +3129,7 @@ func testRPCProtocol(t *testing.T, doRPCCall func(string, string, *testing.T) [] c.ApplicationConfiguration.RPC.SessionEnabled = false }) body := doRPCCall(`{"jsonrpc": "2.0", "id": 1, "method": "traverseiterator", "params": []}"`, httpSrv2.URL, t) - checkErrGetResult(t, body, true, neorpc.ErrSessionsDisabledCode) + checkErrGetResult(t, body, true, tutusrpc.ErrSessionsDisabledCode) }) t.Run("good", func(t *testing.T) { sID, iID := prepareIteratorSession(t) @@ -3145,43 +3145,43 @@ func testRPCProtocol(t *testing.T, doRPCCall func(string, string, *testing.T) [] _, iID := prepareIteratorSession(t) rpc := fmt.Sprintf(`{"jsonrpc": "2.0", "id": 1, "method": "traverseiterator", "params": ["not-a-uuid", "%s", %d]}"`, iID.String(), 1) body := doRPCCall(rpc, httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.InvalidParamsCode, "invalid session ID: not a valid UUID") + checkErrGetResult(t, body, true, tutusrpc.InvalidParamsCode, "invalid session ID: not a valid UUID") }) t.Run("invalid iterator id", func(t *testing.T) { sID, _ := prepareIteratorSession(t) rpc := fmt.Sprintf(`{"jsonrpc": "2.0", "id": 1, "method": "traverseiterator", "params": ["%s", "not-a-uuid", %d]}"`, sID.String(), 1) body := doRPCCall(rpc, httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.InvalidParamsCode, "invalid iterator ID: not a valid UUID") + checkErrGetResult(t, body, true, tutusrpc.InvalidParamsCode, "invalid iterator ID: not a valid UUID") }) t.Run("invalid items count", func(t *testing.T) { sID, iID := prepareIteratorSession(t) rpc := fmt.Sprintf(`{"jsonrpc": "2.0", "id": 1, "method": "traverseiterator", "params": ["%s", "%s"]}"`, sID.String(), iID.String()) body := doRPCCall(rpc, httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.InvalidParamsCode, "invalid iterator items count") + checkErrGetResult(t, body, true, tutusrpc.InvalidParamsCode, "invalid iterator items count") }) t.Run("items count is not an int32", func(t *testing.T) { sID, iID := prepareIteratorSession(t) rpc := fmt.Sprintf(`{"jsonrpc": "2.0", "id": 1, "method": "traverseiterator", "params": ["%s", "%s", %d]}"`, sID.String(), iID.String(), math.MaxInt32+1) body := doRPCCall(rpc, httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.InvalidParamsCode, "invalid iterator items count: not an int32") + checkErrGetResult(t, body, true, tutusrpc.InvalidParamsCode, "invalid iterator items count: not an int32") }) t.Run("count is out of range", func(t *testing.T) { sID, iID := prepareIteratorSession(t) rpc := fmt.Sprintf(`{"jsonrpc": "2.0", "id": 1, "method": "traverseiterator", "params": ["%s", "%s", %d]}"`, sID.String(), iID.String(), config.DefaultMaxIteratorResultItems+1) body := doRPCCall(rpc, httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.InvalidParamsCode, fmt.Sprintf("iterator items count (%d) is out of range (%d at max)", config.DefaultMaxIteratorResultItems+1, config.DefaultMaxIteratorResultItems)) + checkErrGetResult(t, body, true, tutusrpc.InvalidParamsCode, fmt.Sprintf("iterator items count (%d) is out of range (%d at max)", config.DefaultMaxIteratorResultItems+1, config.DefaultMaxIteratorResultItems)) }) t.Run("unknown session", func(t *testing.T) { _, iID := prepareIteratorSession(t) rpc := fmt.Sprintf(`{"jsonrpc": "2.0", "id": 1, "method": "traverseiterator", "params": ["%s", "%s", %d]}"`, uuid.NewString(), iID.String(), 1) body := doRPCCall(rpc, httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.ErrUnknownSessionCode) + checkErrGetResult(t, body, true, tutusrpc.ErrUnknownSessionCode) }) t.Run("unknown iterator", func(t *testing.T) { sID, _ := prepareIteratorSession(t) rpc := fmt.Sprintf(`{"jsonrpc": "2.0", "id": 1, "method": "traverseiterator", "params": ["%s", "%s", %d]}"`, sID.String(), uuid.NewString(), 1) body := doRPCCall(rpc, httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.ErrUnknownIteratorCode) + checkErrGetResult(t, body, true, tutusrpc.ErrUnknownIteratorCode) }) t.Run("sessions expansion enabled", func(t *testing.T) { chain2, _, httpSrv2 := initClearServerWithCustomConfig(t, func(c *config.Config) { @@ -3220,7 +3220,7 @@ func testRPCProtocol(t *testing.T, doRPCCall func(string, string, *testing.T) [] c.ApplicationConfiguration.RPC.SessionEnabled = false }) body := doRPCCall(fmt.Sprintf(rpc, uuid.NewString()), httpSrv2.URL, t) - checkErrGetResult(t, body, true, neorpc.ErrSessionsDisabledCode) + checkErrGetResult(t, body, true, tutusrpc.ErrSessionsDisabledCode) }) t.Run("true", func(t *testing.T) { sID, _ := prepareIteratorSession(t) @@ -3232,7 +3232,7 @@ func testRPCProtocol(t *testing.T, doRPCCall func(string, string, *testing.T) [] }) t.Run("false", func(t *testing.T) { body := doRPCCall(fmt.Sprintf(rpc, uuid.NewString()), httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.ErrUnknownSessionCode) + checkErrGetResult(t, body, true, tutusrpc.ErrUnknownSessionCode) }) t.Run("expired", func(t *testing.T) { _, _ = prepareIteratorSession(t) @@ -3247,15 +3247,15 @@ func testRPCProtocol(t *testing.T, doRPCCall func(string, string, *testing.T) [] t.Run("calculatenetworkfee", func(t *testing.T) { t.Run("no parameters", func(t *testing.T) { body := doRPCCall(`{"jsonrpc": "2.0", "id": 1, "method": "calculatenetworkfee", "params": []}"`, httpSrv.URL, t) - _ = checkErrGetResult(t, body, true, neorpc.InvalidParamsCode, "Invalid params") + _ = checkErrGetResult(t, body, true, tutusrpc.InvalidParamsCode, "Invalid params") }) t.Run("non-base64 parameter", func(t *testing.T) { body := doRPCCall(`{"jsonrpc": "2.0", "id": 1, "method": "calculatenetworkfee", "params": ["noatbase64"]}"`, httpSrv.URL, t) - _ = checkErrGetResult(t, body, true, neorpc.InvalidParamsCode, "Invalid params") + _ = checkErrGetResult(t, body, true, tutusrpc.InvalidParamsCode, "Invalid params") }) t.Run("non-transaction parameter", func(t *testing.T) { body := doRPCCall(`{"jsonrpc": "2.0", "id": 1, "method": "calculatenetworkfee", "params": ["bm90IGEgdHJhbnNhY3Rpb24K"]}"`, httpSrv.URL, t) - _ = checkErrGetResult(t, body, true, neorpc.InvalidParamsCode, "Invalid params") + _ = checkErrGetResult(t, body, true, tutusrpc.InvalidParamsCode, "Invalid params") }) calcReqExactly := func(t *testing.T, tx string) []byte { rpc := fmt.Sprintf(`{"jsonrpc": "2.0", "id": 1, "method": "calculatenetworkfee", "params": ["%s"]}"`, tx) @@ -3274,7 +3274,7 @@ func testRPCProtocol(t *testing.T, doRPCCall func(string, string, *testing.T) [] }}, } body := calcReq(t, tx) - _ = checkErrGetResult(t, body, true, neorpc.ErrInvalidVerificationFunctionCode, fmt.Sprintf("signer 0 (%s) has no verification script and no deployed contract", address.Uint160ToString(util.Uint160{1, 2, 3}))) + _ = checkErrGetResult(t, body, true, tutusrpc.ErrInvalidVerificationFunctionCode, fmt.Sprintf("signer 0 (%s) has no verification script and no deployed contract", address.Uint160ToString(util.Uint160{1, 2, 3}))) }) t.Run("contract with no verify", func(t *testing.T) { tx := &transaction.Transaction{ @@ -3286,7 +3286,7 @@ func testRPCProtocol(t *testing.T, doRPCCall func(string, string, *testing.T) [] }}, } body := calcReq(t, tx) - _ = checkErrGetResult(t, body, true, neorpc.ErrInvalidVerificationFunctionCode, "signer 0 has no verify method in deployed contract") + _ = checkErrGetResult(t, body, true, tutusrpc.ErrInvalidVerificationFunctionCode, "signer 0 has no verify method in deployed contract") }) t.Run("execution limit, fail", func(t *testing.T) { // 1_6000_0000 GAS with the default 1.5 allowed by Policy @@ -3301,7 +3301,7 @@ func testRPCProtocol(t *testing.T, doRPCCall func(string, string, *testing.T) [] }}, } body := calcReq(t, tx) - _ = checkErrGetResult(t, body, true, neorpc.ErrInvalidSignatureCode, "GAS limit exceeded") + _ = checkErrGetResult(t, body, true, tutusrpc.ErrInvalidSignatureCode, "GAS limit exceeded") }) checkCalc := func(t *testing.T, tx *transaction.Transaction, fee int64) { resp := checkErrGetResult(t, calcReq(t, tx), false, 0) @@ -3399,7 +3399,7 @@ func testRPCProtocol(t *testing.T, doRPCCall func(string, string, *testing.T) [] tx.Scripts[0].InvocationScript[10] = ^tx.Scripts[0].InvocationScript[10] rawTx := encodeBinaryToString(t, tx) body := doRPCCall(fmt.Sprintf(rpc, rawTx), httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.ErrInvalidSignatureCode) + checkErrGetResult(t, body, true, tutusrpc.ErrInvalidSignatureCode) }) t.Run("too big tx", func(t *testing.T) { script := make([]byte, transaction.MaxScriptLength) @@ -3436,7 +3436,7 @@ func testRPCProtocol(t *testing.T, doRPCCall func(string, string, *testing.T) [] } rawTx := encodeBinaryToString(t, tx) body := doRPCCall(fmt.Sprintf(rpc, rawTx), httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.ErrInvalidSizeCode) + checkErrGetResult(t, body, true, tutusrpc.ErrInvalidSizeCode) }) t.Run("mempool OOM", func(t *testing.T) { chain, _, httpSrv := initClearServerWithCustomConfig(t, func(c *config.Config) { @@ -3453,7 +3453,7 @@ func testRPCProtocol(t *testing.T, doRPCCall func(string, string, *testing.T) [] tx2 := newTxWithParams(t, chain, opcode.PUSH1, 10, 1, 1, false) rawTx2 := encodeBinaryToString(t, tx2) body2 := doRPCCall(fmt.Sprintf(rpc, rawTx2), httpSrv.URL, t) - checkErrGetResult(t, body2, true, neorpc.ErrMempoolCapReachedCode) + checkErrGetResult(t, body2, true, tutusrpc.ErrMempoolCapReachedCode) }) t.Run("mempool conflict", func(t *testing.T) { chain, _, httpSrv := initClearServerWithCustomConfig(t, func(c *config.Config) { @@ -3470,7 +3470,7 @@ func testRPCProtocol(t *testing.T, doRPCCall func(string, string, *testing.T) [] tx2 := newTxWithParams(t, chain, opcode.PUSH1, 10, 1, 25, false) rawTx2 := encodeBinaryToString(t, tx2) body2 := doRPCCall(fmt.Sprintf(rpc, rawTx2), httpSrv.URL, t) - checkErrGetResult(t, body2, true, neorpc.ErrInsufficientFundsCode) + checkErrGetResult(t, body2, true, tutusrpc.ErrInsufficientFundsCode) }) }) t.Run("test functions with unsupported states", func(t *testing.T) { @@ -3517,27 +3517,27 @@ func testRPCProtocol(t *testing.T, doRPCCall func(string, string, *testing.T) [] Signers: []transaction.Signer{{Account: util.Uint160{1, 2, 3}}}, } body := doRPCCall(fmt.Sprintf(rpc, encodeBinaryToJSON(t, tx)), httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.InvalidParamsCode) + checkErrGetResult(t, body, true, tutusrpc.InvalidParamsCode) }) t.Run("invalid header", func(t *testing.T) { body := doRPCCall(fmt.Sprintf(rpc, fmt.Sprintf(`%s, %s`, txStr, txStr)), httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.InvalidParamsCode) + checkErrGetResult(t, body, true, tutusrpc.InvalidParamsCode) }) t.Run("invalid trigger parameter", func(t *testing.T) { body := doRPCCall(fmt.Sprintf(rpc, fmt.Sprintf(`%s, %s, null`, txStr, hStr)), httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.InvalidParamsCode) + checkErrGetResult(t, body, true, tutusrpc.InvalidParamsCode) }) t.Run("invalid trigger", func(t *testing.T) { body := doRPCCall(fmt.Sprintf(rpc, fmt.Sprintf(`%s, %s, 123`, txStr, hStr)), httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.InvalidParamsCode) + checkErrGetResult(t, body, true, tutusrpc.InvalidParamsCode) }) t.Run("unsupported trigger", func(t *testing.T) { body := doRPCCall(fmt.Sprintf(rpc, fmt.Sprintf(`%s, %s, "%s"`, txStr, hStr, trigger.OnPersist)), httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.InvalidParamsCode) + checkErrGetResult(t, body, true, tutusrpc.InvalidParamsCode) }) t.Run("invalid verbose", func(t *testing.T) { body := doRPCCall(fmt.Sprintf(rpc, fmt.Sprintf(`%s, %s, "%s", null`, txStr, hStr, trigger.Application)), httpSrv.URL, t) - checkErrGetResult(t, body, true, neorpc.InvalidParamsCode) + checkErrGetResult(t, body, true, tutusrpc.InvalidParamsCode) }) t.Run("good, tx", func(t *testing.T) { body := doRPCCall(fmt.Sprintf(rpc, txStr), httpSrv.URL, t) @@ -3597,47 +3597,47 @@ func TestRPC_SubmitBlock(t *testing.T) { b := testchain.NewBlock(t, chain, 1, 0) b.Script.VerificationScript[8] ^= 0xff return b - }, neorpc.ErrVerificationFailedCode) + }, tutusrpc.ErrVerificationFailedCode) }) t.Run("already exists", func(t *testing.T) { check(t, func(chain *core.Blockchain) *block.Block { return testchain.NewBlock(t, chain, 0, 0, newTxWithParams(t, chain, opcode.PUSH1, 10, 0, 1, false)) - }, neorpc.ErrAlreadyExistsCode) + }, tutusrpc.ErrAlreadyExistsCode) }) t.Run("invalid height", func(t *testing.T) { check(t, func(chain *core.Blockchain) *block.Block { return testchain.NewBlock(t, chain, 2, 0, newTxWithParams(t, chain, opcode.PUSH1, 10, 0, 1, false)) - }, neorpc.ErrVerificationFailedCode) + }, tutusrpc.ErrVerificationFailedCode) }) t.Run("invalid script", func(t *testing.T) { check(t, func(chain *core.Blockchain) *block.Block { return testchain.NewBlock(t, chain, 1, 0, newTxWithParams(t, chain, 0xDD, 10, 0, 1, false)) - }, neorpc.ErrInvalidScriptCode) + }, tutusrpc.ErrInvalidScriptCode) }) t.Run("invalid ValidUntilBlock", func(t *testing.T) { check(t, func(chain *core.Blockchain) *block.Block { return testchain.NewBlock(t, chain, 1, 0, newTxWithParams(t, chain, opcode.PUSH1, 0, 0, 1, false)) - }, neorpc.ErrExpiredTransactionCode) + }, tutusrpc.ErrExpiredTransactionCode) }) t.Run("invalid SystemFee", func(t *testing.T) { check(t, func(chain *core.Blockchain) *block.Block { return testchain.NewBlock(t, chain, 1, 0, newTxWithParams(t, chain, opcode.PUSH1, 10, 999999999999, 1, false)) - }, neorpc.ErrPolicyFailedCode) + }, tutusrpc.ErrPolicyFailedCode) }) t.Run("invalid NetworkFee", func(t *testing.T) { check(t, func(chain *core.Blockchain) *block.Block { return testchain.NewBlock(t, chain, 1, 0, newTxWithParams(t, chain, opcode.PUSH1, 10, 0, 0, false)) - }, neorpc.ErrInsufficientNetworkFeeCode) + }, tutusrpc.ErrInsufficientNetworkFeeCode) }) t.Run("invalid attribute", func(t *testing.T) { check(t, func(chain *core.Blockchain) *block.Block { return testchain.NewBlock(t, chain, 1, 0, newTxWithParams(t, chain, opcode.PUSH1, 10, 0, 2, true)) - }, neorpc.ErrInvalidAttributeCode) + }, tutusrpc.ErrInvalidAttributeCode) }) t.Run("insufficient funds", func(t *testing.T) { check(t, func(chain *core.Blockchain) *block.Block { return testchain.NewBlock(t, chain, 1, 0, newTxWithParams(t, chain, opcode.PUSH1, 10, 899999999999, 1, false)) - }, neorpc.ErrInsufficientFundsCode) + }, tutusrpc.ErrInsufficientFundsCode) }) t.Run("positive", func(t *testing.T) { chain, _, httpSrv := initClearServerWithInMemoryChain(t) @@ -3709,7 +3709,7 @@ func (tc rpcTestCase) getResultPair(e *executor) (expected any, res any) { } func checkErrGetResult(t *testing.T, body []byte, expectingFail bool, expectedErrCode int64, expectedErr ...string) json.RawMessage { - var resp neorpc.Response + var resp tutusrpc.Response err := json.Unmarshal(body, &resp) require.Nil(t, err) if expectingFail { @@ -3727,7 +3727,7 @@ func checkErrGetResult(t *testing.T, body []byte, expectingFail bool, expectedEr } func checkErrGetBatchResult(t *testing.T, body []byte, expectingFail bool, expectedErrCode int64, expectedErr ...string) json.RawMessage { - var resp []neorpc.Response + var resp []tutusrpc.Response err := json.Unmarshal(body, &resp) require.Nil(t, err) require.Equal(t, 1, len(resp)) diff --git a/pkg/services/rpcsrv/subscription.go b/pkg/services/rpcsrv/subscription.go index 5c80f20..24ae2b9 100644 --- a/pkg/services/rpcsrv/subscription.go +++ b/pkg/services/rpcsrv/subscription.go @@ -4,7 +4,7 @@ import ( "sync/atomic" "github.com/gorilla/websocket" - "github.com/tutus-one/tutus-chain/pkg/neorpc" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc" ) type ( @@ -13,7 +13,7 @@ type ( // as well as internal ones. intEvent struct { msg *websocket.PreparedMessage - ntf *neorpc.Notification + ntf *tutusrpc.Notification } // subscriber is an event subscriber. subscriber struct { @@ -27,18 +27,18 @@ type ( } // feed stores subscriber's desired event ID with filter. feed struct { - event neorpc.EventID - filter neorpc.SubscriptionFilter + event tutusrpc.EventID + filter tutusrpc.SubscriptionFilter } ) -// EventID implements neorpc.EventComparator interface and returns notification ID. -func (f feed) EventID() neorpc.EventID { +// EventID implements tutusrpc.EventComparator interface and returns notification ID. +func (f feed) EventID() tutusrpc.EventID { return f.event } -// Filter implements neorpc.EventComparator interface and returns notification filter. -func (f feed) Filter() neorpc.SubscriptionFilter { +// Filter implements tutusrpc.EventComparator interface and returns notification filter. +func (f feed) Filter() tutusrpc.SubscriptionFilter { return f.filter } diff --git a/pkg/services/rpcsrv/subscription_test.go b/pkg/services/rpcsrv/subscription_test.go index 8068a52..14c16c1 100644 --- a/pkg/services/rpcsrv/subscription_test.go +++ b/pkg/services/rpcsrv/subscription_test.go @@ -16,7 +16,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core" "github.com/tutus-one/tutus-chain/pkg/core/transaction" "github.com/tutus-one/tutus-chain/pkg/encoding/address" - "github.com/tutus-one/tutus-chain/pkg/neorpc" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/stretchr/testify/require" @@ -58,8 +58,8 @@ readLoop: close(readerToExitCh) } -func callWSGetRaw(t *testing.T, ws *websocket.Conn, msg string, respCh <-chan []byte) *neorpc.Response { - var resp = new(neorpc.Response) +func callWSGetRaw(t *testing.T, ws *websocket.Conn, msg string, respCh <-chan []byte) *tutusrpc.Response { + var resp = new(tutusrpc.Response) require.NoError(t, ws.SetWriteDeadline(time.Now().Add(5*time.Second))) require.NoError(t, ws.WriteMessage(websocket.TextMessage, []byte(msg))) @@ -69,8 +69,8 @@ func callWSGetRaw(t *testing.T, ws *websocket.Conn, msg string, respCh <-chan [] return resp } -func getNotification(t *testing.T, respCh <-chan []byte) *neorpc.Notification { - var resp = new(neorpc.Notification) +func getNotification(t *testing.T, respCh <-chan []byte) *tutusrpc.Notification { + var resp = new(tutusrpc.Notification) body := <-respCh require.NoError(t, json.Unmarshal(body, resp)) return resp @@ -149,10 +149,10 @@ func TestSubscriptions(t *testing.T) { for _, b := range getTestBlocks(t) { require.NoError(t, chain.AddBlock(b)) resp := getNotification(t, respMsgs) - require.Equal(t, neorpc.ExecutionEventID, resp.Event) + require.Equal(t, tutusrpc.ExecutionEventID, resp.Event) for { resp = getNotification(t, respMsgs) - if resp.Event != neorpc.NotificationEventID { + if resp.Event != tutusrpc.NotificationEventID { break } } @@ -160,27 +160,27 @@ func TestSubscriptions(t *testing.T) { if i > 0 { resp = getNotification(t, respMsgs) } - require.Equal(t, neorpc.ExecutionEventID, resp.Event) + require.Equal(t, tutusrpc.ExecutionEventID, resp.Event) for { resp := getNotification(t, respMsgs) - if resp.Event == neorpc.NotificationEventID { + if resp.Event == tutusrpc.NotificationEventID { continue } - require.Equal(t, neorpc.TransactionEventID, resp.Event) + require.Equal(t, tutusrpc.TransactionEventID, resp.Event) break } } resp = getNotification(t, respMsgs) - require.Equal(t, neorpc.ExecutionEventID, resp.Event) + require.Equal(t, tutusrpc.ExecutionEventID, resp.Event) for { resp = getNotification(t, respMsgs) - if resp.Event != neorpc.NotificationEventID { + if resp.Event != tutusrpc.NotificationEventID { break } } - require.Equal(t, neorpc.HeaderOfAddedBlockEventID, resp.Event) + require.Equal(t, tutusrpc.HeaderOfAddedBlockEventID, resp.Event) resp = getNotification(t, respMsgs) - require.Equal(t, neorpc.BlockEventID, resp.Event) + require.Equal(t, tutusrpc.BlockEventID, resp.Event) } // We should manually add NotaryRequest to test notification. @@ -189,7 +189,7 @@ func TestSubscriptions(t *testing.T) { require.NoError(t, err) for { resp := getNotification(t, respMsgs) - if resp.Event == neorpc.NotaryRequestEventID { + if resp.Event == tutusrpc.NotaryRequestEventID { break } } @@ -203,11 +203,11 @@ func TestSubscriptions(t *testing.T) { require.NoError(t, chain.GetMemPool().Add(tx, &FeerStub{})) e := getNotification(t, respMsgs) - require.Equal(t, neorpc.MempoolEventID, e.Event) + require.Equal(t, tutusrpc.MempoolEventID, e.Event) chain.GetMemPool().Remove(tx.Hash()) e2 := getNotification(t, respMsgs) - require.Equal(t, neorpc.MempoolEventID, e2.Event) + require.Equal(t, tutusrpc.MempoolEventID, e2.Event) for _, id := range subIDs { callUnsubscribe(t, c, respMsgs, id) @@ -220,15 +220,15 @@ func TestFilteredSubscriptions(t *testing.T) { var cases = map[string]struct { params string - check func(*testing.T, *neorpc.Notification) + check func(*testing.T, *tutusrpc.Notification) shouldCheck bool }{ "tx matching sender": { params: `["transaction_added", {"sender":"` + goodSender.StringLE() + `"}]`, shouldCheck: true, - check: func(t *testing.T, resp *neorpc.Notification) { + check: func(t *testing.T, resp *tutusrpc.Notification) { rmap := resp.Payload[0].(map[string]any) - require.Equal(t, neorpc.TransactionEventID, resp.Event) + require.Equal(t, tutusrpc.TransactionEventID, resp.Event) sender := rmap["sender"].(string) require.Equal(t, address.Uint160ToString(goodSender), sender) }, @@ -236,9 +236,9 @@ func TestFilteredSubscriptions(t *testing.T) { "tx matching signer": { params: `["transaction_added", {"signer":"` + goodSender.StringLE() + `"}]`, shouldCheck: true, - check: func(t *testing.T, resp *neorpc.Notification) { + check: func(t *testing.T, resp *tutusrpc.Notification) { rmap := resp.Payload[0].(map[string]any) - require.Equal(t, neorpc.TransactionEventID, resp.Event) + require.Equal(t, tutusrpc.TransactionEventID, resp.Event) signers := rmap["signers"].([]any) signer0 := signers[0].(map[string]any) signer0acc := signer0["account"].(string) @@ -248,9 +248,9 @@ func TestFilteredSubscriptions(t *testing.T) { "tx matching sender and signer": { params: `["transaction_added", {"sender":"` + goodSender.StringLE() + `", "signer":"` + goodSender.StringLE() + `"}]`, shouldCheck: true, - check: func(t *testing.T, resp *neorpc.Notification) { + check: func(t *testing.T, resp *tutusrpc.Notification) { rmap := resp.Payload[0].(map[string]any) - require.Equal(t, neorpc.TransactionEventID, resp.Event) + require.Equal(t, tutusrpc.TransactionEventID, resp.Event) sender := rmap["sender"].(string) require.Equal(t, address.Uint160ToString(goodSender), sender) signers := rmap["signers"].([]any) @@ -262,9 +262,9 @@ func TestFilteredSubscriptions(t *testing.T) { "notification matching contract hash": { params: `["notification_from_execution", {"contract":"` + testContractHashLE + `"}]`, shouldCheck: true, - check: func(t *testing.T, resp *neorpc.Notification) { + check: func(t *testing.T, resp *tutusrpc.Notification) { rmap := resp.Payload[0].(map[string]any) - require.Equal(t, neorpc.NotificationEventID, resp.Event) + require.Equal(t, tutusrpc.NotificationEventID, resp.Event) c := rmap["contract"].(string) require.Equal(t, "0x"+testContractHashLE, c) }, @@ -272,9 +272,9 @@ func TestFilteredSubscriptions(t *testing.T) { "notification matching name": { params: `["notification_from_execution", {"name":"Transfer"}]`, shouldCheck: true, - check: func(t *testing.T, resp *neorpc.Notification) { + check: func(t *testing.T, resp *tutusrpc.Notification) { rmap := resp.Payload[0].(map[string]any) - require.Equal(t, neorpc.NotificationEventID, resp.Event) + require.Equal(t, tutusrpc.NotificationEventID, resp.Event) n := rmap["eventname"].(string) require.Equal(t, "Transfer", n) }, @@ -282,9 +282,9 @@ func TestFilteredSubscriptions(t *testing.T) { "notification matching contract hash and name": { params: `["notification_from_execution", {"contract":"` + testContractHashLE + `", "name":"Transfer"}]`, shouldCheck: true, - check: func(t *testing.T, resp *neorpc.Notification) { + check: func(t *testing.T, resp *tutusrpc.Notification) { rmap := resp.Payload[0].(map[string]any) - require.Equal(t, neorpc.NotificationEventID, resp.Event) + require.Equal(t, tutusrpc.NotificationEventID, resp.Event) c := rmap["contract"].(string) require.Equal(t, "0x"+testContractHashLE, c) n := rmap["eventname"].(string) @@ -294,9 +294,9 @@ func TestFilteredSubscriptions(t *testing.T) { "notification matching contract hash and parameter": { params: `["notification_from_execution", {"contract":"` + testContractHashLE + `", "parameters":[{"type":"Any","value":null},{"type":"Hash160","value":"` + testContractHashLE + `"}]}]`, shouldCheck: true, - check: func(t *testing.T, resp *neorpc.Notification) { + check: func(t *testing.T, resp *tutusrpc.Notification) { rmap := resp.Payload[0].(map[string]any) - require.Equal(t, neorpc.NotificationEventID, resp.Event) + require.Equal(t, tutusrpc.NotificationEventID, resp.Event) c := rmap["contract"].(string) require.Equal(t, "0x"+testContractHashLE, c) // It should be exact unique "Init" call sending all the tokens to the contract itself. @@ -317,16 +317,16 @@ func TestFilteredSubscriptions(t *testing.T) { "notification matching contract hash but unknown parameter": { params: `["notification_from_execution", {"contract":"` + testContractHashLE + `", "parameters":[{"type":"Any","value":null},{"type":"Hash160","value":"ffffffffffffffffffffffffffffffffffffffff"}]}]`, shouldCheck: false, - check: func(t *testing.T, resp *neorpc.Notification) { + check: func(t *testing.T, resp *tutusrpc.Notification) { t.Fatal("this filter should not return any notification from test contract") }, }, "execution matching state": { params: `["transaction_executed", {"state":"HALT"}]`, shouldCheck: true, - check: func(t *testing.T, resp *neorpc.Notification) { + check: func(t *testing.T, resp *tutusrpc.Notification) { rmap := resp.Payload[0].(map[string]any) - require.Equal(t, neorpc.ExecutionEventID, resp.Event) + require.Equal(t, tutusrpc.ExecutionEventID, resp.Event) st := rmap["vmstate"].(string) require.Equal(t, "HALT", st) }, @@ -334,9 +334,9 @@ func TestFilteredSubscriptions(t *testing.T) { "execution matching container": { params: `["transaction_executed", {"container":"` + deploymentTxHash + `"}]`, shouldCheck: true, - check: func(t *testing.T, resp *neorpc.Notification) { + check: func(t *testing.T, resp *tutusrpc.Notification) { rmap := resp.Payload[0].(map[string]any) - require.Equal(t, neorpc.ExecutionEventID, resp.Event) + require.Equal(t, tutusrpc.ExecutionEventID, resp.Event) tx := rmap["container"].(string) require.Equal(t, "0x"+deploymentTxHash, tx) }, @@ -344,9 +344,9 @@ func TestFilteredSubscriptions(t *testing.T) { "execution matching state and container": { params: `["transaction_executed", {"state":"HALT", "container":"` + deploymentTxHash + `"}]`, shouldCheck: true, - check: func(t *testing.T, resp *neorpc.Notification) { + check: func(t *testing.T, resp *tutusrpc.Notification) { rmap := resp.Payload[0].(map[string]any) - require.Equal(t, neorpc.ExecutionEventID, resp.Event) + require.Equal(t, tutusrpc.ExecutionEventID, resp.Event) tx := rmap["container"].(string) require.Equal(t, "0x"+deploymentTxHash, tx) st := rmap["vmstate"].(string) @@ -356,14 +356,14 @@ func TestFilteredSubscriptions(t *testing.T) { "tx non-matching": { params: `["transaction_added", {"sender":"00112233445566778899aabbccddeeff00112233"}]`, shouldCheck: false, - check: func(t *testing.T, _ *neorpc.Notification) { + check: func(t *testing.T, _ *tutusrpc.Notification) { t.Fatal("unexpected match for EnrollmentTransaction") }, }, "notification non-matching": { params: `["notification_from_execution", {"contract":"00112233445566778899aabbccddeeff00112233"}]`, shouldCheck: false, - check: func(t *testing.T, _ *neorpc.Notification) { + check: func(t *testing.T, _ *tutusrpc.Notification) { t.Fatal("unexpected match for contract 00112233445566778899aabbccddeeff00112233") }, }, @@ -371,16 +371,16 @@ func TestFilteredSubscriptions(t *testing.T) { // We have single FAULTed transaction in chain, this, use the wrong hash for this test instead of FAULT state. params: `["transaction_executed", {"container":"0x` + util.Uint256{}.StringLE() + `"}]`, shouldCheck: false, - check: func(t *testing.T, n *neorpc.Notification) { + check: func(t *testing.T, n *tutusrpc.Notification) { t.Fatal("unexpected match for faulted execution") }, }, "header of added block": { params: `["header_of_added_block", {"primary": 0, "since": 5}]`, shouldCheck: true, - check: func(t *testing.T, resp *neorpc.Notification) { + check: func(t *testing.T, resp *tutusrpc.Notification) { rmap := resp.Payload[0].(map[string]any) - require.Equal(t, neorpc.HeaderOfAddedBlockEventID, resp.Event) + require.Equal(t, tutusrpc.HeaderOfAddedBlockEventID, resp.Event) primary := rmap["primary"].(float64) require.Equal(t, 0, int(primary)) index := rmap["index"].(float64) @@ -409,7 +409,7 @@ func TestFilteredSubscriptions(t *testing.T) { for { resp := getNotification(t, respMsgs) rmap := resp.Payload[0].(map[string]any) - if resp.Event == neorpc.BlockEventID { + if resp.Event == tutusrpc.BlockEventID { index := rmap["index"].(float64) if uint32(index) == lastBlock { break @@ -442,36 +442,36 @@ func TestFilteredMempoolSubscriptions(t *testing.T) { var cases = map[string]struct { params string - check func(*testing.T, *neorpc.Notification) + check func(*testing.T, *tutusrpc.Notification) }{ "mempool_event matching type": { params: `["mempool_event", {"type":"added"}]`, - check: func(t *testing.T, resp *neorpc.Notification) { - require.Equal(t, neorpc.MempoolEventID, resp.Event) + check: func(t *testing.T, resp *tutusrpc.Notification) { + require.Equal(t, tutusrpc.MempoolEventID, resp.Event) rmap := resp.Payload[0].(map[string]any) require.Equal(t, "added", rmap["type"].(string)) }, }, "mempool_event matching sender": { params: `["mempool_event", {"sender":"` + goodSender.StringLE() + `"}]`, - check: func(t *testing.T, resp *neorpc.Notification) { - require.Equal(t, neorpc.MempoolEventID, resp.Event) + check: func(t *testing.T, resp *tutusrpc.Notification) { + require.Equal(t, tutusrpc.MempoolEventID, resp.Event) txMap := resp.Payload[0].(map[string]any)["transaction"].(map[string]any) require.Equal(t, address.Uint160ToString(goodSender), txMap["sender"].(string)) }, }, "mempool_event matching signer": { params: `["mempool_event", {"signer":"` + goodSender.StringLE() + `"}]`, - check: func(t *testing.T, resp *neorpc.Notification) { - require.Equal(t, neorpc.MempoolEventID, resp.Event) + check: func(t *testing.T, resp *tutusrpc.Notification) { + require.Equal(t, tutusrpc.MempoolEventID, resp.Event) txMap := resp.Payload[0].(map[string]any)["transaction"].(map[string]any) require.Equal(t, "0x"+goodSender.StringLE(), txMap["signers"].([]any)[0].(map[string]any)["account"].(string)) }, }, "mempool_event matching sender, signer and type": { params: `["mempool_event", {"sender":"` + goodSender.StringLE() + `", "signer":"` + goodSender.StringLE() + `", "type":"added"}]`, - check: func(t *testing.T, resp *neorpc.Notification) { - require.Equal(t, neorpc.MempoolEventID, resp.Event) + check: func(t *testing.T, resp *tutusrpc.Notification) { + require.Equal(t, tutusrpc.MempoolEventID, resp.Event) rmap := resp.Payload[0].(map[string]any) require.Equal(t, "added", rmap["type"].(string)) txMap := rmap["transaction"].(map[string]any) @@ -509,13 +509,13 @@ func TestFilteredNotaryRequestSubscriptions(t *testing.T) { var cases = map[string]struct { params string - check func(*testing.T, *neorpc.Notification) + check func(*testing.T, *tutusrpc.Notification) }{ "matching sender": { params: `["notary_request_event", {"sender":"` + goodSender.StringLE() + `"}]`, - check: func(t *testing.T, resp *neorpc.Notification) { + check: func(t *testing.T, resp *tutusrpc.Notification) { rmap := resp.Payload[0].(map[string]any) - require.Equal(t, neorpc.NotaryRequestEventID, resp.Event) + require.Equal(t, tutusrpc.NotaryRequestEventID, resp.Event) require.Equal(t, "added", rmap["type"].(string)) req := rmap["notaryrequest"].(map[string]any) fbTx := req["fallbacktx"].(map[string]any) @@ -525,9 +525,9 @@ func TestFilteredNotaryRequestSubscriptions(t *testing.T) { }, "matching signer": { params: `["notary_request_event", {"signer":"` + goodSender.StringLE() + `"}]`, - check: func(t *testing.T, resp *neorpc.Notification) { + check: func(t *testing.T, resp *tutusrpc.Notification) { rmap := resp.Payload[0].(map[string]any) - require.Equal(t, neorpc.NotaryRequestEventID, resp.Event) + require.Equal(t, tutusrpc.NotaryRequestEventID, resp.Event) require.Equal(t, "added", rmap["type"].(string)) req := rmap["notaryrequest"].(map[string]any) mainTx := req["maintx"].(map[string]any) @@ -539,17 +539,17 @@ func TestFilteredNotaryRequestSubscriptions(t *testing.T) { }, "matching type": { params: `["notary_request_event", {"type":"added"}]`, - check: func(t *testing.T, resp *neorpc.Notification) { - require.Equal(t, neorpc.NotaryRequestEventID, resp.Event) + check: func(t *testing.T, resp *tutusrpc.Notification) { + require.Equal(t, tutusrpc.NotaryRequestEventID, resp.Event) rmap := resp.Payload[0].(map[string]any) require.Equal(t, "added", rmap["type"].(string)) }, }, "matching sender, signer and type": { params: `["notary_request_event", {"sender":"` + goodSender.StringLE() + `", "signer":"` + goodSender.StringLE() + `","type":"added"}]`, - check: func(t *testing.T, resp *neorpc.Notification) { + check: func(t *testing.T, resp *tutusrpc.Notification) { rmap := resp.Payload[0].(map[string]any) - require.Equal(t, neorpc.NotaryRequestEventID, resp.Event) + require.Equal(t, tutusrpc.NotaryRequestEventID, resp.Event) require.Equal(t, "added", rmap["type"].(string)) req := rmap["notaryrequest"].(map[string]any) mainTx := req["maintx"].(map[string]any) @@ -581,7 +581,7 @@ func TestFilteredNotaryRequestSubscriptions(t *testing.T) { require.NoError(t, err) nonce++ - var resp = new(neorpc.Notification) + var resp = new(tutusrpc.Notification) select { case body := <-respMsgs: require.NoError(t, json.Unmarshal(body, resp)) @@ -589,7 +589,7 @@ func TestFilteredNotaryRequestSubscriptions(t *testing.T) { t.Fatal("timeout waiting for event") } - require.Equal(t, neorpc.NotaryRequestEventID, resp.Event) + require.Equal(t, tutusrpc.NotaryRequestEventID, resp.Event) this.check(t, resp) callUnsubscribe(t, c, respMsgs, subID) @@ -616,7 +616,7 @@ func TestFilteredBlockSubscriptions(t *testing.T) { } for range expectedCnt { - var resp = new(neorpc.Notification) + var resp = new(tutusrpc.Notification) select { case body := <-respMsgs: require.NoError(t, json.Unmarshal(body, resp)) @@ -624,7 +624,7 @@ func TestFilteredBlockSubscriptions(t *testing.T) { t.Fatal("timeout waiting for event") } - require.Equal(t, neorpc.BlockEventID, resp.Event) + require.Equal(t, tutusrpc.BlockEventID, resp.Event) rmap := resp.Payload[0].(map[string]any) primary := rmap["primary"].(float64) require.Equal(t, 3, int(primary)) @@ -649,7 +649,7 @@ func TestHeaderOfAddedBlockSubscriptions(t *testing.T) { } for range expectedCnt { - var resp = new(neorpc.Notification) + var resp = new(tutusrpc.Notification) select { case body := <-respMsgs: require.NoError(t, json.Unmarshal(body, resp)) @@ -657,7 +657,7 @@ func TestHeaderOfAddedBlockSubscriptions(t *testing.T) { t.Fatal("timeout waiting for event") } - require.Equal(t, neorpc.HeaderOfAddedBlockEventID, resp.Event) + require.Equal(t, tutusrpc.HeaderOfAddedBlockEventID, resp.Event) rmap := resp.Payload[0].(map[string]any) primary := rmap["primary"].(float64) require.Equal(t, 3, int(primary)) @@ -819,8 +819,8 @@ func TestSubscriptionOverflow(t *testing.T) { } for range blockCnt { resp := getNotification(t, respMsgs) - if resp.Event != neorpc.BlockEventID { - require.Equal(t, neorpc.MissedEventID, resp.Event) + if resp.Event != tutusrpc.BlockEventID { + require.Equal(t, tutusrpc.MissedEventID, resp.Event) receivedMiss = true break } @@ -848,7 +848,7 @@ func TestFilteredSubscriptions_InvalidFilter(t *testing.T) { resp := callWSGetRaw(t, c, fmt.Sprintf(`{"jsonrpc": "2.0","method": "subscribe","params": %s,"id": 1}`, this.params), respMsgs) require.NotNil(t, resp.Error) require.Nil(t, resp.Result) - require.Contains(t, resp.Error.Error(), neorpc.ErrInvalidSubscriptionFilter.Error()) + require.Contains(t, resp.Error.Error(), tutusrpc.ErrInvalidSubscriptionFilter.Error()) }) } } diff --git a/pkg/services/rpcsrv/tokens.go b/pkg/services/rpcsrv/tokens.go index 91086e9..c581a9f 100644 --- a/pkg/services/rpcsrv/tokens.go +++ b/pkg/services/rpcsrv/tokens.go @@ -1,7 +1,7 @@ package rpcsrv import ( - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" ) // tokenTransfers is a generic type used to represent NEP-11 and NEP-17 transfers. diff --git a/pkg/services/stateroot/service_test.go b/pkg/services/stateroot/service_test.go index f11ae3c..4b354e8 100644 --- a/pkg/services/stateroot/service_test.go +++ b/pkg/services/stateroot/service_test.go @@ -23,8 +23,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/crypto/keys" "github.com/tutus-one/tutus-chain/pkg/interop/native/roles" "github.com/tutus-one/tutus-chain/pkg/io" - "github.com/tutus-one/tutus-chain/pkg/neotest" - "github.com/tutus-one/tutus-chain/pkg/neotest/chain" + "github.com/tutus-one/tutus-chain/pkg/tutustest" + "github.com/tutus-one/tutus-chain/pkg/tutustest/chain" "github.com/tutus-one/tutus-chain/pkg/network/payload" "github.com/tutus-one/tutus-chain/pkg/services/stateroot" "github.com/tutus-one/tutus-chain/pkg/smartcontract" diff --git a/pkg/smartcontract/binding/generate.go b/pkg/smartcontract/binding/generate.go index fd4bbe0..ded2684 100644 --- a/pkg/smartcontract/binding/generate.go +++ b/pkg/smartcontract/binding/generate.go @@ -25,10 +25,10 @@ func {{.Name}}({{range $index, $arg := .Arguments -}} {{- if ne $index 0}}, {{end}} {{- .Name}} {{.Type}} {{- end}}) {{if .ReturnType }}{{ .ReturnType }} { - return neogointernal.CallWithToken(Hash, "{{ .NameABI }}", int(contract.{{ .CallFlag }}) + return tutusinternal.CallWithToken(Hash, "{{ .NameABI }}", int(contract.{{ .CallFlag }}) {{- range $arg := .Arguments -}}, {{.Name}}{{end}}).({{ .ReturnType }}) {{- else -}} { - neogointernal.CallWithTokenNoRet(Hash, "{{ .NameABI }}", int(contract.{{ .CallFlag }}) + tutusinternal.CallWithTokenNoRet(Hash, "{{ .NameABI }}", int(contract.{{ .CallFlag }}) {{- range $arg := .Arguments -}}, {{.Name}}{{end}}) {{- end}} } @@ -157,7 +157,7 @@ func Generate(cfg Config) error { ctr := TemplateFromManifest(cfg, scTypeToGo) ctr.Imports = append(ctr.Imports, "github.com/tutus-one/tutus-chain/pkg/interop/contract") if ctr.Hash != "" { - ctr.Imports = append(ctr.Imports, "github.com/tutus-one/tutus-chain/pkg/interop/neogointernal") + ctr.Imports = append(ctr.Imports, "github.com/tutus-one/tutus-chain/pkg/interop/tutusinternal") } slices.Sort(ctr.Imports) diff --git a/pkg/smartcontract/doc_test.go b/pkg/smartcontract/doc_test.go index 8b45a7e..9bb32c0 100644 --- a/pkg/smartcontract/doc_test.go +++ b/pkg/smartcontract/doc_test.go @@ -7,7 +7,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/rpcclient" "github.com/tutus-one/tutus-chain/pkg/rpcclient/actor" "github.com/tutus-one/tutus-chain/pkg/rpcclient/gas" - "github.com/tutus-one/tutus-chain/pkg/rpcclient/neo" + "github.com/tutus-one/tutus-chain/pkg/rpcclient/tutus" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/wallet" @@ -27,8 +27,8 @@ func ExampleBuilder() { b := smartcontract.NewBuilder() // Transfer + vote in a single script with each action leaving return value on the stack. - b.InvokeMethod(neo.Hash, "transfer", a.Sender(), util.Uint160{0xff}, 1, nil) - b.InvokeMethod(neo.Hash, "vote", pKey) + b.InvokeMethod(tutus.Hash, "transfer", a.Sender(), util.Uint160{0xff}, 1, nil) + b.InvokeMethod(tutus.Hash, "vote", pKey) script, _ := b.Script() // Actor has an Invoker inside, so we can perform test invocation using the script. @@ -51,9 +51,9 @@ func ExampleBuilder() { // Multiple transfers of different tokens in a single script. If any of // them fails whole script fails. - b.InvokeWithAssert(neo.Hash, "transfer", a.Sender(), util.Uint160{0x70}, 1, nil) + b.InvokeWithAssert(tutus.Hash, "transfer", a.Sender(), util.Uint160{0x70}, 1, nil) b.InvokeWithAssert(gas.Hash, "transfer", a.Sender(), util.Uint160{0x71}, 100000, []byte("data")) - b.InvokeWithAssert(neo.Hash, "transfer", a.Sender(), util.Uint160{0x72}, 1, nil) + b.InvokeWithAssert(tutus.Hash, "transfer", a.Sender(), util.Uint160{0x72}, 1, nil) script, _ = b.Script() // Now send a transaction with this script via an RPC node. diff --git a/pkg/smartcontract/manifest/manifest.go b/pkg/smartcontract/manifest/manifest.go index aad954c..54a9489 100644 --- a/pkg/smartcontract/manifest/manifest.go +++ b/pkg/smartcontract/manifest/manifest.go @@ -10,7 +10,7 @@ import ( "slices" "strings" - ojson "github.com/nspcc-dev/go-ordered-json" + ojson "github.com/tutus-one/tutus-ordered-json" "github.com/tutus-one/tutus-chain/pkg/util" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" ) diff --git a/pkg/smartcontract/rpcbinding/binding.go b/pkg/smartcontract/rpcbinding/binding.go index 6a04657..3844850 100644 --- a/pkg/smartcontract/rpcbinding/binding.go +++ b/pkg/smartcontract/rpcbinding/binding.go @@ -1098,7 +1098,7 @@ func scTemplateToRPC(cfg binding.Config, ctr ContractTmpl, imports map[string]st } if len(ctr.CustomEvents) > 0 { - imports["github.com/tutus-one/tutus-chain/pkg/neorpc/result"] = struct{}{} + imports["github.com/tutus-one/tutus-chain/pkg/tutusrpc/result"] = struct{}{} imports["github.com/tutus-one/tutus-chain/pkg/vm/stackitem"] = struct{}{} imports["fmt"] = struct{}{} imports["errors"] = struct{}{} @@ -1111,7 +1111,7 @@ func scTemplateToRPC(cfg binding.Config, ctr ContractTmpl, imports map[string]st if abim.ReturnType == smartcontract.InteropInterfaceType { imports["github.com/google/uuid"] = struct{}{} imports["github.com/tutus-one/tutus-chain/pkg/vm/stackitem"] = struct{}{} - imports["github.com/tutus-one/tutus-chain/pkg/neorpc/result"] = struct{}{} + imports["github.com/tutus-one/tutus-chain/pkg/tutusrpc/result"] = struct{}{} ctr.SafeMethods[i].ReturnType = "uuid.UUID, result.Iterator" ctr.SafeMethods[i].Unwrapper = "SessionIterator" ctr.HasIterator = true @@ -1164,7 +1164,7 @@ func scTemplateToRPC(cfg binding.Config, ctr ContractTmpl, imports map[string]st if len(ctr.SafeMethods) > 0 { imports["github.com/tutus-one/tutus-chain/pkg/rpcclient/unwrap"] = struct{}{} if !ctr.IsNep17 && !ctr.IsNep11D && !ctr.IsNep11ND && !ctr.IsNep24 { - imports["github.com/tutus-one/tutus-chain/pkg/neorpc/result"] = struct{}{} + imports["github.com/tutus-one/tutus-chain/pkg/tutusrpc/result"] = struct{}{} } } if len(ctr.Methods) > 0 { diff --git a/pkg/neorpc/errors.go b/pkg/tutusrpc/errors.go similarity index 99% rename from pkg/neorpc/errors.go rename to pkg/tutusrpc/errors.go index 512865b..ffea7d9 100644 --- a/pkg/neorpc/errors.go +++ b/pkg/tutusrpc/errors.go @@ -1,4 +1,4 @@ -package neorpc +package tutusrpc import ( "errors" diff --git a/pkg/neorpc/errors_test.go b/pkg/tutusrpc/errors_test.go similarity index 98% rename from pkg/neorpc/errors_test.go rename to pkg/tutusrpc/errors_test.go index f9fa212..a976fea 100644 --- a/pkg/neorpc/errors_test.go +++ b/pkg/tutusrpc/errors_test.go @@ -1,4 +1,4 @@ -package neorpc +package tutusrpc import ( "errors" diff --git a/pkg/neorpc/events.go b/pkg/tutusrpc/events.go similarity index 99% rename from pkg/neorpc/events.go rename to pkg/tutusrpc/events.go index 22c7800..3e12ef0 100644 --- a/pkg/neorpc/events.go +++ b/pkg/tutusrpc/events.go @@ -1,4 +1,4 @@ -package neorpc +package tutusrpc import ( "encoding/json" diff --git a/pkg/neorpc/filters.go b/pkg/tutusrpc/filters.go similarity index 99% rename from pkg/neorpc/filters.go rename to pkg/tutusrpc/filters.go index 5708bd1..2fe6f02 100644 --- a/pkg/neorpc/filters.go +++ b/pkg/tutusrpc/filters.go @@ -1,4 +1,4 @@ -package neorpc +package tutusrpc import ( "errors" diff --git a/pkg/neorpc/filters_test.go b/pkg/tutusrpc/filters_test.go similarity index 99% rename from pkg/neorpc/filters_test.go rename to pkg/tutusrpc/filters_test.go index ca1874f..438707c 100644 --- a/pkg/neorpc/filters_test.go +++ b/pkg/tutusrpc/filters_test.go @@ -1,4 +1,4 @@ -package neorpc +package tutusrpc import ( "testing" diff --git a/pkg/neorpc/result/application_log.go b/pkg/tutusrpc/result/application_log.go similarity index 100% rename from pkg/neorpc/result/application_log.go rename to pkg/tutusrpc/result/application_log.go diff --git a/pkg/neorpc/result/block.go b/pkg/tutusrpc/result/block.go similarity index 100% rename from pkg/neorpc/result/block.go rename to pkg/tutusrpc/result/block.go diff --git a/pkg/neorpc/result/block_header.go b/pkg/tutusrpc/result/block_header.go similarity index 100% rename from pkg/neorpc/result/block_header.go rename to pkg/tutusrpc/result/block_header.go diff --git a/pkg/neorpc/result/block_notifications.go b/pkg/tutusrpc/result/block_notifications.go similarity index 100% rename from pkg/neorpc/result/block_notifications.go rename to pkg/tutusrpc/result/block_notifications.go diff --git a/pkg/neorpc/result/findstates.go b/pkg/tutusrpc/result/findstates.go similarity index 100% rename from pkg/neorpc/result/findstates.go rename to pkg/tutusrpc/result/findstates.go diff --git a/pkg/neorpc/result/findstorage.go b/pkg/tutusrpc/result/findstorage.go similarity index 100% rename from pkg/neorpc/result/findstorage.go rename to pkg/tutusrpc/result/findstorage.go diff --git a/pkg/neorpc/result/invoke.go b/pkg/tutusrpc/result/invoke.go similarity index 100% rename from pkg/neorpc/result/invoke.go rename to pkg/tutusrpc/result/invoke.go diff --git a/pkg/neorpc/result/invoke_test.go b/pkg/tutusrpc/result/invoke_test.go similarity index 100% rename from pkg/neorpc/result/invoke_test.go rename to pkg/tutusrpc/result/invoke_test.go diff --git a/pkg/neorpc/result/mempool_event.go b/pkg/tutusrpc/result/mempool_event.go similarity index 100% rename from pkg/neorpc/result/mempool_event.go rename to pkg/tutusrpc/result/mempool_event.go diff --git a/pkg/neorpc/result/mpt.go b/pkg/tutusrpc/result/mpt.go similarity index 100% rename from pkg/neorpc/result/mpt.go rename to pkg/tutusrpc/result/mpt.go diff --git a/pkg/neorpc/result/mpt_test.go b/pkg/tutusrpc/result/mpt_test.go similarity index 100% rename from pkg/neorpc/result/mpt_test.go rename to pkg/tutusrpc/result/mpt_test.go diff --git a/pkg/neorpc/result/netfee.go b/pkg/tutusrpc/result/netfee.go similarity index 100% rename from pkg/neorpc/result/netfee.go rename to pkg/tutusrpc/result/netfee.go diff --git a/pkg/neorpc/result/notary_request_event.go b/pkg/tutusrpc/result/notary_request_event.go similarity index 100% rename from pkg/neorpc/result/notary_request_event.go rename to pkg/tutusrpc/result/notary_request_event.go diff --git a/pkg/neorpc/result/peers.go b/pkg/tutusrpc/result/peers.go similarity index 100% rename from pkg/neorpc/result/peers.go rename to pkg/tutusrpc/result/peers.go diff --git a/pkg/neorpc/result/peers_test.go b/pkg/tutusrpc/result/peers_test.go similarity index 100% rename from pkg/neorpc/result/peers_test.go rename to pkg/tutusrpc/result/peers_test.go diff --git a/pkg/neorpc/result/raw_mempool.go b/pkg/tutusrpc/result/raw_mempool.go similarity index 100% rename from pkg/neorpc/result/raw_mempool.go rename to pkg/tutusrpc/result/raw_mempool.go diff --git a/pkg/neorpc/result/raw_notary_pool.go b/pkg/tutusrpc/result/raw_notary_pool.go similarity index 100% rename from pkg/neorpc/result/raw_notary_pool.go rename to pkg/tutusrpc/result/raw_notary_pool.go diff --git a/pkg/neorpc/result/relay_result.go b/pkg/tutusrpc/result/relay_result.go similarity index 100% rename from pkg/neorpc/result/relay_result.go rename to pkg/tutusrpc/result/relay_result.go diff --git a/pkg/neorpc/result/tokens.go b/pkg/tutusrpc/result/tokens.go similarity index 100% rename from pkg/neorpc/result/tokens.go rename to pkg/tutusrpc/result/tokens.go diff --git a/pkg/neorpc/result/tx_raw_output.go b/pkg/tutusrpc/result/tx_raw_output.go similarity index 100% rename from pkg/neorpc/result/tx_raw_output.go rename to pkg/tutusrpc/result/tx_raw_output.go diff --git a/pkg/neorpc/result/unclaimed_gas.go b/pkg/tutusrpc/result/unclaimed_gas.go similarity index 100% rename from pkg/neorpc/result/unclaimed_gas.go rename to pkg/tutusrpc/result/unclaimed_gas.go diff --git a/pkg/neorpc/result/validate_address.go b/pkg/tutusrpc/result/validate_address.go similarity index 100% rename from pkg/neorpc/result/validate_address.go rename to pkg/tutusrpc/result/validate_address.go diff --git a/pkg/neorpc/result/validator.go b/pkg/tutusrpc/result/validator.go similarity index 100% rename from pkg/neorpc/result/validator.go rename to pkg/tutusrpc/result/validator.go diff --git a/pkg/neorpc/result/validator_test.go b/pkg/tutusrpc/result/validator_test.go similarity index 100% rename from pkg/neorpc/result/validator_test.go rename to pkg/tutusrpc/result/validator_test.go diff --git a/pkg/neorpc/result/version.go b/pkg/tutusrpc/result/version.go similarity index 100% rename from pkg/neorpc/result/version.go rename to pkg/tutusrpc/result/version.go diff --git a/pkg/neorpc/result/version_test.go b/pkg/tutusrpc/result/version_test.go similarity index 100% rename from pkg/neorpc/result/version_test.go rename to pkg/tutusrpc/result/version_test.go diff --git a/pkg/neorpc/rpcevent/filter.go b/pkg/tutusrpc/rpcevent/filter.go similarity index 81% rename from pkg/neorpc/rpcevent/filter.go rename to pkg/tutusrpc/rpcevent/filter.go index 3e18f11..5d9e0f4 100644 --- a/pkg/neorpc/rpcevent/filter.go +++ b/pkg/tutusrpc/rpcevent/filter.go @@ -4,8 +4,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/block" "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/vm/stackitem" ) @@ -13,13 +13,13 @@ type ( // Comparator is an interface required from notification event filter to be able to // filter notifications. Comparator interface { - EventID() neorpc.EventID - Filter() neorpc.SubscriptionFilter + EventID() tutusrpc.EventID + Filter() tutusrpc.SubscriptionFilter } // Container is an interface required from notification event to be able to // pass filter. Container interface { - EventID() neorpc.EventID + EventID() tutusrpc.EventID EventPayload() any } ) @@ -35,10 +35,10 @@ func Matches(f Comparator, r Container) bool { return true } switch f.EventID() { - case neorpc.BlockEventID, neorpc.HeaderOfAddedBlockEventID: - filt := filter.(neorpc.BlockFilter) + case tutusrpc.BlockEventID, tutusrpc.HeaderOfAddedBlockEventID: + filt := filter.(tutusrpc.BlockFilter) var b *block.Header - if f.EventID() == neorpc.HeaderOfAddedBlockEventID { + if f.EventID() == tutusrpc.HeaderOfAddedBlockEventID { b = r.EventPayload().(*block.Header) } else { b = &r.EventPayload().(*block.Block).Header @@ -47,8 +47,8 @@ func Matches(f Comparator, r Container) bool { sinceOk := filt.Since == nil || *filt.Since <= b.Index tillOk := filt.Till == nil || b.Index <= *filt.Till return primaryOk && sinceOk && tillOk - case neorpc.TransactionEventID: - filt := filter.(neorpc.TxFilter) + case tutusrpc.TransactionEventID: + filt := filter.(tutusrpc.TxFilter) tx := r.EventPayload().(*transaction.Transaction) senderOK := filt.Sender == nil || tx.Sender().Equals(*filt.Sender) signerOK := true @@ -62,8 +62,8 @@ func Matches(f Comparator, r Container) bool { } } return senderOK && signerOK - case neorpc.NotificationEventID: - filt := filter.(neorpc.NotificationFilter) + case tutusrpc.NotificationEventID: + filt := filter.(tutusrpc.NotificationFilter) notification := r.EventPayload().(*state.ContainedNotificationEvent) hashOk := filt.Contract == nil || notification.ScriptHash.Equals(*filt.Contract) nameOk := filt.Name == nil || notification.Name == *filt.Name @@ -88,14 +88,14 @@ func Matches(f Comparator, r Container) bool { } } return hashOk && nameOk && parametersOk - case neorpc.ExecutionEventID: - filt := filter.(neorpc.ExecutionFilter) + case tutusrpc.ExecutionEventID: + filt := filter.(tutusrpc.ExecutionFilter) applog := r.EventPayload().(*state.AppExecResult) stateOK := filt.State == nil || applog.VMState.String() == *filt.State containerOK := filt.Container == nil || applog.Container.Equals(*filt.Container) return stateOK && containerOK - case neorpc.NotaryRequestEventID: - filt := filter.(neorpc.NotaryRequestFilter) + case tutusrpc.NotaryRequestEventID: + filt := filter.(tutusrpc.NotaryRequestFilter) req := r.EventPayload().(*result.NotaryRequestEvent) typeOk := filt.Type == nil || req.Type == *filt.Type senderOk := filt.Sender == nil || req.NotaryRequest.FallbackTransaction.Signers[1].Account == *filt.Sender @@ -110,8 +110,8 @@ func Matches(f Comparator, r Container) bool { } } return senderOk && signerOK && typeOk - case neorpc.MempoolEventID: - filt := filter.(neorpc.MempoolEventFilter) + case tutusrpc.MempoolEventID: + filt := filter.(tutusrpc.MempoolEventFilter) memEvent := r.EventPayload().(*result.MempoolEvent) if filt.Type != nil && memEvent.Type != *filt.Type { return false diff --git a/pkg/neorpc/rpcevent/filter_test.go b/pkg/tutusrpc/rpcevent/filter_test.go similarity index 66% rename from pkg/neorpc/rpcevent/filter_test.go rename to pkg/tutusrpc/rpcevent/filter_test.go index b15ceb9..ff95d83 100644 --- a/pkg/neorpc/rpcevent/filter_test.go +++ b/pkg/tutusrpc/rpcevent/filter_test.go @@ -7,8 +7,8 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/mempoolevent" "github.com/tutus-one/tutus-chain/pkg/core/state" "github.com/tutus-one/tutus-chain/pkg/core/transaction" - "github.com/tutus-one/tutus-chain/pkg/neorpc" - "github.com/tutus-one/tutus-chain/pkg/neorpc/result" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc" + "github.com/tutus-one/tutus-chain/pkg/tutusrpc/result" "github.com/tutus-one/tutus-chain/pkg/network/payload" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/util" @@ -19,22 +19,22 @@ import ( type ( testComparator struct { - id neorpc.EventID - filter neorpc.SubscriptionFilter + id tutusrpc.EventID + filter tutusrpc.SubscriptionFilter } testContainer struct { - id neorpc.EventID + id tutusrpc.EventID pld any } ) -func (c testComparator) EventID() neorpc.EventID { +func (c testComparator) EventID() tutusrpc.EventID { return c.id } -func (c testComparator) Filter() neorpc.SubscriptionFilter { +func (c testComparator) Filter() tutusrpc.SubscriptionFilter { return c.filter } -func (c testContainer) EventID() neorpc.EventID { +func (c testContainer) EventID() tutusrpc.EventID { return c.id } func (c testContainer) EventPayload() any { @@ -62,28 +62,28 @@ func TestMatches(t *testing.T) { badParameters, err := smartcontract.NewParametersFromValues([]byte{3}, "2", []byte{1}) require.NoError(t, err) bContainer := testContainer{ - id: neorpc.BlockEventID, + id: tutusrpc.BlockEventID, pld: &block.Block{ Header: block.Header{PrimaryIndex: byte(primary), Index: index}, }, } headerContainer := testContainer{ - id: neorpc.HeaderOfAddedBlockEventID, + id: tutusrpc.HeaderOfAddedBlockEventID, pld: &block.Header{PrimaryIndex: byte(primary), Index: index}, } st := vmstate.Halt goodState := st.String() badState := "FAULT" txContainer := testContainer{ - id: neorpc.TransactionEventID, + id: tutusrpc.TransactionEventID, pld: &transaction.Transaction{Signers: []transaction.Signer{{Account: sender}, {Account: signer}}}, } ntfContainer := testContainer{ - id: neorpc.NotificationEventID, + id: tutusrpc.NotificationEventID, pld: &state.ContainedNotificationEvent{NotificationEvent: state.NotificationEvent{ScriptHash: contract, Name: name}}, } ntfContainerParameters := testContainer{ - id: neorpc.NotificationEventID, + id: tutusrpc.NotificationEventID, pld: &state.ContainedNotificationEvent{ NotificationEvent: state.NotificationEvent{ ScriptHash: contract, @@ -93,11 +93,11 @@ func TestMatches(t *testing.T) { }, } exContainer := testContainer{ - id: neorpc.ExecutionEventID, + id: tutusrpc.ExecutionEventID, pld: &state.AppExecResult{Container: cnt, Execution: state.Execution{VMState: st}}, } ntrContainer := testContainer{ - id: neorpc.NotaryRequestEventID, + id: tutusrpc.NotaryRequestEventID, pld: &result.NotaryRequestEvent{ Type: goodType, NotaryRequest: &payload.P2PNotaryRequest{ @@ -107,14 +107,14 @@ func TestMatches(t *testing.T) { }, } mempoolContainer := testContainer{ - id: neorpc.MempoolEventID, + id: tutusrpc.MempoolEventID, pld: &result.MempoolEvent{ Type: goodType, Tx: &transaction.Transaction{Signers: []transaction.Signer{{Account: sender}, {Account: signer}}}, }, } missedContainer := testContainer{ - id: neorpc.MissedEventID, + id: tutusrpc.MissedEventID, } var testCases = []struct { name string @@ -124,27 +124,27 @@ func TestMatches(t *testing.T) { }{ { name: "ID mismatch", - comparator: testComparator{id: neorpc.TransactionEventID}, + comparator: testComparator{id: tutusrpc.TransactionEventID}, container: bContainer, expected: false, }, { name: "missed event", - comparator: testComparator{id: neorpc.BlockEventID}, + comparator: testComparator{id: tutusrpc.BlockEventID}, container: missedContainer, expected: false, }, { name: "block, no filter", - comparator: testComparator{id: neorpc.BlockEventID}, + comparator: testComparator{id: tutusrpc.BlockEventID}, container: bContainer, expected: true, }, { name: "block, primary mismatch", comparator: testComparator{ - id: neorpc.BlockEventID, - filter: neorpc.BlockFilter{Primary: &badPrimary}, + id: tutusrpc.BlockEventID, + filter: tutusrpc.BlockFilter{Primary: &badPrimary}, }, container: bContainer, expected: false, @@ -152,8 +152,8 @@ func TestMatches(t *testing.T) { { name: "block, since mismatch", comparator: testComparator{ - id: neorpc.BlockEventID, - filter: neorpc.BlockFilter{Since: &badHigherIndex}, + id: tutusrpc.BlockEventID, + filter: tutusrpc.BlockFilter{Since: &badHigherIndex}, }, container: bContainer, expected: false, @@ -161,8 +161,8 @@ func TestMatches(t *testing.T) { { name: "block, till mismatch", comparator: testComparator{ - id: neorpc.BlockEventID, - filter: neorpc.BlockFilter{Till: &badLowerIndex}, + id: tutusrpc.BlockEventID, + filter: tutusrpc.BlockFilter{Till: &badLowerIndex}, }, container: bContainer, expected: false, @@ -170,23 +170,23 @@ func TestMatches(t *testing.T) { { name: "block, filter match", comparator: testComparator{ - id: neorpc.BlockEventID, - filter: neorpc.BlockFilter{Primary: &primary, Since: &index, Till: &index}, + id: tutusrpc.BlockEventID, + filter: tutusrpc.BlockFilter{Primary: &primary, Since: &index, Till: &index}, }, container: bContainer, expected: true, }, { name: "header, no filter", - comparator: testComparator{id: neorpc.HeaderOfAddedBlockEventID}, + comparator: testComparator{id: tutusrpc.HeaderOfAddedBlockEventID}, container: headerContainer, expected: true, }, { name: "header, primary mismatch", comparator: testComparator{ - id: neorpc.HeaderOfAddedBlockEventID, - filter: neorpc.BlockFilter{Primary: &badPrimary}, + id: tutusrpc.HeaderOfAddedBlockEventID, + filter: tutusrpc.BlockFilter{Primary: &badPrimary}, }, container: headerContainer, expected: false, @@ -194,8 +194,8 @@ func TestMatches(t *testing.T) { { name: "header, since mismatch", comparator: testComparator{ - id: neorpc.HeaderOfAddedBlockEventID, - filter: neorpc.BlockFilter{Since: &badHigherIndex}, + id: tutusrpc.HeaderOfAddedBlockEventID, + filter: tutusrpc.BlockFilter{Since: &badHigherIndex}, }, container: headerContainer, expected: false, @@ -203,8 +203,8 @@ func TestMatches(t *testing.T) { { name: "header, till mismatch", comparator: testComparator{ - id: neorpc.HeaderOfAddedBlockEventID, - filter: neorpc.BlockFilter{Till: &badLowerIndex}, + id: tutusrpc.HeaderOfAddedBlockEventID, + filter: tutusrpc.BlockFilter{Till: &badLowerIndex}, }, container: headerContainer, expected: false, @@ -212,23 +212,23 @@ func TestMatches(t *testing.T) { { name: "header, filter match", comparator: testComparator{ - id: neorpc.HeaderOfAddedBlockEventID, - filter: neorpc.BlockFilter{Primary: &primary, Since: &index, Till: &index}, + id: tutusrpc.HeaderOfAddedBlockEventID, + filter: tutusrpc.BlockFilter{Primary: &primary, Since: &index, Till: &index}, }, container: headerContainer, expected: true, }, { name: "transaction, no filter", - comparator: testComparator{id: neorpc.TransactionEventID}, + comparator: testComparator{id: tutusrpc.TransactionEventID}, container: txContainer, expected: true, }, { name: "transaction, sender mismatch", comparator: testComparator{ - id: neorpc.TransactionEventID, - filter: neorpc.TxFilter{Sender: &badUint160}, + id: tutusrpc.TransactionEventID, + filter: tutusrpc.TxFilter{Sender: &badUint160}, }, container: txContainer, expected: false, @@ -236,8 +236,8 @@ func TestMatches(t *testing.T) { { name: "transaction, signer mismatch", comparator: testComparator{ - id: neorpc.TransactionEventID, - filter: neorpc.TxFilter{Signer: &badUint160}, + id: tutusrpc.TransactionEventID, + filter: tutusrpc.TxFilter{Signer: &badUint160}, }, container: txContainer, expected: false, @@ -245,23 +245,23 @@ func TestMatches(t *testing.T) { { name: "transaction, filter match", comparator: testComparator{ - id: neorpc.TransactionEventID, - filter: neorpc.TxFilter{Sender: &sender, Signer: &signer}, + id: tutusrpc.TransactionEventID, + filter: tutusrpc.TxFilter{Sender: &sender, Signer: &signer}, }, container: txContainer, expected: true, }, { name: "notification, no filter", - comparator: testComparator{id: neorpc.NotificationEventID}, + comparator: testComparator{id: tutusrpc.NotificationEventID}, container: ntfContainer, expected: true, }, { name: "notification, contract mismatch", comparator: testComparator{ - id: neorpc.NotificationEventID, - filter: neorpc.NotificationFilter{Contract: &badUint160}, + id: tutusrpc.NotificationEventID, + filter: tutusrpc.NotificationFilter{Contract: &badUint160}, }, container: ntfContainer, expected: false, @@ -269,8 +269,8 @@ func TestMatches(t *testing.T) { { name: "notification, name mismatch", comparator: testComparator{ - id: neorpc.NotificationEventID, - filter: neorpc.NotificationFilter{Name: &badName}, + id: tutusrpc.NotificationEventID, + filter: tutusrpc.NotificationFilter{Name: &badName}, }, container: ntfContainer, expected: false, @@ -278,8 +278,8 @@ func TestMatches(t *testing.T) { { name: "notification, filter match", comparator: testComparator{ - id: neorpc.NotificationEventID, - filter: neorpc.NotificationFilter{Name: &name, Contract: &contract}, + id: tutusrpc.NotificationEventID, + filter: tutusrpc.NotificationFilter{Name: &name, Contract: &contract}, }, container: ntfContainer, expected: true, @@ -287,8 +287,8 @@ func TestMatches(t *testing.T) { { name: "notification, parameters match", comparator: testComparator{ - id: neorpc.NotificationEventID, - filter: neorpc.NotificationFilter{Name: &name, Contract: &contract, Parameters: parameters}, + id: tutusrpc.NotificationEventID, + filter: tutusrpc.NotificationFilter{Name: &name, Contract: &contract, Parameters: parameters}, }, container: ntfContainerParameters, expected: true, @@ -296,23 +296,23 @@ func TestMatches(t *testing.T) { { name: "notification, parameters mismatch", comparator: testComparator{ - id: neorpc.NotificationEventID, - filter: neorpc.NotificationFilter{Name: &name, Contract: &contract, Parameters: badParameters}, + id: tutusrpc.NotificationEventID, + filter: tutusrpc.NotificationFilter{Name: &name, Contract: &contract, Parameters: badParameters}, }, container: ntfContainerParameters, expected: false, }, { name: "execution, no filter", - comparator: testComparator{id: neorpc.ExecutionEventID}, + comparator: testComparator{id: tutusrpc.ExecutionEventID}, container: exContainer, expected: true, }, { name: "execution, state mismatch", comparator: testComparator{ - id: neorpc.ExecutionEventID, - filter: neorpc.ExecutionFilter{State: &badState}, + id: tutusrpc.ExecutionEventID, + filter: tutusrpc.ExecutionFilter{State: &badState}, }, container: exContainer, expected: false, @@ -320,8 +320,8 @@ func TestMatches(t *testing.T) { { name: "execution, container mismatch", comparator: testComparator{ - id: neorpc.ExecutionEventID, - filter: neorpc.ExecutionFilter{Container: &badUint256}, + id: tutusrpc.ExecutionEventID, + filter: tutusrpc.ExecutionFilter{Container: &badUint256}, }, container: exContainer, expected: false, @@ -329,23 +329,23 @@ func TestMatches(t *testing.T) { { name: "execution, filter mismatch", comparator: testComparator{ - id: neorpc.ExecutionEventID, - filter: neorpc.ExecutionFilter{State: &goodState, Container: &cnt}, + id: tutusrpc.ExecutionEventID, + filter: tutusrpc.ExecutionFilter{State: &goodState, Container: &cnt}, }, container: exContainer, expected: true, }, { name: "notary request, no filter", - comparator: testComparator{id: neorpc.NotaryRequestEventID}, + comparator: testComparator{id: tutusrpc.NotaryRequestEventID}, container: ntrContainer, expected: true, }, { name: "notary request, sender mismatch", comparator: testComparator{ - id: neorpc.NotaryRequestEventID, - filter: neorpc.NotaryRequestFilter{Sender: &badUint160}, + id: tutusrpc.NotaryRequestEventID, + filter: tutusrpc.NotaryRequestFilter{Sender: &badUint160}, }, container: ntrContainer, expected: false, @@ -353,8 +353,8 @@ func TestMatches(t *testing.T) { { name: "notary request, signer mismatch", comparator: testComparator{ - id: neorpc.NotaryRequestEventID, - filter: neorpc.NotaryRequestFilter{Signer: &badUint160}, + id: tutusrpc.NotaryRequestEventID, + filter: tutusrpc.NotaryRequestFilter{Signer: &badUint160}, }, container: ntrContainer, expected: false, @@ -362,8 +362,8 @@ func TestMatches(t *testing.T) { { name: "notary request, type mismatch", comparator: testComparator{ - id: neorpc.NotaryRequestEventID, - filter: neorpc.NotaryRequestFilter{Type: &badType}, + id: tutusrpc.NotaryRequestEventID, + filter: tutusrpc.NotaryRequestFilter{Type: &badType}, }, container: ntrContainer, expected: false, @@ -371,23 +371,23 @@ func TestMatches(t *testing.T) { { name: "notary request, filter match", comparator: testComparator{ - id: neorpc.NotaryRequestEventID, - filter: neorpc.NotaryRequestFilter{Sender: &sender, Signer: &signer, Type: &goodType}, + id: tutusrpc.NotaryRequestEventID, + filter: tutusrpc.NotaryRequestFilter{Sender: &sender, Signer: &signer, Type: &goodType}, }, container: ntrContainer, expected: true, }, { name: "mempool event, no filter", - comparator: testComparator{id: neorpc.MempoolEventID}, + comparator: testComparator{id: tutusrpc.MempoolEventID}, container: mempoolContainer, expected: true, }, { name: "mempool event, sender mismatch", comparator: testComparator{ - id: neorpc.MempoolEventID, - filter: neorpc.MempoolEventFilter{Sender: &badUint160}, + id: tutusrpc.MempoolEventID, + filter: tutusrpc.MempoolEventFilter{Sender: &badUint160}, }, container: mempoolContainer, expected: false, @@ -395,8 +395,8 @@ func TestMatches(t *testing.T) { { name: "mempool event, signer mismatch", comparator: testComparator{ - id: neorpc.MempoolEventID, - filter: neorpc.MempoolEventFilter{Signer: &badUint160}, + id: tutusrpc.MempoolEventID, + filter: tutusrpc.MempoolEventFilter{Signer: &badUint160}, }, container: mempoolContainer, expected: false, @@ -404,8 +404,8 @@ func TestMatches(t *testing.T) { { name: "mempool event, type mismatch", comparator: testComparator{ - id: neorpc.MempoolEventID, - filter: neorpc.MempoolEventFilter{Type: &badType}, + id: tutusrpc.MempoolEventID, + filter: tutusrpc.MempoolEventFilter{Type: &badType}, }, container: mempoolContainer, expected: false, @@ -413,8 +413,8 @@ func TestMatches(t *testing.T) { { name: "mempool event, filter match", comparator: testComparator{ - id: neorpc.MempoolEventID, - filter: neorpc.MempoolEventFilter{Sender: &sender, Signer: &signer, Type: &goodType}, + id: tutusrpc.MempoolEventID, + filter: tutusrpc.MempoolEventFilter{Sender: &sender, Signer: &signer, Type: &goodType}, }, container: mempoolContainer, expected: true, diff --git a/pkg/neorpc/types.go b/pkg/tutusrpc/types.go similarity index 99% rename from pkg/neorpc/types.go rename to pkg/tutusrpc/types.go index 0c66868..687b33a 100644 --- a/pkg/neorpc/types.go +++ b/pkg/tutusrpc/types.go @@ -3,7 +3,7 @@ Package neorpc contains a set of types used for JSON-RPC communication with Neo It defines basic request/response types as well as a set of errors and additional parameters used for specific requests/responses. */ -package neorpc +package tutusrpc import ( "encoding/json" diff --git a/pkg/neorpc/types_test.go b/pkg/tutusrpc/types_test.go similarity index 99% rename from pkg/neorpc/types_test.go rename to pkg/tutusrpc/types_test.go index c15b278..3b05562 100644 --- a/pkg/neorpc/types_test.go +++ b/pkg/tutusrpc/types_test.go @@ -1,4 +1,4 @@ -package neorpc +package tutusrpc import ( "encoding/json" diff --git a/pkg/neotest/account.go b/pkg/tutustest/account.go similarity index 89% rename from pkg/neotest/account.go rename to pkg/tutustest/account.go index cbee806..d903b8f 100644 --- a/pkg/neotest/account.go +++ b/pkg/tutustest/account.go @@ -1,4 +1,4 @@ -package neotest +package tutustest var _nonce uint32 diff --git a/pkg/neotest/basic.go b/pkg/tutustest/basic.go similarity index 99% rename from pkg/neotest/basic.go rename to pkg/tutustest/basic.go index 36c11a1..2a1b449 100644 --- a/pkg/neotest/basic.go +++ b/pkg/tutustest/basic.go @@ -1,4 +1,4 @@ -package neotest +package tutustest import ( "encoding/json" diff --git a/pkg/neotest/chain/chain.go b/pkg/tutustest/chain/chain.go similarity index 99% rename from pkg/neotest/chain/chain.go rename to pkg/tutustest/chain/chain.go index 08947c1..2d00a7a 100644 --- a/pkg/neotest/chain/chain.go +++ b/pkg/tutustest/chain/chain.go @@ -12,7 +12,7 @@ import ( "github.com/tutus-one/tutus-chain/pkg/core/interop" "github.com/tutus-one/tutus-chain/pkg/core/storage" "github.com/tutus-one/tutus-chain/pkg/crypto/keys" - "github.com/tutus-one/tutus-chain/pkg/neotest" + "github.com/tutus-one/tutus-chain/pkg/tutustest" "github.com/tutus-one/tutus-chain/pkg/smartcontract" "github.com/tutus-one/tutus-chain/pkg/wallet" "github.com/stretchr/testify/require" diff --git a/pkg/neotest/chain/chain_test.go b/pkg/tutustest/chain/chain_test.go similarity index 91% rename from pkg/neotest/chain/chain_test.go rename to pkg/tutustest/chain/chain_test.go index 190ca73..98896a4 100644 --- a/pkg/neotest/chain/chain_test.go +++ b/pkg/tutustest/chain/chain_test.go @@ -3,7 +3,7 @@ package chain import ( "testing" - "github.com/tutus-one/tutus-chain/pkg/neotest" + "github.com/tutus-one/tutus-chain/pkg/tutustest" "github.com/stretchr/testify/require" ) diff --git a/pkg/neotest/chain/doc.go b/pkg/tutustest/chain/doc.go similarity index 100% rename from pkg/neotest/chain/doc.go rename to pkg/tutustest/chain/doc.go diff --git a/pkg/neotest/client.go b/pkg/tutustest/client.go similarity index 99% rename from pkg/neotest/client.go rename to pkg/tutustest/client.go index ce05c36..8343aed 100644 --- a/pkg/neotest/client.go +++ b/pkg/tutustest/client.go @@ -1,4 +1,4 @@ -package neotest +package tutustest import ( "testing" diff --git a/pkg/neotest/compile.go b/pkg/tutustest/compile.go similarity index 99% rename from pkg/neotest/compile.go rename to pkg/tutustest/compile.go index 9779a72..206f46b 100644 --- a/pkg/neotest/compile.go +++ b/pkg/tutustest/compile.go @@ -1,4 +1,4 @@ -package neotest +package tutustest import ( "encoding/json" diff --git a/pkg/neotest/compile_test.go b/pkg/tutustest/compile_test.go similarity index 98% rename from pkg/neotest/compile_test.go rename to pkg/tutustest/compile_test.go index 02e47df..5b37ec2 100644 --- a/pkg/neotest/compile_test.go +++ b/pkg/tutustest/compile_test.go @@ -1,4 +1,4 @@ -package neotest +package tutustest import ( "os" diff --git a/pkg/neotest/coverage.go b/pkg/tutustest/coverage.go similarity index 99% rename from pkg/neotest/coverage.go rename to pkg/tutustest/coverage.go index b9453c7..71f2018 100644 --- a/pkg/neotest/coverage.go +++ b/pkg/tutustest/coverage.go @@ -1,4 +1,4 @@ -package neotest +package tutustest import ( "cmp" diff --git a/pkg/neotest/doc.go b/pkg/tutustest/doc.go similarity index 99% rename from pkg/neotest/doc.go rename to pkg/tutustest/doc.go index b4bf55b..9f4ff0c 100644 --- a/pkg/neotest/doc.go +++ b/pkg/tutustest/doc.go @@ -33,4 +33,4 @@ coverage collection is properly supported for different Executor instances only; not run a parallel coverage collection for a single Executor instance if EnableCoverage or DisableCoverage is used (ref. #4108). */ -package neotest +package tutustest diff --git a/pkg/neotest/signer.go b/pkg/tutustest/signer.go similarity index 99% rename from pkg/neotest/signer.go rename to pkg/tutustest/signer.go index 6b6644e..e2c8095 100644 --- a/pkg/neotest/signer.go +++ b/pkg/tutustest/signer.go @@ -1,4 +1,4 @@ -package neotest +package tutustest import ( "bytes" diff --git a/pkg/neotest/signer_test.go b/pkg/tutustest/signer_test.go similarity index 98% rename from pkg/neotest/signer_test.go rename to pkg/tutustest/signer_test.go index 9735638..15ea9e6 100644 --- a/pkg/neotest/signer_test.go +++ b/pkg/tutustest/signer_test.go @@ -1,4 +1,4 @@ -package neotest +package tutustest import ( "slices"