Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

manifest: support NEP-24 #3560

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open

manifest: support NEP-24 #3560

wants to merge 2 commits into from

Conversation

AliceInHunterland
Copy link
Contributor

@AliceInHunterland AliceInHunterland commented Aug 19, 2024

Close #3451

wrapper generates:

// RoyaltyInfo invokes `royaltyInfo` method of contract.
func (c *ContractReader) RoyaltyInfo(tokenID []byte, royaltyToken util.Uint160, salePrice *big.Int) ([]stackitem.Item, error) {
	return unwrap.Array(c.invoker.Call(c.hash, "royaltyInfo", tokenID, royaltyToken, salePrice))
}

but it should be different.

add tests with smartcontact/testdata/

Copy link

codecov bot commented Sep 9, 2024

Codecov Report

Attention: Patch coverage is 72.67081% with 44 lines in your changes missing coverage. Please review.

Project coverage is 83.04%. Comparing base (b8a65d3) to head (cbfda6a).
Report is 24 commits behind head on master.

Files with missing lines Patch % Lines
pkg/rpcclient/nep24/royalty.go 63.80% 25 Missing and 13 partials ⚠️
pkg/smartcontract/manifest/standard/comply.go 25.00% 2 Missing and 1 partial ⚠️
pkg/smartcontract/rpcbinding/binding.go 94.23% 2 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3560      +/-   ##
==========================================
- Coverage   83.26%   83.04%   -0.22%     
==========================================
  Files         334      335       +1     
  Lines       46488    46738     +250     
==========================================
+ Hits        38707    38815     +108     
- Misses       6205     6339     +134     
- Partials     1576     1584       +8     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

pkg/rpcclient/nep11/royalty.go Outdated Show resolved Hide resolved
pkg/rpcclient/nep11/royalty.go Outdated Show resolved Hide resolved
pkg/rpcclient/nep11/royalty.go Outdated Show resolved Hide resolved
pkg/rpcclient/nep11/royalty.go Outdated Show resolved Hide resolved
pkg/rpcclient/nep11/royalty.go Outdated Show resolved Hide resolved
pkg/rpcclient/nep11/royalty.go Outdated Show resolved Hide resolved
pkg/rpcclient/nep11/royalty_test.go Outdated Show resolved Hide resolved
pkg/rpcclient/nep11/royalty.go Outdated Show resolved Hide resolved
pkg/smartcontract/manifest/standard/nep24.go Outdated Show resolved Hide resolved
pkg/smartcontract/rpcbinding/binding.go Outdated Show resolved Hide resolved
pkg/rpcclient/nep24/royalty.go Show resolved Hide resolved
pkg/rpcclient/nep24/royalty.go Outdated Show resolved Hide resolved
pkg/rpcclient/nep24/royalty.go Outdated Show resolved Hide resolved
pkg/rpcclient/nep24/royalty.go Outdated Show resolved Hide resolved
pkg/rpcclient/nep24/royalty.go Outdated Show resolved Hide resolved
pkg/rpcclient/nep24/royalty.go Outdated Show resolved Hide resolved
pkg/rpcclient/nep24/royalty_test.go Outdated Show resolved Hide resolved
pkg/rpcclient/nep24/royalty_test.go Show resolved Hide resolved
pkg/smartcontract/manifest/standard/nep24.go Outdated Show resolved Hide resolved
pkg/smartcontract/rpcbinding/binding.go Outdated Show resolved Hide resolved
Copy link
Member

@AnnaShaleva AnnaShaleva left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And you need to adjust

func comply(m *manifest.Manifest, checkNames bool, st *Standard) error {
in the following way:

  1. Extend standard.Standard structure with Required []string field. This field includes standards required by this standard.
  2. In comply() check that standards marked as "Required" are present in the manifest. No compliance check is needed for them, the presence check is enough since compliance is checked by the calling code for all standards.

Copy link
Member

@AnnaShaleva AnnaShaleva left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, the test of RPC bindings generator based on the existing NEP contract is missing, we discussed it in DM.

Copy link
Member

@AnnaShaleva AnnaShaleva left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review is not finished, some new code is uploaded.

examples/nft-nd/nft.go Outdated Show resolved Hide resolved
Comment on lines 16 to 27
- name: RoyaltiesTransferred
parameters:
- name: royaltyToken
type: Hash160
- name: royaltyRecipient
type: Hash160
- name: buyer
type: Hash160
- name: tokenId
type: ByteArray
- name: amount
type: Integer
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not for the NEP11 contract itself, read the spec:

Marketplaces that support this standard MUST emit the event, RoyaltiesTransferred for each recipient, after sending a payment.

Copy link
Contributor Author

@AliceInHunterland AliceInHunterland Oct 25, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so I should remove it from manifest/standard too?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it's not a part of the standard that belongs to the NEP11 contract itself. But it should be moved to a separate standard, ref. #3560 (comment).

examples/nft-nd/nft.yml Outdated Show resolved Hide resolved
Copy link
Member

@AnnaShaleva AnnaShaleva left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test is not finished. I need a test with generated RPC bindings.

pkg/rpcclient/nep24/royalty.go Outdated Show resolved Hide resolved
examples/nft-nd/nft.go Outdated Show resolved Hide resolved
pkg/rpcclient/nep24/royalty.go Outdated Show resolved Hide resolved
Comment on lines 64 to 72
var royalties []RoyaltyRecipient
for _, item := range res.Stack {
royalty, ok := item.Value().([]stackitem.Item)
if !ok || len(royalty) != 2 {
return nil, fmt.Errorf("invalid royalty structure: expected array of 2 items, got %d", len(royalty))
}
var recipient RoyaltyRecipient
err = recipient.FromStackItem(royalty)
if err != nil {
return nil, fmt.Errorf("failed to decode royalty detail: %w", err)
}
royalties = append(royalties, recipient)
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Waiting for the response.

pkg/smartcontract/manifest/standard/comply.go Show resolved Hide resolved
pkg/smartcontract/manifest/standard/nep24.go Show resolved Hide resolved
pkg/smartcontract/manifest/standard/comply.go Outdated Show resolved Hide resolved
examples/nft-nd/nft.go Outdated Show resolved Hide resolved
pkg/smartcontract/rpcbinding/binding.go Outdated Show resolved Hide resolved
pkg/smartcontract/rpcbinding/binding.go Show resolved Hide resolved
@AnnaShaleva
Copy link
Member

AnnaShaleva commented Oct 25, 2024

wrapper generates:

// RoyaltyInfo invokes royaltyInfo method of contract.
func (c *ContractReader) RoyaltyInfo(tokenID []byte, royaltyToken util.Uint160, salePrice *big.Int) ([]stackitem.Item, error) {
return unwrap.Array(c.invoker.Call(c.hash, "royaltyInfo", tokenID, royaltyToken, salePrice))
}

but it should be different.

What is your expected result? To me, the auto-generated code looks good although it does not includes named return structures, but it depends on the original contract. As I said earlier, it's a matter of separate issue anyway.

@AliceInHunterland
Copy link
Contributor Author

i have:

// RoyaltyInfo invokes `royaltyInfo` method of contract.
func (c *RoyaltyReader) RoyaltyInfo(tokenID []byte, royaltyToken util.Uint160, salePrice *big.Int) ([]stackitem.Item, error) {
	return unwrap.Array(c.Invoker.Call(c.Hash, "royaltyInfo", tokenID, royaltyToken, salePrice))
}

and:

func TestRoyaltyReaderRoyaltyInfo2(t *testing.T) {
	ta := new(testAct)
	rr := &RoyaltyReader{
		Invoker: ta,
		Hash:    util.Uint160{1, 2, 3},
	}

	tokenID := []byte{1, 2, 3}
	royaltyToken := util.Uint160{4, 5, 6}
	salePrice := big.NewInt(1000)

	tests := []struct {
		name       string
		setupFunc  func()
		expectErr  bool
		expectedRI []RoyaltyRecipient
	}{
		{
			name: "error case",
			setupFunc: func() {
				ta.err = errors.New("some error")
			},
			expectErr: true,
		},
		{
			name: "valid response",
			setupFunc: func() {
				ta.err = nil
				recipient := util.Uint160{7, 8, 9}
				amount := big.NewInt(100)
				ta.res = &result.Invoke{
					State: "HALT",
					Stack: []stackitem.Item{
						stackitem.Make([]stackitem.Item{
							stackitem.Make(recipient.BytesBE()),
							stackitem.Make(amount),
						}),
					},
				}
			},
			expectErr: false,
			expectedRI: []RoyaltyRecipient{
				{
					Address: util.Uint160{7, 8, 9},
					Amount:  big.NewInt(100),
				},
			},
		},
		{
			name: "invalid data response",
			setupFunc: func() {
				ta.res = &result.Invoke{
					State: "HALT",
					Stack: []stackitem.Item{
						stackitem.Make([]stackitem.Item{
							stackitem.Make(util.Uint160{7, 8, 9}.BytesBE()),
						}),
					},
				}
			},
			expectErr: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			tt.setupFunc()
			riStackItems, err := rr.RoyaltyInfo(tokenID, royaltyToken, salePrice)
			if tt.expectErr {
				require.Error(t, err)
			} else {
				require.NoError(t, err)
				require.Len(t, riStackItems, len(tt.expectedRI))

				var actualRI []RoyaltyRecipient
				for _, item := range riStackItems {
					subItems, ok := item.Value().([]stackitem.Item)
					require.True(t, ok)
					require.Len(t, subItems, 2)

					recipientBytes, err := subItems[0].TryBytes()
					require.NoError(t, err)
					recipient, err := util.Uint160DecodeBytesBE(recipientBytes)
					require.NoError(t, err)

					amount, err := subItems[1].TryInteger()
					require.NoError(t, err)

					actualRI = append(actualRI, RoyaltyRecipient{
						Address: recipient,
						Amount:  amount,
					})
				}

				require.Equal(t, tt.expectedRI, actualRI)
			}
		})
	}
}

and:


=== RUN   TestRoyaltyReaderRoyaltyInfo2/valid_response
    royalty_test.go:183: 
        	Error Trace:	/Users/ekaterinapavlova/Workplace/neo-go/pkg/rpcclient/nep24/royalty_test.go:183
        	Error:      	"[ByteString BigInteger]" should have 1 item(s), but has 2
        	Test:       	TestRoyaltyReaderRoyaltyInfo2/valid_response
--- FAIL: TestRoyaltyReaderRoyaltyInfo2/valid_response (0.00s)

=== RUN   TestRoyaltyReaderRoyaltyInfo2/invalid_data_response
    royalty_test.go:180: 
        	Error Trace:	/Users/ekaterinapavlova/Workplace/neo-go/pkg/rpcclient/nep24/royalty_test.go:180
        	Error:      	An error is expected but got nil.
        	Test:       	TestRoyaltyReaderRoyaltyInfo2/invalid_data_response
--- FAIL: TestRoyaltyReaderRoyaltyInfo2/invalid_data_response (0.00s)

@AliceInHunterland
Copy link
Contributor Author

wrapper generates:
// RoyaltyInfo invokes royaltyInfo method of contract.
func (c *ContractReader) RoyaltyInfo(tokenID []byte, royaltyToken util.Uint160, salePrice *big.Int) ([]stackitem.Item, error) {
return unwrap.Array(c.invoker.Call(c.hash, "royaltyInfo", tokenID, royaltyToken, salePrice))
}
but it should be different.

What is your expected result? To me, the auto-generated code looks good although it does not includes named return structures, but it depends on the original contract. As I said earlier, it's a matter of separate issue anyway.

I wrongly passed as a config file to generate-rpcbinding the same config file as used for contract compile which is why I expected a different result (something like:

func (c *ContractReader) RoyaltyInfo(tokenID []byte, royaltyToken util.Uint160, salePrice *big.Int) ([]*TestnepRoyaltyRecipient, error) {
). Also tried to write the test for it #3560 (comment) and with that implementation, it didn't work.

@roman-khimov
Copy link
Member

I wrongly passed as a config file to generate-rpcbinding the same config file as used for contract compile

You're not first one to do this, btw. @smallhive and @tatiana-nspcc both know it happens easily. Long-term this will be solved by removing binding configuration file because of NEP-25.

Copy link
Member

@AnnaShaleva AnnaShaleva left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#3560 (comment) is still missing.

cli/smartcontract/generate_test.go Show resolved Hide resolved
cli/smartcontract/generate_test.go Outdated Show resolved Hide resolved
examples/nft-d/nft.go Outdated Show resolved Hide resolved
examples/nft-d/nft.go Outdated Show resolved Hide resolved
pkg/rpcclient/nep24/royalty_test.go Outdated Show resolved Hide resolved
pkg/rpcclient/nep24/royalty_test.go Outdated Show resolved Hide resolved
pkg/rpcclient/nep24/royalty_test.go Outdated Show resolved Hide resolved
pkg/smartcontract/manifest/standard/comply.go Outdated Show resolved Hide resolved
pkg/smartcontract/rpcbinding/binding.go Outdated Show resolved Hide resolved
@AnnaShaleva
Copy link
Member

@AliceInHunterland, ready for review?

examples/nft-d/nft.go Outdated Show resolved Hide resolved
if val == nil {
recipients = []RoyaltyRecipient{
{
Address: owner,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not fixed.

examples/nft-d/nft.go Outdated Show resolved Hide resolved
}

// RoyaltiesTransfer an event that MUST be emitted by marketplaces that support the `royaltyInfo` method.
var RoyaltiesTransfer = &Standard{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RoyaltiesTransfer an event that MUST

Grammar. Ans it's not an event, make it similar to the reference:

// Nep11Payable contains NEP-11's onNEP11Payment method definition.
var Nep11Payable = &Standard{

var RoyaltiesTransfer

Rename it to Nep24Payable, make a separate constant for this standard. Add it to the list of standards check.

Copy link
Contributor Author

@AliceInHunterland AliceInHunterland Nov 5, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also added Nep24Payable to binding.Generate as mfst.ABI.Events = dropStdEvents(mfst.ABI.Events, standard.Nep24Payable) in case of ctr.IsNep24 = true. Do we need a separate test (new smartcontract in testdata) for it?

Copy link
Member

@AnnaShaleva AnnaShaleva Nov 6, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need a separate test (new smartcontract in testdata) for it?

Would be nice, and this contract shouldn't be large in fact. A single transferring method is enough for the testing purposes.

Required: []string{manifest.NEP11StandardName},
}

// RoyaltiesTransfer an event that MUST be emitted by marketplaces that support the `royaltyInfo` method.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not true. Marketplaces don't support this method, this method may be supported by NEP11 token contract. If you're copy-pasting from the standard, then make it properly, here's what the standard tells about it:

MUST trigger after marketplaces transferring royalties to the royalty recipient if royaltyInfo method is implemented.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The standard also tells:

The royaltyInfo() function MUST NOT ignore the salePrice, royaltyAmount MAY be dynamic due to salePrice and time.

Marketplaces that support this standard MUST emit the event, RoyaltiesTransferred for each recipient, after sending a payment.

Which is literally my comment. So the comment // RoyaltiesTransfer is an event that MUST trigger after marketplaces transferring royalties to the royalty recipient if royaltyInfo method is implemented. is more correct?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I should have left a comment to the standard when it was on the review stage. OK, then choose either you'd like.

an event that MUST trigger

Grammar: an event that MUST be triggered

pkg/smartcontract/rpcbinding/binding.go Outdated Show resolved Hide resolved
pkg/smartcontract/rpcbinding/binding.go Outdated Show resolved Hide resolved
pkg/smartcontract/rpcbinding/binding.go Outdated Show resolved Hide resolved
`Required` contains standards that are required for this standard.

Signed-off-by: Ekaterina Pavlova <[email protected]>
Close #3451

Signed-off-by: Ekaterina Pavlova <[email protected]>
func New(actor Actor) *Contract {
var hash = Hash
var nep11dt = nep11.NewDivisible(actor, hash)
return &Contract{ContractReader{nep11dt.DivisibleReader, nep24.RoyaltyReader{}, actor, hash}, nep11dt.DivisibleWriter, actor, hash}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nep24.RoyaltyReader{}

It's not correct, you have to properly initialize it. Make it similar to var nep11dt = nep11.NewDivisible(actor, hash).

panic("sale price must be positive")
}

callingHash := runtime.GetExecutingScriptHash()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

callingHash

It's not calling, it's executing.

for _, owner := range owners {
recipients = append(recipients, RoyaltyRecipient{
Address: owner,
Amount: salePrice / 10,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Amount: salePrice / 10,

Allocate variable once and then reuse it. And I'd suggest salePrice / 10 / len(owners) as a unit of royalty payment (consider if there are more than 10 owners), because usually it's some tiny part of the token price that is aimed to support authors; and the rest is taken by marketplace.

supportedstandards: ["NEP-11"]
safemethods: ["balanceOf", "decimals", "symbol", "totalSupply", "tokensOf", "ownerOf", "properties", "tokens"]
supportedstandards: ["NEP-11","NEP-24"]
safemethods: ["balanceOf", "decimals", "symbol", "totalSupply", "tokensOf", "ownerOf", "properties", "tokens","royaltyInfo"]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indent?

@@ -34,6 +34,8 @@ const (
tokenOwnerPrefix = "t"
// tokenPrefix contains map from token id to its properties (serialised containerID + objectID).
tokenPrefix = "i"
// royaltyInfoPrefix contains map from token id to its royalty information.
royaltyInfoPrefix = "r"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For this contract it's not needed because there's a fixed rate of royalty payment for every token.

}
if ctr.IsNep24 {
mfst.ABI.Methods = dropStdMethods(mfst.ABI.Methods, standard.Nep24)
mfst.ABI.Events = dropStdEvents(mfst.ABI.Events, standard.Nep24Payable)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dropStdEvents

NEP24Payable is represented as a separate standard, can't be done in one case with NEP24.

// dropTypes removes NamedTypes of NEP-24 from the config if they are used only once.
func dropTypes(cfg binding.Config, std *standard.Standard) binding.Config {
var targetTypeName string
if royaltyInfo, ok := cfg.Types[std.ABI.Methods[0].Name]; ok && royaltyInfo.Value != nil {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this method is generic, then you can't use any royalty-relating naming and things like std.ABI.Methods[0].Name inside this method because std can be anything. If this method is royalties-specific, then the method name must reflect this fact and no std argument must be present.

count := 0
for _, typeDef := range cfg.Types {
if typeDef.Value != nil && typeDef.Value.Name == targetTypeName {
count++
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just return immediately if there's another occurrence of this type. And you don't even need count for that, some bool is sufficient.

}
if count == 1 {
filteredNamedTypes := maps.Clone(cfg.NamedTypes)
if _, exists := cfg.NamedTypes[targetTypeName]; exists {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/exists/ok

}
}
if count == 1 {
filteredNamedTypes := maps.Clone(cfg.NamedTypes)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Too expensive, you don't need it.

@@ -15,5 +15,5 @@ events:
type: ByteArray
permissions:
- hash: fffdc93764dbaddd97c48f252a53ea4643faa3fd
methods: ["update", "destroy"]
methods: ["update", "destroy","setRoyaltyInfo"]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Revert it. This section allows contract to call native Management's destroy and update methods, it's not related to the contract itself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add NEP-24 to known manifests, check compliance
3 participants