diff --git a/encoding/ccf/ccf_test.go b/encoding/ccf/ccf_test.go index d3e4d2062d..258cc85c81 100644 --- a/encoding/ccf/ccf_test.go +++ b/encoding/ccf/ccf_test.go @@ -97,10 +97,10 @@ func TestEncodeOptional(t *testing.T) { // as tests may run in parallel newStructType := func() *cadence.StructType { - return &cadence.StructType{ - Location: utils.TestLocation, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ + return cadence.NewStructType( + utils.TestLocation, + "Foo", + []cadence.Field{ { Identifier: "a", Type: cadence.NewOptionalType(cadence.IntType), @@ -114,14 +114,15 @@ func TestEncodeOptional(t *testing.T) { Type: cadence.NewOptionalType(cadence.NewOptionalType(cadence.NewOptionalType(cadence.IntType))), }, }, - } + nil, + ) } newStructTypeWithOptionalAbstractField := func() *cadence.StructType { - return &cadence.StructType{ - Location: utils.TestLocation, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ + return cadence.NewStructType( + utils.TestLocation, + "Foo", + []cadence.Field{ { Identifier: "a", Type: cadence.NewOptionalType(cadence.AnyStructType), @@ -135,7 +136,8 @@ func TestEncodeOptional(t *testing.T) { Type: cadence.NewOptionalType(cadence.NewOptionalType(cadence.NewOptionalType(cadence.AnyStructType))), }, }, - } + nil, + ) } testAllEncodeAndDecode(t, []encodeTest{ @@ -802,16 +804,17 @@ func TestEncodeOptional(t *testing.T) { name: "struct with non-nil optional abstract fields", val: func() cadence.Value { structTypeWithOptionalAbstractField := newStructTypeWithOptionalAbstractField() - simpleStructType := &cadence.StructType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooStruct", - Fields: []cadence.Field{ + simpleStructType := cadence.NewStructType( + utils.TestLocation, + "FooStruct", + []cadence.Field{ { Identifier: "bar", Type: cadence.IntType, }, }, - } + nil, + ) return cadence.NewStruct([]cadence.Value{ cadence.NewOptional(cadence.NewInt(1)), cadence.NewOptional(cadence.NewOptional(cadence.NewInt(2))), @@ -3570,10 +3573,12 @@ func TestEncodeArray(t *testing.T) { resourceInterfaceTypeArray := encodeTest{ name: "Resource Interface Array", val: func() cadence.Value { - resourceInterfaceType := &cadence.ResourceInterfaceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "Bar", - } + resourceInterfaceType := cadence.NewResourceInterfaceType( + utils.TestLocation, + "Bar", + nil, + nil, + ) fooResourceType := newFooResourceType() foooResourceTypeWithAbstractField := newFoooResourceTypeWithAbstractField() return cadence.NewArray([]cadence.Value{ @@ -3922,20 +3927,23 @@ func TestEncodeArray(t *testing.T) { structInterfaceTypeArray := encodeTest{ name: "Struct Interface Array", val: func() cadence.Value { - structInterfaceType := &cadence.StructInterfaceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooStructInterface", - } - structType := &cadence.StructType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooStruct", - Fields: []cadence.Field{ + structInterfaceType := cadence.NewStructInterfaceType( + utils.TestLocation, + "FooStructInterface", + nil, + nil, + ) + structType := cadence.NewStructType( + utils.TestLocation, + "FooStruct", + []cadence.Field{ { Identifier: "a", Type: cadence.IntType, }, }, - } + nil, + ) return cadence.NewArray([]cadence.Value{ cadence.NewStruct([]cadence.Value{ cadence.NewInt(1), @@ -4064,20 +4072,23 @@ func TestEncodeArray(t *testing.T) { contractInterfaceTypeArray := encodeTest{ name: "Contract Interface Array", val: func() cadence.Value { - contractInterfaceType := &cadence.ContractInterfaceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooContractInterface", - } - contractType := &cadence.ContractType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooContract", - Fields: []cadence.Field{ + contractInterfaceType := cadence.NewContractInterfaceType( + utils.TestLocation, + "FooContractInterface", + nil, + nil, + ) + contractType := cadence.NewContractType( + utils.TestLocation, + "FooContract", + []cadence.Field{ { Identifier: "a", Type: cadence.IntType, }, }, - } + nil, + ) return cadence.NewArray([]cadence.Value{ cadence.NewContract([]cadence.Value{ cadence.NewInt(1), @@ -5400,11 +5411,12 @@ func TestEncodeStruct(t *testing.T) { noFieldStruct := encodeTest{ name: "no field", val: func() cadence.Value { - noFieldStructType := &cadence.StructType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooStruct", - Fields: []cadence.Field{}, - } + noFieldStructType := cadence.NewStructType( + utils.TestLocation, + "FooStruct", + []cadence.Field{}, + nil, + ) return cadence.NewStruct( []cadence.Value{}, ).WithType(noFieldStructType) @@ -5458,10 +5470,10 @@ func TestEncodeStruct(t *testing.T) { simpleStruct := encodeTest{ name: "Simple", val: func() cadence.Value { - simpleStructType := &cadence.StructType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooStruct", - Fields: []cadence.Field{ + simpleStructType := cadence.NewStructType( + utils.TestLocation, + "FooStruct", + []cadence.Field{ { Identifier: "a", Type: cadence.IntType, @@ -5471,7 +5483,8 @@ func TestEncodeStruct(t *testing.T) { Type: cadence.StringType, }, }, - } + nil, + ) return cadence.NewStruct( []cadence.Value{ cadence.NewInt(1), @@ -5808,10 +5821,10 @@ func TestEncodeEvent(t *testing.T) { simpleEvent := encodeTest{ name: "Simple", val: func() cadence.Value { - simpleEventType := &cadence.EventType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooEvent", - Fields: []cadence.Field{ + simpleEventType := cadence.NewEventType( + utils.TestLocation, + "FooEvent", + []cadence.Field{ { Identifier: "a", Type: cadence.IntType, @@ -5821,7 +5834,8 @@ func TestEncodeEvent(t *testing.T) { Type: cadence.StringType, }, }, - } + nil, + ) return cadence.NewEvent( []cadence.Value{ cadence.NewInt(1), @@ -5911,10 +5925,10 @@ func TestEncodeEvent(t *testing.T) { abstractEvent := encodeTest{ name: "abstract event", val: func() cadence.Value { - abstractEventType := &cadence.EventType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooEvent", - Fields: []cadence.Field{ + abstractEventType := cadence.NewEventType( + utils.TestLocation, + "FooEvent", + []cadence.Field{ { Identifier: "a", Type: cadence.IntType, @@ -5924,17 +5938,19 @@ func TestEncodeEvent(t *testing.T) { Type: cadence.AnyStructType, }, }, - } - simpleStructType := &cadence.StructType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooStruct", - Fields: []cadence.Field{ + nil, + ) + simpleStructType := cadence.NewStructType( + utils.TestLocation, + "FooStruct", + []cadence.Field{ { Identifier: "c", Type: cadence.StringType, }, }, - } + nil, + ) return cadence.NewEvent( []cadence.Value{ cadence.NewInt(1), @@ -6071,10 +6087,10 @@ func TestEncodeEvent(t *testing.T) { name: "Resources", val: func() cadence.Value { fooResourceType := newFooResourceType() - resourceEventType := &cadence.EventType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooEvent", - Fields: []cadence.Field{ + resourceEventType := cadence.NewEventType( + utils.TestLocation, + "FooEvent", + []cadence.Field{ { Identifier: "a", Type: cadence.StringType, @@ -6084,7 +6100,8 @@ func TestEncodeEvent(t *testing.T) { Type: fooResourceType, }, }, - } + nil, + ) return cadence.NewEvent( []cadence.Value{ cadence.String("foo"), @@ -6239,10 +6256,10 @@ func TestEncodeContract(t *testing.T) { simpleContract := encodeTest{ name: "Simple", val: func() cadence.Value { - simpleContractType := &cadence.ContractType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooContract", - Fields: []cadence.Field{ + simpleContractType := cadence.NewContractType( + utils.TestLocation, + "FooContract", + []cadence.Field{ { Identifier: "a", Type: cadence.IntType, @@ -6252,7 +6269,8 @@ func TestEncodeContract(t *testing.T) { Type: cadence.StringType, }, }, - } + nil, + ) return cadence.NewContract( []cadence.Value{ cadence.NewInt(1), @@ -6342,20 +6360,21 @@ func TestEncodeContract(t *testing.T) { abstractContract := encodeTest{ name: "abstract contract", val: func() cadence.Value { - simpleStructType := &cadence.StructType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooStruct", - Fields: []cadence.Field{ + simpleStructType := cadence.NewStructType( + utils.TestLocation, + "FooStruct", + []cadence.Field{ { Identifier: "c", Type: cadence.StringType, }, }, - } - abstractContractType := &cadence.ContractType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooContract", - Fields: []cadence.Field{ + nil, + ) + abstractContractType := cadence.NewContractType( + utils.TestLocation, + "FooContract", + []cadence.Field{ { Identifier: "a", Type: cadence.IntType, @@ -6365,7 +6384,8 @@ func TestEncodeContract(t *testing.T) { Type: cadence.AnyStructType, }, }, - } + nil, + ) return cadence.NewContract( []cadence.Value{ cadence.NewInt(1), @@ -6502,10 +6522,10 @@ func TestEncodeContract(t *testing.T) { name: "Resources", val: func() cadence.Value { fooResourceType := newFooResourceType() - resourceContractType := &cadence.ContractType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooContract", - Fields: []cadence.Field{ + resourceContractType := cadence.NewContractType( + utils.TestLocation, + "FooContract", + []cadence.Field{ { Identifier: "a", Type: cadence.StringType, @@ -6515,7 +6535,8 @@ func TestEncodeContract(t *testing.T) { Type: fooResourceType, }, }, - } + nil, + ) return cadence.NewContract( []cadence.Value{ cadence.String("foo"), @@ -6653,16 +6674,18 @@ func TestEncodeEnum(t *testing.T) { simpleEnum := encodeTest{ name: "Simple", val: func() cadence.Value { - simpleEnumType := &cadence.EnumType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooEnum", - Fields: []cadence.Field{ + simpleEnumType := cadence.NewEnumType( + utils.TestLocation, + "FooEnum", + nil, + []cadence.Field{ { Identifier: "raw", Type: cadence.UInt8Type, }, }, - } + nil, + ) return cadence.NewEnum( []cadence.Value{ cadence.NewUInt8(1), @@ -6738,11 +6761,13 @@ func TestEncodeAttachment(t *testing.T) { noFieldAttachment := encodeTest{ name: "no field", val: func() cadence.Value { - attachmentType := &cadence.AttachmentType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooAttachment", - Fields: []cadence.Field{}, - } + attachmentType := cadence.NewAttachmentType( + utils.TestLocation, + "FooAttachment", + nil, + []cadence.Field{}, + nil, + ) return cadence.NewAttachment( []cadence.Value{}, ).WithType(attachmentType) @@ -6797,16 +6822,18 @@ func TestEncodeAttachment(t *testing.T) { primitiveFieldAttachment := encodeTest{ name: "simple", val: func() cadence.Value { - attachmentType := &cadence.AttachmentType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooAttachment", - Fields: []cadence.Field{ + attachmentType := cadence.NewAttachmentType( + utils.TestLocation, + "FooAttachment", + nil, + []cadence.Field{ { Identifier: "i", Type: cadence.UInt8Type, }, }, - } + nil, + ) return cadence.NewAttachment( []cadence.Value{ cadence.NewUInt8(1), @@ -6876,20 +6903,22 @@ func TestEncodeAttachment(t *testing.T) { structFieldAttachment := encodeTest{ name: "struct field", val: func() cadence.Value { - structType := &cadence.StructType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooStruct", - Fields: []cadence.Field{ + structType := cadence.NewStructType( + utils.TestLocation, + "FooStruct", + []cadence.Field{ { Identifier: "bar", Type: cadence.IntType, }, }, - } - attachmentType := &cadence.AttachmentType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooAttachment", - Fields: []cadence.Field{ + nil, + ) + attachmentType := cadence.NewAttachmentType( + utils.TestLocation, + "FooAttachment", + nil, + []cadence.Field{ { Identifier: "a", Type: cadence.StringType, @@ -6899,7 +6928,8 @@ func TestEncodeAttachment(t *testing.T) { Type: structType, }, }, - } + nil, + ) return cadence.NewAttachment( []cadence.Value{ cadence.String("foo"), @@ -7475,16 +7505,17 @@ func TestEncodeValueOfReferenceType(t *testing.T) { // as tests may run in parallel newSimpleStructType := func() *cadence.StructType { - return &cadence.StructType{ - Location: utils.TestLocation, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ + return cadence.NewStructType( + utils.TestLocation, + "Foo", + []cadence.Field{ { Identifier: "a", Type: cadence.StringType, }, }, - } + nil, + ) } // ["a", "b"] with static type []&String @@ -8806,12 +8837,12 @@ func TestEncodeType(t *testing.T) { testEncodeAndDecode( t, cadence.TypeValue{ - StaticType: &cadence.StructType{ - Location: utils.TestLocation, - QualifiedIdentifier: "S", - Fields: []cadence.Field{}, - Initializers: [][]cadence.Parameter{}, - }, + StaticType: cadence.NewStructType( + utils.TestLocation, + "S", + []cadence.Field{}, + [][]cadence.Parameter{}, + ), }, []byte{ // language=json, format=json-cdc @@ -8855,20 +8886,20 @@ func TestEncodeType(t *testing.T) { t.Parallel() val := cadence.TypeValue{ - StaticType: &cadence.StructType{ - Location: utils.TestLocation, - QualifiedIdentifier: "S", - Fields: []cadence.Field{ + StaticType: cadence.NewStructType( + utils.TestLocation, + "S", + []cadence.Field{ {Identifier: "foo", Type: cadence.IntType}, {Identifier: "bar", Type: cadence.IntType}, }, - Initializers: [][]cadence.Parameter{ + [][]cadence.Parameter{ { {Label: "foo", Identifier: "bar", Type: cadence.IntType}, {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, }, - }, + ), } expectedCBOR := []byte{ @@ -8978,20 +9009,20 @@ func TestEncodeType(t *testing.T) { testEncodeAndDecodeEx( t, cadence.TypeValue{ - StaticType: &cadence.StructType{ - Location: utils.TestLocation, - QualifiedIdentifier: "S", - Fields: []cadence.Field{ + StaticType: cadence.NewStructType( + utils.TestLocation, + "S", + []cadence.Field{ {Identifier: "foo", Type: cadence.IntType}, {Identifier: "bar", Type: cadence.IntType}, }, - Initializers: [][]cadence.Parameter{ + [][]cadence.Parameter{ { {Label: "foo", Identifier: "bar", Type: cadence.IntType}, {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, }, - }, + ), }, []byte{ // language=json, format=json-cdc @@ -9079,20 +9110,20 @@ func TestEncodeType(t *testing.T) { 0x01, }, cadence.TypeValue{ - StaticType: &cadence.StructType{ - Location: utils.TestLocation, - QualifiedIdentifier: "S", - Fields: []cadence.Field{ + StaticType: cadence.NewStructType( + utils.TestLocation, + "S", + []cadence.Field{ {Identifier: "bar", Type: cadence.IntType}, {Identifier: "foo", Type: cadence.IntType}, }, - Initializers: [][]cadence.Parameter{ + [][]cadence.Parameter{ { {Label: "foo", Identifier: "bar", Type: cadence.IntType}, {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, }, - }, + ), }, ) }) @@ -9100,30 +9131,30 @@ func TestEncodeType(t *testing.T) { t.Run("with static resource of composite fields and initializers", func(t *testing.T) { t.Parallel() - fooTy := &cadence.ResourceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{}, - Initializers: [][]cadence.Parameter{}, - } + fooTy := cadence.NewResourceType( + utils.TestLocation, + "Foo", + []cadence.Field{}, + [][]cadence.Parameter{}, + ) - fooTy2 := &cadence.ResourceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "Foo2", - Fields: []cadence.Field{}, - Initializers: [][]cadence.Parameter{}, - } + fooTy2 := cadence.NewResourceType( + utils.TestLocation, + "Foo2", + []cadence.Field{}, + [][]cadence.Parameter{}, + ) - barTy := &cadence.ResourceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "Bar", - Fields: []cadence.Field{ + barTy := cadence.NewResourceType( + utils.TestLocation, + "Bar", + []cadence.Field{ { Identifier: "foo1", Type: fooTy, }, }, - Initializers: [][]cadence.Parameter{ + [][]cadence.Parameter{ { cadence.Parameter{ Type: fooTy2, @@ -9132,7 +9163,7 @@ func TestEncodeType(t *testing.T) { }, }, }, - } + ) testEncodeAndDecode( t, @@ -9240,19 +9271,19 @@ func TestEncodeType(t *testing.T) { testEncodeAndDecode( t, cadence.TypeValue{ - StaticType: &cadence.ResourceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "R", - Fields: []cadence.Field{ + StaticType: cadence.NewResourceType( + utils.TestLocation, + "R", + []cadence.Field{ {Identifier: "foo", Type: cadence.IntType}, }, - Initializers: [][]cadence.Parameter{ + [][]cadence.Parameter{ { {Label: "foo", Identifier: "bar", Type: cadence.IntType}, {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, }, - }, + ), }, []byte{ // language=json, format=json-cdc @@ -9338,19 +9369,19 @@ func TestEncodeType(t *testing.T) { testEncodeAndDecode( t, cadence.TypeValue{ - StaticType: &cadence.ContractType{ - Location: utils.TestLocation, - QualifiedIdentifier: "C", - Fields: []cadence.Field{ + StaticType: cadence.NewContractType( + utils.TestLocation, + "C", + []cadence.Field{ {Identifier: "foo", Type: cadence.IntType}, }, - Initializers: [][]cadence.Parameter{ + [][]cadence.Parameter{ { {Label: "foo", Identifier: "bar", Type: cadence.IntType}, {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, }, - }, + ), }, []byte{ // language=json, format=json-cdc @@ -9436,19 +9467,19 @@ func TestEncodeType(t *testing.T) { testEncodeAndDecode( t, cadence.TypeValue{ - StaticType: &cadence.StructInterfaceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "S", - Fields: []cadence.Field{ + StaticType: cadence.NewStructInterfaceType( + utils.TestLocation, + "S", + []cadence.Field{ {Identifier: "foo", Type: cadence.IntType}, }, - Initializers: [][]cadence.Parameter{ + [][]cadence.Parameter{ { {Label: "foo", Identifier: "bar", Type: cadence.IntType}, {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, }, - }, + ), }, []byte{ // language=json, format=json-cdc @@ -9534,19 +9565,19 @@ func TestEncodeType(t *testing.T) { testEncodeAndDecode( t, cadence.TypeValue{ - StaticType: &cadence.ResourceInterfaceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "R", - Fields: []cadence.Field{ + StaticType: cadence.NewResourceInterfaceType( + utils.TestLocation, + "R", + []cadence.Field{ {Identifier: "foo", Type: cadence.IntType}, }, - Initializers: [][]cadence.Parameter{ + [][]cadence.Parameter{ { {Label: "foo", Identifier: "bar", Type: cadence.IntType}, {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, }, - }, + ), }, []byte{ // language=json, format=json-cdc @@ -9632,19 +9663,19 @@ func TestEncodeType(t *testing.T) { testEncodeAndDecode( t, cadence.TypeValue{ - StaticType: &cadence.ContractInterfaceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "C", - Fields: []cadence.Field{ + StaticType: cadence.NewContractInterfaceType( + utils.TestLocation, + "C", + []cadence.Field{ {Identifier: "foo", Type: cadence.IntType}, }, - Initializers: [][]cadence.Parameter{ + [][]cadence.Parameter{ { {Label: "foo", Identifier: "bar", Type: cadence.IntType}, {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, }, - }, + ), }, []byte{ // language=json, format=json-cdc @@ -9730,17 +9761,17 @@ func TestEncodeType(t *testing.T) { testEncodeAndDecode( t, cadence.TypeValue{ - StaticType: &cadence.EventType{ - Location: utils.TestLocation, - QualifiedIdentifier: "E", - Fields: []cadence.Field{ + StaticType: cadence.NewEventType( + utils.TestLocation, + "E", + []cadence.Field{ {Identifier: "foo", Type: cadence.IntType}, }, - Initializer: []cadence.Parameter{ + []cadence.Parameter{ {Label: "foo", Identifier: "bar", Type: cadence.IntType}, {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, - }, + ), }, []byte{ // language=json, format=json-cdc @@ -9826,20 +9857,20 @@ func TestEncodeType(t *testing.T) { testEncodeAndDecode( t, cadence.TypeValue{ - StaticType: &cadence.EnumType{ - Location: utils.TestLocation, - QualifiedIdentifier: "E", - RawType: cadence.StringType, - Fields: []cadence.Field{ + StaticType: cadence.NewEnumType( + utils.TestLocation, + "E", + cadence.StringType, + []cadence.Field{ {Identifier: "foo", Type: cadence.IntType}, }, - Initializers: [][]cadence.Parameter{ + [][]cadence.Parameter{ { {Label: "foo", Identifier: "bar", Type: cadence.IntType}, {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, }, - }, + ), }, []byte{ // language=json, format=json-cdc @@ -9927,20 +9958,20 @@ func TestEncodeType(t *testing.T) { testEncodeAndDecode( t, cadence.TypeValue{ - StaticType: &cadence.AttachmentType{ - Location: utils.TestLocation, - QualifiedIdentifier: "A", - BaseType: cadence.StringType, - Fields: []cadence.Field{ + StaticType: cadence.NewAttachmentType( + utils.TestLocation, + "A", + cadence.StringType, + []cadence.Field{ {Identifier: "foo", Type: cadence.IntType}, }, - Initializers: [][]cadence.Parameter{ + [][]cadence.Parameter{ { {Label: "foo", Identifier: "bar", Type: cadence.IntType}, {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, }, - }, + ), }, []byte{ // language=json, format=json-cdc @@ -10025,32 +10056,32 @@ func TestEncodeType(t *testing.T) { t.Run("with static attachment of resource base type", func(t *testing.T) { t.Parallel() - baseType := &cadence.ResourceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooBase", - Fields: []cadence.Field{ + baseType := cadence.NewResourceType( + utils.TestLocation, + "FooBase", + []cadence.Field{ {Identifier: "bar", Type: cadence.StringType}, }, - Initializers: [][]cadence.Parameter{}, - } + [][]cadence.Parameter{}, + ) testEncodeAndDecode( t, cadence.TypeValue{ - StaticType: &cadence.AttachmentType{ - Location: utils.TestLocation, - QualifiedIdentifier: "A", - BaseType: baseType, - Fields: []cadence.Field{ + StaticType: cadence.NewAttachmentType( + utils.TestLocation, + "A", + baseType, + []cadence.Field{ {Identifier: "foo", Type: cadence.IntType}, }, - Initializers: [][]cadence.Parameter{ + [][]cadence.Parameter{ { {Label: "foo", Identifier: "bar", Type: cadence.IntType}, {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, }, - }, + ), }, []byte{ // language=json, format=json-cdc @@ -11016,16 +11047,17 @@ func TestEncodeCapability(t *testing.T) { t.Run("array of unparameterized Capability", func(t *testing.T) { t.Parallel() - simpleStructType := &cadence.StructType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooStruct", - Fields: []cadence.Field{ + simpleStructType := cadence.NewStructType( + utils.TestLocation, + "FooStruct", + []cadence.Field{ { Identifier: "bar", Type: cadence.IntType, }, }, - } + nil, + ) capability1 := cadence.Capability{ ID: 42, @@ -11682,17 +11714,19 @@ func TestExportRecursiveType(t *testing.T) { t.Parallel() - ty := &cadence.ResourceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ - { - Identifier: "foo", - }, + fields := []cadence.Field{ + { + Identifier: "foo", }, } + ty := cadence.NewResourceType( + utils.TestLocation, + "Foo", + fields, + nil, + ) - ty.Fields[0].Type = &cadence.OptionalType{ + fields[0].Type = &cadence.OptionalType{ Type: ty, } @@ -11773,18 +11807,19 @@ func TestExportTypeValueRecursiveType(t *testing.T) { t.Parallel() - ty := &cadence.ResourceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ - { - Identifier: "foo", - }, + fields := []cadence.Field{ + { + Identifier: "foo", }, - Initializers: [][]cadence.Parameter{}, } + ty := cadence.NewResourceType( + utils.TestLocation, + "Foo", + fields, + [][]cadence.Parameter{}, + ) - ty.Fields[0].Type = &cadence.OptionalType{ + fields[0].Type = &cadence.OptionalType{ Type: ty, } @@ -11926,14 +11961,16 @@ func TestExportTypeValueRecursiveType(t *testing.T) { t.Parallel() // structType is generated by fuzzer. + fields := []cadence.Field{{}} + structType := cadence.NewStructType( common.StringLocation("foo"), "Foo", - []cadence.Field{{}}, + fields, [][]cadence.Parameter{{{}}}, ) - structType.Fields[0] = cadence.Field{ + fields[0] = cadence.Field{ Type: &cadence.OptionalType{Type: structType}, Identifier: "aa", } @@ -12021,24 +12058,24 @@ func TestExportTypeValueRecursiveType(t *testing.T) { t.Parallel() - fooTy := &cadence.ResourceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{}, - Initializers: [][]cadence.Parameter{}, - } + fooTy := cadence.NewResourceType( + utils.TestLocation, + "Foo", + []cadence.Field{}, + [][]cadence.Parameter{}, + ) - fooTy2 := &cadence.ResourceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "Foo2", - Fields: []cadence.Field{}, - Initializers: [][]cadence.Parameter{}, - } + fooTy2 := cadence.NewResourceType( + utils.TestLocation, + "Foo2", + []cadence.Field{}, + [][]cadence.Parameter{}, + ) - barTy := &cadence.ResourceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "Bar", - Fields: []cadence.Field{ + barTy := cadence.NewResourceType( + utils.TestLocation, + "Bar", + []cadence.Field{ { Identifier: "foo1", Type: fooTy, @@ -12048,7 +12085,7 @@ func TestExportTypeValueRecursiveType(t *testing.T) { Type: fooTy, }, }, - Initializers: [][]cadence.Parameter{ + [][]cadence.Parameter{ { cadence.Parameter{ Type: &cadence.OptionalType{Type: fooTy}, @@ -12062,7 +12099,7 @@ func TestExportTypeValueRecursiveType(t *testing.T) { }, }, }, - } + ) testEncodeAndDecode( t, @@ -12708,10 +12745,10 @@ func testDecode(t *testing.T, actualCBOR []byte, expectedVal cadence.Value) { // TODO: make resource (illegal nesting) func newResourceStructType() *cadence.StructType { - return &cadence.StructType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooStruct", - Fields: []cadence.Field{ + return cadence.NewStructType( + utils.TestLocation, + "FooStruct", + []cadence.Field{ { Identifier: "a", Type: cadence.StringType, @@ -12721,27 +12758,29 @@ func newResourceStructType() *cadence.StructType { Type: newFooResourceType(), }, }, - } + nil, + ) } func newFooResourceType() *cadence.ResourceType { - return &cadence.ResourceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ + return cadence.NewResourceType( + utils.TestLocation, + "Foo", + []cadence.Field{ { Identifier: "bar", Type: cadence.IntType, }, }, - } + nil, + ) } func newFoooResourceTypeWithAbstractField() *cadence.ResourceType { - return &cadence.ResourceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "Fooo", - Fields: []cadence.Field{ + return cadence.NewResourceType( + utils.TestLocation, + "Fooo", + []cadence.Field{ { Identifier: "bar", Type: cadence.IntType, @@ -12751,7 +12790,8 @@ func newFoooResourceTypeWithAbstractField() *cadence.ResourceType { Type: cadence.AnyStructType, }, }, - } + nil, + ) } func TestEncodeBuiltinComposites(t *testing.T) { @@ -12766,10 +12806,12 @@ func TestEncodeBuiltinComposites(t *testing.T) { testCases := []testCase{ { name: "Struct", - typ: &cadence.StructType{ - Location: nil, - QualifiedIdentifier: "Foo", - }, + typ: cadence.NewStructType( + nil, + "Foo", + nil, + nil, + ), encoded: []byte{ // language=json, format=json-cdc // {"type":"Type","value":{"staticType":{"kind":"Struct","typeID":"Foo","fields":[],"initializers":[],"type":""}}} @@ -12808,10 +12850,12 @@ func TestEncodeBuiltinComposites(t *testing.T) { }, { name: "StructInterface", - typ: &cadence.StructInterfaceType{ - Location: nil, - QualifiedIdentifier: "Foo", - }, + typ: cadence.NewStructInterfaceType( + nil, + "Foo", + nil, + nil, + ), encoded: []byte{ // language=json, format=json-cdc // {"type":"Type","value":{"staticType":{"kind":"StructInterface","typeID":"Foo","fields":[],"initializers":[],"type":""}}} @@ -12850,10 +12894,12 @@ func TestEncodeBuiltinComposites(t *testing.T) { }, { name: "Resource", - typ: &cadence.ResourceType{ - Location: nil, - QualifiedIdentifier: "Foo", - }, + typ: cadence.NewResourceType( + nil, + "Foo", + nil, + nil, + ), encoded: []byte{ // language=json, format=json-cdc // {"type":"Type","value":{"staticType":{"kind":"Resource","typeID":"Foo","fields":[],"initializers":[],"type":""}}} @@ -12892,10 +12938,12 @@ func TestEncodeBuiltinComposites(t *testing.T) { }, { name: "ResourceInterface", - typ: &cadence.ResourceInterfaceType{ - Location: nil, - QualifiedIdentifier: "Foo", - }, + typ: cadence.NewResourceInterfaceType( + nil, + "Foo", + nil, + nil, + ), encoded: []byte{ // language=json, format=json-cdc // {"type":"Type","value":{"staticType":{"kind":"ResourceInterface","typeID":"Foo","fields":[],"initializers":[],"type":""}}} @@ -12934,10 +12982,12 @@ func TestEncodeBuiltinComposites(t *testing.T) { }, { name: "Contract", - typ: &cadence.ContractType{ - Location: nil, - QualifiedIdentifier: "Foo", - }, + typ: cadence.NewContractType( + nil, + "Foo", + nil, + nil, + ), encoded: []byte{ // language=json, format=json-cdc // {"type":"Type","value":{"staticType":{"kind":"Contract","typeID":"Foo","fields":[],"initializers":[],"type":""}}} @@ -12976,10 +13026,12 @@ func TestEncodeBuiltinComposites(t *testing.T) { }, { name: "ContractInterface", - typ: &cadence.ContractInterfaceType{ - Location: nil, - QualifiedIdentifier: "Foo", - }, + typ: cadence.NewContractInterfaceType( + nil, + "Foo", + nil, + nil, + ), encoded: []byte{ // language=json, format=json-cdc // {"type":"Type","value":{"staticType":{"kind":"ContractInterface","typeID":"Foo","fields":[],"initializers":[],"type":""}}} @@ -13018,10 +13070,13 @@ func TestEncodeBuiltinComposites(t *testing.T) { }, { name: "Enum", - typ: &cadence.EnumType{ - Location: nil, - QualifiedIdentifier: "Foo", - }, + typ: cadence.NewEnumType( + nil, + "Foo", + nil, + nil, + nil, + ), encoded: []byte{ // language=json, format=json-cdc // {"type":"Type","value":{"staticType":{"kind":"Enum","typeID":"Foo","fields":[],"initializers":[],"type":""}}} @@ -13060,10 +13115,12 @@ func TestEncodeBuiltinComposites(t *testing.T) { }, { name: "Event", - typ: &cadence.EventType{ - Location: nil, - QualifiedIdentifier: "Foo", - }, + typ: cadence.NewEventType( + nil, + "Foo", + nil, + nil, + ), encoded: []byte{ // language=json, format=json-cdc // {"type":"Type","value":{"staticType":{"kind":"Event","typeID":"Foo","fields":[],"initializers":[],"type":""}}} @@ -13122,17 +13179,19 @@ func TestExportFunctionValue(t *testing.T) { t.Parallel() - ty := &cadence.ResourceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ - { - Identifier: "foo", - }, + fields := []cadence.Field{ + { + Identifier: "foo", }, } + ty := cadence.NewResourceType( + utils.TestLocation, + "Foo", + fields, + nil, + ) - ty.Fields[0].Type = &cadence.OptionalType{ + fields[0].Type = &cadence.OptionalType{ Type: ty, } @@ -14003,10 +14062,10 @@ func newFlowFeesFeesDeductedEventType() *cadence.EventType { address, _ := common.HexToAddress("f919ee77447b7497") location := common.NewAddressLocation(nil, address, "FlowFees") - return &cadence.EventType{ - Location: location, - QualifiedIdentifier: "FlowFees.FeesDeducted", - Fields: []cadence.Field{ + return cadence.NewEventType( + location, + "FlowFees.FeesDeducted", + []cadence.Field{ { Identifier: "amount", Type: cadence.UFix64Type, @@ -14020,7 +14079,8 @@ func newFlowFeesFeesDeductedEventType() *cadence.EventType { Type: cadence.UFix64Type, }, }, - } + nil, + ) } func createFlowFeesFeesDeductedEvent() cadence.Event { @@ -14047,16 +14107,17 @@ func newFlowFeesTokensWithdrawnEventType() *cadence.EventType { address, _ := common.HexToAddress("f919ee77447b7497") location := common.NewAddressLocation(nil, address, "FlowFees") - return &cadence.EventType{ - Location: location, - QualifiedIdentifier: "FlowFees.TokensWithdrawn", - Fields: []cadence.Field{ + return cadence.NewEventType( + location, + "FlowFees.TokensWithdrawn", + []cadence.Field{ { Identifier: "amount", Type: cadence.UFix64Type, }, }, - } + nil, + ) } func createFlowFeesTokensWithdrawnEvent() cadence.Event { @@ -14079,10 +14140,10 @@ func newFlowTokenTokensDepositedEventType() *cadence.EventType { address, _ := common.HexToAddress("1654653399040a61") location := common.NewAddressLocation(nil, address, "FlowToken") - return &cadence.EventType{ - Location: location, - QualifiedIdentifier: "FlowToken.TokensDeposited", - Fields: []cadence.Field{ + return cadence.NewEventType( + location, + "FlowToken.TokensDeposited", + []cadence.Field{ { Identifier: "amount", Type: cadence.UFix64Type, @@ -14094,7 +14155,8 @@ func newFlowTokenTokensDepositedEventType() *cadence.EventType { }, }, }, - } + nil, + ) } func createFlowTokenTokensDepositedEventNoReceiver() cadence.Event { @@ -14137,16 +14199,17 @@ func newFlowTokenTokensMintedEventType() *cadence.EventType { address, _ := common.HexToAddress("1654653399040a61") location := common.NewAddressLocation(nil, address, "FlowToken") - return &cadence.EventType{ - Location: location, - QualifiedIdentifier: "FlowToken.TokensMinted", - Fields: []cadence.Field{ + return cadence.NewEventType( + location, + "FlowToken.TokensMinted", + []cadence.Field{ { Identifier: "amount", Type: cadence.UFix64Type, }, }, - } + nil, + ) } func createFlowTokenTokensMintedEvent() cadence.Event { @@ -14169,10 +14232,10 @@ func newFlowTokenTokensWithdrawnEventType() *cadence.EventType { address, _ := common.HexToAddress("1654653399040a61") location := common.NewAddressLocation(nil, address, "FlowToken") - return &cadence.EventType{ - Location: location, - QualifiedIdentifier: "FlowToken.TokensWithdrawn", - Fields: []cadence.Field{ + return cadence.NewEventType( + location, + "FlowToken.TokensWithdrawn", + []cadence.Field{ { Identifier: "amount", Type: cadence.UFix64Type, @@ -14184,7 +14247,8 @@ func newFlowTokenTokensWithdrawnEventType() *cadence.EventType { }, }, }, - } + nil, + ) } func createFlowTokenTokensWithdrawnEvent() cadence.Event { @@ -14211,10 +14275,10 @@ func newFlowIDTableStakingDelegatorRewardsPaidEventType() *cadence.EventType { address, _ := common.HexToAddress("8624b52f9ddcd04a") location := common.NewAddressLocation(nil, address, "FlowIDTableStaking") - return &cadence.EventType{ - Location: location, - QualifiedIdentifier: "FlowIDTableStaking.DelegatorRewardsPaid", - Fields: []cadence.Field{ + return cadence.NewEventType( + location, + "FlowIDTableStaking.DelegatorRewardsPaid", + []cadence.Field{ { Identifier: "nodeID", Type: cadence.StringType, @@ -14228,7 +14292,8 @@ func newFlowIDTableStakingDelegatorRewardsPaidEventType() *cadence.EventType { Type: cadence.UFix64Type, }, }, - } + nil, + ) } func createFlowIDTableStakingDelegatorRewardsPaidEvent() cadence.Event { @@ -14255,10 +14320,10 @@ func newFlowIDTableStakingEpochTotalRewardsPaidEventType() *cadence.EventType { address, _ := common.HexToAddress("8624b52f9ddcd04a") location := common.NewAddressLocation(nil, address, "FlowIDTableStaking") - return &cadence.EventType{ - Location: location, - QualifiedIdentifier: "FlowIDTableStaking.EpochTotalRewardsPaid", - Fields: []cadence.Field{ + return cadence.NewEventType( + location, + "FlowIDTableStaking.EpochTotalRewardsPaid", + []cadence.Field{ { Identifier: "total", Type: cadence.UFix64Type, @@ -14276,7 +14341,8 @@ func newFlowIDTableStakingEpochTotalRewardsPaidEventType() *cadence.EventType { Type: cadence.UFix64Type, }, }, - } + nil, + ) } func createFlowIDTableStakingEpochTotalRewardsPaidEvent() cadence.Event { @@ -14305,16 +14371,17 @@ func newFlowIDTableStakingNewWeeklyPayoutEventType() *cadence.EventType { address, _ := common.HexToAddress("8624b52f9ddcd04a") location := common.NewAddressLocation(nil, address, "FlowIDTableStaking") - return &cadence.EventType{ - Location: location, - QualifiedIdentifier: "FlowIDTableStaking.NewWeeklyPayout", - Fields: []cadence.Field{ + return cadence.NewEventType( + location, + "FlowIDTableStaking.NewWeeklyPayout", + []cadence.Field{ { Identifier: "newPayout", Type: cadence.UFix64Type, }, }, - } + nil, + ) } func createFlowIDTableStakingNewWeeklyPayoutEvent() cadence.Event { @@ -14337,10 +14404,10 @@ func newFlowIDTableStakingRewardsPaidEventType() *cadence.EventType { address, _ := common.HexToAddress("8624b52f9ddcd04a") location := common.NewAddressLocation(nil, address, "FlowIDTableStaking") - return &cadence.EventType{ - Location: location, - QualifiedIdentifier: "FlowIDTableStaking.RewardsPaid", - Fields: []cadence.Field{ + return cadence.NewEventType( + location, + "FlowIDTableStaking.RewardsPaid", + []cadence.Field{ { Identifier: "nodeID", Type: cadence.StringType, @@ -14350,7 +14417,8 @@ func newFlowIDTableStakingRewardsPaidEventType() *cadence.EventType { Type: cadence.UFix64Type, }, }, - } + nil, + ) } func createFlowIDTableStakingRewardsPaidEvent() cadence.Event { diff --git a/encoding/ccf/ccf_type_id_test.go b/encoding/ccf/ccf_type_id_test.go index 1e84004e8f..eda0d4938c 100644 --- a/encoding/ccf/ccf_type_id_test.go +++ b/encoding/ccf/ccf_type_id_test.go @@ -116,23 +116,24 @@ func TestCadenceTypeByCCFTypeID(t *testing.T) { } func simpleStructType() *cadence.StructType { - return &cadence.StructType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooStruct", - Fields: []cadence.Field{ + return cadence.NewStructType( + utils.TestLocation, + "FooStruct", + []cadence.Field{ { Identifier: "a", Type: cadence.IntType, }, }, - } + nil, + ) } func simpleStructType2() *cadence.StructType { - return &cadence.StructType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooStruct2", - Fields: []cadence.Field{ + return cadence.NewStructType( + utils.TestLocation, + "FooStruct2", + []cadence.Field{ { Identifier: "a", Type: cadence.IntType, @@ -142,5 +143,6 @@ func simpleStructType2() *cadence.StructType { Type: cadence.StringType, }, }, - } + nil, + ) } diff --git a/encoding/ccf/decode.go b/encoding/ccf/decode.go index e0f4b60fe2..990b21605b 100644 --- a/encoding/ccf/decode.go +++ b/encoding/ccf/decode.go @@ -24,6 +24,7 @@ import ( "math" "math/big" goRuntime "runtime" + _ "unsafe" "github.com/fxamacker/cbor/v2" @@ -1210,11 +1211,17 @@ func (d *Decoder) decodeComposite(fieldTypes []cadence.Field, types *cadenceType return fieldValues, nil } +//go:linkname getCompositeTypeFields github.com/onflow/cadence.getCompositeTypeFields +func getCompositeTypeFields(cadence.CompositeType) []cadence.Field + +//go:linkname getInterfaceTypeFields github.com/onflow/cadence.getInterfaceTypeFields +func getInterfaceTypeFields(cadence.InterfaceType) []cadence.Field + // decodeStruct decodes encoded composite-value as // language=CDDL // composite-value = [* (field: value)] func (d *Decoder) decodeStruct(typ *cadence.StructType, types *cadenceTypeByCCFTypeID) (cadence.Value, error) { - fieldValues, err := d.decodeComposite(typ.Fields, types) + fieldValues, err := d.decodeComposite(getCompositeTypeFields(typ), types) if err != nil { return nil, err } @@ -1238,7 +1245,7 @@ func (d *Decoder) decodeStruct(typ *cadence.StructType, types *cadenceTypeByCCFT // language=CDDL // composite-value = [* (field: value)] func (d *Decoder) decodeResource(typ *cadence.ResourceType, types *cadenceTypeByCCFTypeID) (cadence.Value, error) { - fieldValues, err := d.decodeComposite(typ.Fields, types) + fieldValues, err := d.decodeComposite(getCompositeTypeFields(typ), types) if err != nil { return nil, err } @@ -1262,7 +1269,7 @@ func (d *Decoder) decodeResource(typ *cadence.ResourceType, types *cadenceTypeBy // language=CDDL // composite-value = [* (field: value)] func (d *Decoder) decodeEvent(typ *cadence.EventType, types *cadenceTypeByCCFTypeID) (cadence.Value, error) { - fieldValues, err := d.decodeComposite(typ.Fields, types) + fieldValues, err := d.decodeComposite(getCompositeTypeFields(typ), types) if err != nil { return nil, err } @@ -1286,7 +1293,7 @@ func (d *Decoder) decodeEvent(typ *cadence.EventType, types *cadenceTypeByCCFTyp // language=CDDL // composite-value = [* (field: value)] func (d *Decoder) decodeContract(typ *cadence.ContractType, types *cadenceTypeByCCFTypeID) (cadence.Value, error) { - fieldValues, err := d.decodeComposite(typ.Fields, types) + fieldValues, err := d.decodeComposite(getCompositeTypeFields(typ), types) if err != nil { return nil, err } @@ -1310,7 +1317,7 @@ func (d *Decoder) decodeContract(typ *cadence.ContractType, types *cadenceTypeBy // language=CDDL // composite-value = [* (field: value)] func (d *Decoder) decodeEnum(typ *cadence.EnumType, types *cadenceTypeByCCFTypeID) (cadence.Value, error) { - fieldValues, err := d.decodeComposite(typ.Fields, types) + fieldValues, err := d.decodeComposite(getCompositeTypeFields(typ), types) if err != nil { return nil, err } @@ -1334,7 +1341,7 @@ func (d *Decoder) decodeEnum(typ *cadence.EnumType, types *cadenceTypeByCCFTypeI // language=CDDL // composite-value = [* (field: value)] func (d *Decoder) decodeAttachment(typ *cadence.AttachmentType, types *cadenceTypeByCCFTypeID) (cadence.Value, error) { - fieldValues, err := d.decodeComposite(typ.Fields, types) + fieldValues, err := d.decodeComposite(getCompositeTypeFields(typ), types) if err != nil { return nil, err } @@ -1780,8 +1787,8 @@ func (d *Decoder) decodeAttachmentTypeValue(visited *cadenceTypeByCCFTypeID) (ca return cadence.NewMeteredAttachmentType( d.gauge, location, - typ, qualifiedIdentifier, + typ, nil, nil, ), nil @@ -1894,6 +1901,12 @@ type compositeTypeValue struct { rawInitializers []byte } +//go:linkname setCompositeTypeFields github.com/onflow/cadence.setCompositeTypeFields +func setCompositeTypeFields(cadence.CompositeType, []cadence.Field) + +//go:linkname setInterfaceTypeFields github.com/onflow/cadence.setInterfaceTypeFields +func setInterfaceTypeFields(cadence.InterfaceType, []cadence.Field) + // decodeCompositeTypeValue decodes composite-type-value. // See _decodeCompositeTypeValue for details. func (d *Decoder) decodeCompositeTypeValue( @@ -1943,11 +1956,11 @@ func (d *Decoder) decodeCompositeTypeValue( switch compositeType := compositeType.(type) { case *cadence.StructType: - compositeType.Fields = fields + setCompositeTypeFields(compositeType, fields) compositeType.Initializers = initializers case *cadence.ResourceType: - compositeType.Fields = fields + setCompositeTypeFields(compositeType, fields) compositeType.Initializers = initializers case *cadence.EventType: @@ -1957,31 +1970,31 @@ func (d *Decoder) decodeCompositeTypeValue( len(initializers), ) } - compositeType.Fields = fields + setCompositeTypeFields(compositeType, fields) compositeType.Initializer = initializers[0] case *cadence.ContractType: - compositeType.Fields = fields + setCompositeTypeFields(compositeType, fields) compositeType.Initializers = initializers case *cadence.EnumType: - compositeType.Fields = fields + setCompositeTypeFields(compositeType, fields) compositeType.Initializers = initializers case *cadence.AttachmentType: - compositeType.Fields = fields + setCompositeTypeFields(compositeType, fields) compositeType.Initializers = initializers case *cadence.StructInterfaceType: - compositeType.Fields = fields + setInterfaceTypeFields(compositeType, fields) compositeType.Initializers = initializers case *cadence.ResourceInterfaceType: - compositeType.Fields = fields + setInterfaceTypeFields(compositeType, fields) compositeType.Initializers = initializers case *cadence.ContractInterfaceType: - compositeType.Fields = fields + setInterfaceTypeFields(compositeType, fields) compositeType.Initializers = initializers } diff --git a/encoding/ccf/decode_typedef.go b/encoding/ccf/decode_typedef.go index 5221211b5c..11c4dd583e 100644 --- a/encoding/ccf/decode_typedef.go +++ b/encoding/ccf/decode_typedef.go @@ -133,7 +133,7 @@ func (d *Decoder) decodeTypeDefs() (*cadenceTypeByCCFTypeID, error) { switch typ := typ.(type) { case cadence.CompositeType: - typ.SetCompositeFields(fields) + setCompositeTypeFields(typ, fields) default: return nil, fmt.Errorf("unsupported type %s (%T) in composite-typedef", typ.ID(), typ) @@ -269,10 +269,10 @@ func (d *Decoder) decodeTypeDef( return cadence.NewMeteredAttachmentType( d.gauge, location, - nil, identifier, nil, nil, + nil, ) } return d.decodeCompositeType(types, ctr) diff --git a/encoding/ccf/encode.go b/encoding/ccf/encode.go index 8feb208515..9317773150 100644 --- a/encoding/ccf/encode.go +++ b/encoding/ccf/encode.go @@ -640,7 +640,7 @@ func (e *Encoder) encodeValue( // encodeVoid encodes cadence.Void as // language=CDDL // void-value = nil -func (e *Encoder) encodeVoid(v cadence.Void) error { +func (e *Encoder) encodeVoid(_ cadence.Void) error { return e.enc.EncodeNil() } @@ -1022,8 +1022,8 @@ func (e *Encoder) encodeInclusiveRange(v *cadence.InclusiveRange, tids ccfTypeID return e.encodeValue(v.Step, staticElementType, tids) } -//go:linkname getFieldValues github.com/onflow/cadence.getFieldValues -func getFieldValues(cadence.Composite) []cadence.Value +//go:linkname getCompositeFieldValues github.com/onflow/cadence.getCompositeFieldValues +func getCompositeFieldValues(cadence.Composite) []cadence.Value // encodeStruct encodes cadence.Struct as // language=CDDL @@ -1031,7 +1031,7 @@ func getFieldValues(cadence.Composite) []cadence.Value func (e *Encoder) encodeStruct(v cadence.Struct, tids ccfTypeIDByCadenceType) error { return e.encodeComposite( v.StructType, - getFieldValues(v), + getCompositeFieldValues(v), tids, ) } @@ -1042,7 +1042,7 @@ func (e *Encoder) encodeStruct(v cadence.Struct, tids ccfTypeIDByCadenceType) er func (e *Encoder) encodeResource(v cadence.Resource, tids ccfTypeIDByCadenceType) error { return e.encodeComposite( v.ResourceType, - getFieldValues(v), + getCompositeFieldValues(v), tids, ) } @@ -1053,7 +1053,7 @@ func (e *Encoder) encodeResource(v cadence.Resource, tids ccfTypeIDByCadenceType func (e *Encoder) encodeEvent(v cadence.Event, tids ccfTypeIDByCadenceType) error { return e.encodeComposite( v.EventType, - getFieldValues(v), + getCompositeFieldValues(v), tids, ) } @@ -1064,7 +1064,7 @@ func (e *Encoder) encodeEvent(v cadence.Event, tids ccfTypeIDByCadenceType) erro func (e *Encoder) encodeContract(v cadence.Contract, tids ccfTypeIDByCadenceType) error { return e.encodeComposite( v.ContractType, - getFieldValues(v), + getCompositeFieldValues(v), tids, ) } @@ -1075,7 +1075,7 @@ func (e *Encoder) encodeContract(v cadence.Contract, tids ccfTypeIDByCadenceType func (e *Encoder) encodeEnum(v cadence.Enum, tids ccfTypeIDByCadenceType) error { return e.encodeComposite( v.EnumType, - getFieldValues(v), + getCompositeFieldValues(v), tids, ) } @@ -1086,7 +1086,7 @@ func (e *Encoder) encodeEnum(v cadence.Enum, tids ccfTypeIDByCadenceType) error func (e *Encoder) encodeAttachment(v cadence.Attachment, tids ccfTypeIDByCadenceType) error { return e.encodeComposite( v.AttachmentType, - getFieldValues(v), + getCompositeFieldValues(v), tids, ) } @@ -1099,7 +1099,7 @@ func (e *Encoder) encodeComposite( fields []cadence.Value, tids ccfTypeIDByCadenceType, ) error { - staticFieldTypes := typ.CompositeFields() + staticFieldTypes := getCompositeTypeFields(typ) if len(staticFieldTypes) != len(fields) { panic(cadenceErrors.NewUnexpectedError( @@ -1564,7 +1564,7 @@ func (e *Encoder) encodeStructTypeValue(typ *cadence.StructType, visited ccfType return e.encodeCompositeTypeValue( typ.ID(), nil, - typ.Fields, + getCompositeTypeFields(typ), typ.Initializers, visited, rawTagNum, @@ -1582,7 +1582,7 @@ func (e *Encoder) encodeResourceTypeValue(typ *cadence.ResourceType, visited ccf return e.encodeCompositeTypeValue( typ.ID(), nil, - typ.Fields, + getCompositeTypeFields(typ), typ.Initializers, visited, rawTagNum, @@ -1600,7 +1600,7 @@ func (e *Encoder) encodeEventTypeValue(typ *cadence.EventType, visited ccfTypeID return e.encodeCompositeTypeValue( typ.ID(), nil, - typ.Fields, + getCompositeTypeFields(typ), [][]cadence.Parameter{typ.Initializer}, visited, rawTagNum, @@ -1618,7 +1618,7 @@ func (e *Encoder) encodeContractTypeValue(typ *cadence.ContractType, visited ccf return e.encodeCompositeTypeValue( typ.ID(), nil, - typ.Fields, + getCompositeTypeFields(typ), typ.Initializers, visited, rawTagNum, @@ -1636,7 +1636,7 @@ func (e *Encoder) encodeEnumTypeValue(typ *cadence.EnumType, visited ccfTypeIDBy return e.encodeCompositeTypeValue( typ.ID(), typ.RawType, - typ.Fields, + getCompositeTypeFields(typ), typ.Initializers, visited, rawTagNum, @@ -1654,7 +1654,7 @@ func (e *Encoder) encodeAttachmentTypeValue(typ *cadence.AttachmentType, visited return e.encodeCompositeTypeValue( typ.ID(), typ.BaseType, - typ.Fields, + getCompositeTypeFields(typ), typ.Initializers, visited, rawTagNum, @@ -1672,7 +1672,7 @@ func (e *Encoder) encodeStructInterfaceTypeValue(typ *cadence.StructInterfaceTyp return e.encodeCompositeTypeValue( typ.ID(), nil, - typ.Fields, + getInterfaceTypeFields(typ), typ.Initializers, visited, rawTagNum, @@ -1690,7 +1690,7 @@ func (e *Encoder) encodeResourceInterfaceTypeValue(typ *cadence.ResourceInterfac return e.encodeCompositeTypeValue( typ.ID(), nil, - typ.Fields, + getInterfaceTypeFields(typ), typ.Initializers, visited, rawTagNum, @@ -1708,7 +1708,7 @@ func (e *Encoder) encodeContractInterfaceTypeValue(typ *cadence.ContractInterfac return e.encodeCompositeTypeValue( typ.ID(), nil, - typ.Fields, + getInterfaceTypeFields(typ), typ.Initializers, visited, rawTagNum, @@ -2182,7 +2182,7 @@ func (e *Encoder) getSortedFieldIndex(t cadence.CompositeType) []int { // NOTE: bytewiseFieldIdentifierSorter doesn't sort fields in place. // bytewiseFieldIdentifierSorter.indexes is used as sorted fieldTypes // index. - sorter := newBytewiseFieldSorter(t.CompositeFields()) + sorter := newBytewiseFieldSorter(getCompositeTypeFields(t)) sort.Sort(sorter) diff --git a/encoding/ccf/encode_typedef.go b/encoding/ccf/encode_typedef.go index 50897e5731..844f1cc0d0 100644 --- a/encoding/ccf/encode_typedef.go +++ b/encoding/ccf/encode_typedef.go @@ -136,7 +136,7 @@ func (e *Encoder) encodeCompositeType(typ cadence.CompositeType, tids ccfTypeIDB // ] // ] func (e *Encoder) encodeCompositeTypeFields(typ cadence.CompositeType, tids ccfTypeIDByCadenceType) error { - fieldTypes := typ.CompositeFields() + fieldTypes := getCompositeTypeFields(typ) // Encode array head with number of fields. err := e.enc.EncodeArrayHead(uint64(len(fieldTypes))) diff --git a/encoding/ccf/service_events_test.go b/encoding/ccf/service_events_test.go index b5244db5fb..b6e7c3c74a 100644 --- a/encoding/ccf/service_events_test.go +++ b/encoding/ccf/service_events_test.go @@ -52,12 +52,15 @@ func TestEpochSetupEvent(t *testing.T) { evtType, ok := decodedValue.Type().(*cadence.EventType) require.True(t, ok) - require.Len(t, evtType.Fields, 9) + + typeFields := evtType.FieldsMappedByName() + + require.Len(t, typeFields, 9) // field 0: counter require.Equal(t, - "counter", - evtType.Fields[0].Identifier, + cadence.UInt64Type, + typeFields["counter"], ) require.Equal(t, cadence.UInt64(1), @@ -65,9 +68,9 @@ func TestEpochSetupEvent(t *testing.T) { ) // field 1: nodeInfo - require.Equal(t, - "nodeInfo", - evtType.Fields[1].Identifier, + require.IsType(t, + cadence.NewVariableSizedArrayType(newFlowIDTableStakingNodeInfoStructType()), + typeFields["nodeInfo"], ) nodeInfos, ok := fields["nodeInfo"].(cadence.Array) require.True(t, ok) @@ -75,8 +78,8 @@ func TestEpochSetupEvent(t *testing.T) { // field 2: firstView require.Equal(t, - "firstView", - evtType.Fields[2].Identifier, + cadence.UInt64Type, + typeFields["firstView"], ) require.Equal(t, cadence.UInt64(100), @@ -85,8 +88,8 @@ func TestEpochSetupEvent(t *testing.T) { // field 3: finalView require.Equal(t, - "finalView", - evtType.Fields[3].Identifier, + cadence.UInt64Type, + typeFields["finalView"], ) require.Equal(t, cadence.UInt64(200), @@ -95,8 +98,8 @@ func TestEpochSetupEvent(t *testing.T) { // field 4: collectorClusters require.Equal(t, - "collectorClusters", - evtType.Fields[4].Identifier, + cadence.NewVariableSizedArrayType(newFlowClusterQCClusterStructType()), + typeFields["collectorClusters"], ) epochCollectors, ok := fields["collectorClusters"].(cadence.Array) require.True(t, ok) @@ -104,8 +107,8 @@ func TestEpochSetupEvent(t *testing.T) { // field 5: randomSource require.Equal(t, - "randomSource", - evtType.Fields[5].Identifier, + cadence.StringType, + typeFields["randomSource"], ) require.Equal(t, cadence.String("01020304"), @@ -114,8 +117,8 @@ func TestEpochSetupEvent(t *testing.T) { // field 6: DKGPhase1FinalView require.Equal(t, - "DKGPhase1FinalView", - evtType.Fields[6].Identifier, + cadence.UInt64Type, + typeFields["DKGPhase1FinalView"], ) require.Equal(t, cadence.UInt64(150), @@ -124,8 +127,8 @@ func TestEpochSetupEvent(t *testing.T) { // field 7: DKGPhase2FinalView require.Equal(t, - "DKGPhase2FinalView", - evtType.Fields[7].Identifier, + cadence.UInt64Type, + typeFields["DKGPhase2FinalView"], ) require.Equal(t, cadence.UInt64(160), @@ -134,8 +137,8 @@ func TestEpochSetupEvent(t *testing.T) { // field 8: DKGPhase3FinalView require.Equal(t, - "DKGPhase3FinalView", - evtType.Fields[8].Identifier, + cadence.UInt64Type, + typeFields["DKGPhase3FinalView"], ) require.Equal(t, cadence.UInt64(170), @@ -156,12 +159,14 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { nodeInfoType, ok := node0.Type().(*cadence.StructType) require.True(t, ok) - require.Len(t, nodeInfoType.Fields, 14) + + node0FieldTypes := nodeInfoType.FieldsMappedByName() + require.Len(t, node0FieldTypes, 14) // field 0: id require.Equal(t, - "id", - nodeInfoType.Fields[0].Identifier, + cadence.StringType, + node0FieldTypes["id"], ) require.Equal(t, cadence.String("0000000000000000000000000000000000000000000000000000000000000001"), @@ -170,8 +175,8 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { // field 1: role require.Equal(t, - "role", - nodeInfoType.Fields[1].Identifier, + cadence.UInt8Type, + node0FieldTypes["role"], ) require.Equal(t, cadence.UInt8(1), @@ -180,8 +185,8 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { // field 2: networkingAddress require.Equal(t, - "networkingAddress", - nodeInfoType.Fields[2].Identifier, + cadence.StringType, + node0FieldTypes["networkingAddress"], ) require.Equal(t, cadence.String("1.flow.com"), @@ -190,8 +195,8 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { // field 3: networkingKey require.Equal(t, - "networkingKey", - nodeInfoType.Fields[3].Identifier, + cadence.StringType, + node0FieldTypes["networkingKey"], ) require.Equal(t, cadence.String("378dbf45d85c614feb10d8bd4f78f4b6ef8eec7d987b937e123255444657fb3da031f232a507e323df3a6f6b8f50339c51d188e80c0e7a92420945cc6ca893fc"), @@ -200,8 +205,8 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { // field 4: stakingKey require.Equal(t, - "stakingKey", - nodeInfoType.Fields[4].Identifier, + cadence.StringType, + node0FieldTypes["stakingKey"], ) require.Equal(t, cadence.String("af4aade26d76bb2ab15dcc89adcef82a51f6f04b3cb5f4555214b40ec89813c7a5f95776ea4fe449de48166d0bbc59b919b7eabebaac9614cf6f9461fac257765415f4d8ef1376a2365ec9960121888ea5383d88a140c24c29962b0a14e4e4e7"), @@ -210,8 +215,8 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { // field 5: tokensStaked require.Equal(t, - "tokensStaked", - nodeInfoType.Fields[5].Identifier, + cadence.UFix64Type, + node0FieldTypes["tokensStaked"], ) require.Equal(t, ufix64FromString("0.00000000"), @@ -220,8 +225,8 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { // field 6: tokensCommitted require.Equal(t, - "tokensCommitted", - nodeInfoType.Fields[6].Identifier, + cadence.UFix64Type, + node0FieldTypes["tokensCommitted"], ) require.Equal(t, ufix64FromString("1350000.00000000"), @@ -230,8 +235,8 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { // field 7: tokensUnstaking require.Equal(t, - "tokensUnstaking", - nodeInfoType.Fields[7].Identifier, + cadence.UFix64Type, + node0FieldTypes["tokensUnstaking"], ) require.Equal(t, ufix64FromString("0.00000000"), @@ -240,8 +245,8 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { // field 8: tokensUnstaked require.Equal(t, - "tokensUnstaked", - nodeInfoType.Fields[8].Identifier, + cadence.UFix64Type, + node0FieldTypes["tokensUnstaked"], ) require.Equal(t, ufix64FromString("0.00000000"), @@ -250,8 +255,8 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { // field 9: tokensRewarded require.Equal(t, - "tokensRewarded", - nodeInfoType.Fields[9].Identifier, + cadence.UFix64Type, + node0FieldTypes["tokensRewarded"], ) require.Equal(t, ufix64FromString("0.00000000"), @@ -259,28 +264,41 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { ) // field 10: delegators - require.Equal(t, "delegators", nodeInfoType.Fields[10].Identifier) + require.Equal(t, + cadence.NewVariableSizedArrayType(cadence.UInt32Type), + node0FieldTypes["delegators"], + ) delegators, ok := node0Fields["delegators"].(cadence.Array) require.True(t, ok) require.Len(t, delegators.Values, 0) // field 11: delegatorIDCounter - require.Equal(t, "delegatorIDCounter", nodeInfoType.Fields[11].Identifier) + require.Equal( + t, + cadence.UInt32Type, + node0FieldTypes["delegatorIDCounter"], + ) require.Equal(t, cadence.UInt32(0), node0Fields["delegatorIDCounter"], ) // field 12: tokensRequestedToUnstake - require.Equal(t, "tokensRequestedToUnstake", nodeInfoType.Fields[12].Identifier) + require.Equal(t, + cadence.UFix64Type, + node0FieldTypes["tokensRequestedToUnstake"], + ) require.Equal(t, ufix64FromString("0.00000000"), node0Fields["tokensRequestedToUnstake"], ) // field 13: initialWeight - require.Equal(t, "initialWeight", nodeInfoType.Fields[13].Identifier) + require.Equal(t, + cadence.UInt64Type, + node0FieldTypes["initialWeight"], + ) require.Equal(t, cadence.UInt64(100), node0Fields["initialWeight"], @@ -295,10 +313,15 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { nodeInfoType, ok = node6.Type().(*cadence.StructType) require.True(t, ok) - require.Len(t, nodeInfoType.Fields, 14) + + node6FieldTypes := nodeInfoType.FieldsMappedByName() + require.Len(t, node6FieldTypes, 14) // field 0: id - require.Equal(t, "id", nodeInfoType.Fields[0].Identifier) + require.Equal(t, + cadence.StringType, + node6FieldTypes["id"], + ) require.Equal(t, cadence.String("0000000000000000000000000000000000000000000000000000000000000031"), node6Fields["id"], @@ -306,8 +329,8 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { // field 1: role require.Equal(t, - "role", - nodeInfoType.Fields[1].Identifier, + cadence.UInt8Type, + node6FieldTypes["role"], ) require.Equal(t, cadence.UInt8(4), @@ -316,8 +339,8 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { // field 2: networkingAddress require.Equal(t, - "networkingAddress", - nodeInfoType.Fields[2].Identifier, + cadence.StringType, + node6FieldTypes["networkingAddress"], ) require.Equal(t, cadence.String("31.flow.com"), @@ -326,8 +349,8 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { // field 3: networkingKey require.Equal(t, - "networkingKey", - nodeInfoType.Fields[3].Identifier, + cadence.StringType, + node6FieldTypes["networkingKey"], ) require.Equal(t, cadence.String("697241208dcc9142b6f53064adc8ff1c95760c68beb2ba083c1d005d40181fd7a1b113274e0163c053a3addd47cd528ec6a1f190cf465aac87c415feaae011ae"), @@ -336,8 +359,8 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { // field 4: stakingKey require.Equal(t, - "stakingKey", - nodeInfoType.Fields[4].Identifier, + cadence.StringType, + node6FieldTypes["stakingKey"], ) require.Equal(t, cadence.String("b1f97d0a06020eca97352e1adde72270ee713c7daf58da7e74bf72235321048b4841bdfc28227964bf18e371e266e32107d238358848bcc5d0977a0db4bda0b4c33d3874ff991e595e0f537c7b87b4ddce92038ebc7b295c9ea20a1492302aa7"), @@ -346,8 +369,8 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { // field 5: tokensStaked require.Equal(t, - "tokensStaked", - nodeInfoType.Fields[5].Identifier, + cadence.UFix64Type, + node6FieldTypes["tokensStaked"], ) require.Equal(t, ufix64FromString("0.00000000"), @@ -356,8 +379,8 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { // field 6: tokensCommitted require.Equal(t, - "tokensCommitted", - nodeInfoType.Fields[6].Identifier, + cadence.UFix64Type, + node6FieldTypes["tokensCommitted"], ) require.Equal(t, ufix64FromString("1350000.00000000"), @@ -366,8 +389,8 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { // field 7: tokensUnstaking require.Equal(t, - "tokensUnstaking", - nodeInfoType.Fields[7].Identifier, + cadence.UFix64Type, + node6FieldTypes["tokensUnstaking"], ) require.Equal(t, ufix64FromString("0.00000000"), @@ -376,8 +399,8 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { // field 8: tokensUnstaked require.Equal(t, - "tokensUnstaked", - nodeInfoType.Fields[8].Identifier, + cadence.UFix64Type, + node6FieldTypes["tokensUnstaked"], ) require.Equal(t, ufix64FromString("0.00000000"), @@ -386,8 +409,8 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { // field 9: tokensRewarded require.Equal(t, - "tokensRewarded", - nodeInfoType.Fields[9].Identifier, + cadence.UFix64Type, + node6FieldTypes["tokensRewarded"], ) require.Equal(t, ufix64FromString("0.00000000"), @@ -396,8 +419,8 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { // field 10: delegators require.Equal(t, - "delegators", - nodeInfoType.Fields[10].Identifier, + cadence.NewVariableSizedArrayType(cadence.UInt32Type), + node6FieldTypes["delegators"], ) delegators, ok = node6Fields["delegators"].(cadence.Array) require.True(t, ok) @@ -405,8 +428,8 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { // field 11: delegatorIDCounter require.Equal(t, - "delegatorIDCounter", - nodeInfoType.Fields[11].Identifier, + cadence.UInt32Type, + node6FieldTypes["delegatorIDCounter"], ) require.Equal(t, cadence.UInt32(0), @@ -415,8 +438,8 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { // field 12: tokensRequestedToUnstake require.Equal(t, - "tokensRequestedToUnstake", - nodeInfoType.Fields[12].Identifier, + cadence.UFix64Type, + node6FieldTypes["tokensRequestedToUnstake"], ) require.Equal(t, ufix64FromString("0.00000000"), @@ -425,8 +448,8 @@ func testNodeInfos(t *testing.T, nodeInfos cadence.Array) { // field 13: initialWeight require.Equal(t, - "initialWeight", - nodeInfoType.Fields[13].Identifier, + cadence.UInt64Type, + node6FieldTypes["initialWeight"], ) require.Equal(t, cadence.UInt64(100), @@ -441,15 +464,17 @@ func testEpochCollectors(t *testing.T, collectors cadence.Array) { collector0, ok := collectors.Values[0].(cadence.Struct) require.True(t, ok) - collectorType, ok := collector0.Type().(*cadence.StructType) + collector0Type, ok := collector0.Type().(*cadence.StructType) require.True(t, ok) collector0Fields := cadence.FieldsMappedByName(collector0) + collector0FieldTypes := collector0Type.FieldsMappedByName() + // field 0: index require.Equal(t, - "index", - collectorType.Fields[0].Identifier, + cadence.UInt16Type, + collector0FieldTypes["index"], ) require.Equal(t, cadence.UInt16(0), @@ -458,8 +483,8 @@ func testEpochCollectors(t *testing.T, collectors cadence.Array) { // field 1: nodeWeights require.Equal(t, - "nodeWeights", - collectorType.Fields[1].Identifier, + cadence.NewDictionaryType(cadence.StringType, cadence.UInt64Type), + collector0FieldTypes["nodeWeights"], ) weights, ok := collector0Fields["nodeWeights"].(cadence.Dictionary) require.True(t, ok) @@ -482,8 +507,8 @@ func testEpochCollectors(t *testing.T, collectors cadence.Array) { // field 2: totalWeight require.Equal(t, - "totalWeight", - collectorType.Fields[2].Identifier, + cadence.UInt64Type, + collector0FieldTypes["totalWeight"], ) require.Equal(t, cadence.NewUInt64(100), @@ -492,8 +517,8 @@ func testEpochCollectors(t *testing.T, collectors cadence.Array) { // field 3: generatedVotes require.Equal(t, - "generatedVotes", - collectorType.Fields[3].Identifier, + cadence.NewDictionaryType(cadence.StringType, newFlowClusterQCVoteStructType()), + collector0FieldTypes["generatedVotes"], ) generatedVotes, ok := collector0Fields["generatedVotes"].(cadence.Dictionary) require.True(t, ok) @@ -501,8 +526,8 @@ func testEpochCollectors(t *testing.T, collectors cadence.Array) { // field 4: uniqueVoteMessageTotalWeights require.Equal(t, - "uniqueVoteMessageTotalWeights", - collectorType.Fields[4].Identifier, + cadence.NewDictionaryType(cadence.StringType, cadence.UInt64Type), + collector0FieldTypes["uniqueVoteMessageTotalWeights"], ) uniqueVoteMessageTotalWeights, ok := collector0Fields["uniqueVoteMessageTotalWeights"].(cadence.Dictionary) require.True(t, ok) @@ -512,15 +537,16 @@ func testEpochCollectors(t *testing.T, collectors cadence.Array) { collector1, ok := collectors.Values[1].(cadence.Struct) require.True(t, ok) - collectorType, ok = collector1.Type().(*cadence.StructType) + collector1Type, ok := collector1.Type().(*cadence.StructType) require.True(t, ok) - collector1Fields := cadence.FieldsMappedByName(collector1) + collector1Fields := collector1.FieldsMappedByName() + collector1FieldTypes := collector1Type.FieldsMappedByName() // field 0: index require.Equal(t, - "index", - collectorType.Fields[0].Identifier, + cadence.UInt16Type, + collector1FieldTypes["index"], ) require.Equal(t, cadence.UInt16(1), @@ -529,8 +555,8 @@ func testEpochCollectors(t *testing.T, collectors cadence.Array) { // field 1: nodeWeights require.Equal(t, - "nodeWeights", - collectorType.Fields[1].Identifier, + cadence.NewDictionaryType(cadence.StringType, cadence.UInt64Type), + collector1FieldTypes["nodeWeights"], ) weights, ok = collector1Fields["nodeWeights"].(cadence.Dictionary) require.True(t, ok) @@ -552,8 +578,8 @@ func testEpochCollectors(t *testing.T, collectors cadence.Array) { // field 2: totalWeight require.Equal(t, - "totalWeight", - collectorType.Fields[2].Identifier, + cadence.UInt64Type, + collector1FieldTypes["totalWeight"], ) require.Equal(t, cadence.NewUInt64(0), @@ -562,8 +588,8 @@ func testEpochCollectors(t *testing.T, collectors cadence.Array) { // field 3: generatedVotes require.Equal(t, - "generatedVotes", - collectorType.Fields[3].Identifier, + cadence.NewDictionaryType(cadence.StringType, newFlowClusterQCVoteStructType()), + collector1FieldTypes["generatedVotes"], ) generatedVotes, ok = collector1Fields["generatedVotes"].(cadence.Dictionary) require.True(t, ok) @@ -571,8 +597,8 @@ func testEpochCollectors(t *testing.T, collectors cadence.Array) { // field 4: uniqueVoteMessageTotalWeights require.Equal(t, - "uniqueVoteMessageTotalWeights", - collectorType.Fields[4].Identifier, + cadence.NewDictionaryType(cadence.StringType, cadence.UInt64Type), + collector1FieldTypes["uniqueVoteMessageTotalWeights"], ) uniqueVoteMessageTotalWeights, ok = collector1Fields["uniqueVoteMessageTotalWeights"].(cadence.Dictionary) require.True(t, ok) @@ -603,12 +629,14 @@ func TestEpochCommitEvent(t *testing.T) { evtType, ok := decodedValue.Type().(*cadence.EventType) require.True(t, ok) - require.Len(t, evtType.Fields, 3) + + fieldTypes := evtType.FieldsMappedByName() + require.Len(t, fieldTypes, 3) // field 0: counter require.Equal(t, - "counter", - evtType.Fields[0].Identifier, + cadence.UInt64Type, + fieldTypes["counter"], ) require.Equal(t, cadence.UInt64(1), @@ -617,8 +645,8 @@ func TestEpochCommitEvent(t *testing.T) { // field 1: clusterQCs require.Equal(t, - "clusterQCs", - evtType.Fields[1].Identifier, + cadence.NewVariableSizedArrayType(newFlowClusterQCClusterQCStructType()), + fieldTypes["clusterQCs"], ) clusterQCs, ok := fields["clusterQCs"].(cadence.Array) require.True(t, ok) @@ -626,8 +654,8 @@ func TestEpochCommitEvent(t *testing.T) { // field 2: dkgPubKeys require.Equal(t, - "dkgPubKeys", - evtType.Fields[2].Identifier, + cadence.NewVariableSizedArrayType(cadence.StringType), + fieldTypes["dkgPubKeys"], ) dkgPubKeys, ok := fields["dkgPubKeys"].(cadence.Array) require.True(t, ok) @@ -652,10 +680,14 @@ func testClusterQCs(t *testing.T, clusterQCs cadence.Array) { clusterQCType, ok := clusterQC0.Type().(*cadence.StructType) require.True(t, ok) - clusterQC0Fields := cadence.FieldsMappedByName(clusterQC0) + clusterQC0Fields := clusterQC0.FieldsMappedByName() + clusterQC0FieldTypes := clusterQCType.FieldsMappedByName() // field 0: index - require.Equal(t, "index", clusterQCType.Fields[0].Identifier) + require.Equal(t, + cadence.UInt16Type, + clusterQC0FieldTypes["index"], + ) require.Equal(t, cadence.UInt16(0), clusterQC0Fields["index"], @@ -663,8 +695,8 @@ func testClusterQCs(t *testing.T, clusterQCs cadence.Array) { // field 1: voteSignatures require.Equal(t, - "voteSignatures", - clusterQCType.Fields[1].Identifier, + cadence.NewVariableSizedArrayType(cadence.StringType), + clusterQC0FieldTypes["voteSignatures"], ) sigs, ok := clusterQC0Fields["voteSignatures"].(cadence.Array) require.True(t, ok) @@ -678,8 +710,8 @@ func testClusterQCs(t *testing.T, clusterQCs cadence.Array) { // field 2: voteMessage require.Equal(t, - "voteMessage", - clusterQCType.Fields[2].Identifier, + cadence.StringType, + clusterQC0FieldTypes["voteMessage"], ) require.Equal(t, cadence.String("irrelevant_for_these_purposes"), @@ -688,8 +720,8 @@ func testClusterQCs(t *testing.T, clusterQCs cadence.Array) { // field 3: voterIDs require.Equal(t, - "voterIDs", - clusterQCType.Fields[3].Identifier, + cadence.NewVariableSizedArrayType(cadence.StringType), + clusterQC0FieldTypes["voterIDs"], ) ids, ok := clusterQC0Fields["voterIDs"].(cadence.Array) require.True(t, ok) @@ -706,15 +738,16 @@ func testClusterQCs(t *testing.T, clusterQCs cadence.Array) { clusterQC1, ok := clusterQCs.Values[1].(cadence.Struct) require.True(t, ok) - clusterQCType, ok = clusterQC1.Type().(*cadence.StructType) + clusterQC1Type, ok := clusterQC1.Type().(*cadence.StructType) require.True(t, ok) - clusterQC1Fields := cadence.FieldsMappedByName(clusterQC1) + clusterQC1Fields := clusterQC1.FieldsMappedByName() + clusterQC1FieldTypes := clusterQC1Type.FieldsMappedByName() // field 0: index require.Equal(t, - "index", - clusterQCType.Fields[0].Identifier, + cadence.UInt16Type, + clusterQC1FieldTypes["index"], ) require.Equal(t, cadence.UInt16(1), @@ -723,8 +756,8 @@ func testClusterQCs(t *testing.T, clusterQCs cadence.Array) { // field 1: voteSignatures require.Equal(t, - "voteSignatures", - clusterQCType.Fields[1].Identifier, + cadence.NewVariableSizedArrayType(cadence.StringType), + clusterQC1FieldTypes["voteSignatures"], ) sigs, ok = clusterQC1Fields["voteSignatures"].(cadence.Array) require.True(t, ok) @@ -738,8 +771,8 @@ func testClusterQCs(t *testing.T, clusterQCs cadence.Array) { // field 2: voteMessage require.Equal(t, - "voteMessage", - clusterQCType.Fields[2].Identifier, + cadence.StringType, + clusterQC1FieldTypes["voteMessage"], ) require.Equal(t, cadence.String("irrelevant_for_these_purposes"), @@ -748,8 +781,8 @@ func testClusterQCs(t *testing.T, clusterQCs cadence.Array) { // field 3: voterIDs require.Equal(t, - "voterIDs", - clusterQCType.Fields[3].Identifier, + cadence.NewVariableSizedArrayType(cadence.StringType), + clusterQC1FieldTypes["voterIDs"], ) ids, ok = clusterQC1Fields["voterIDs"].(cadence.Array) require.True(t, ok) @@ -786,12 +819,14 @@ func TestVersionBeaconEvent(t *testing.T) { evtType, ok := decodedValue.Type().(*cadence.EventType) require.True(t, ok) - require.Len(t, evtType.Fields, 2) + + fieldTypes := evtType.FieldsMappedByName() + require.Len(t, fieldTypes, 2) // field 0: versionBoundaries require.Equal(t, - "versionBoundaries", - evtType.Fields[0].Identifier, + cadence.NewVariableSizedArrayType(newNodeVersionBeaconVersionBoundaryStructType()), + fieldTypes["versionBoundaries"], ) versionBoundaries, ok := fields["versionBoundaries"].(cadence.Array) require.True(t, ok) @@ -799,8 +834,8 @@ func TestVersionBeaconEvent(t *testing.T) { // field 1: sequence require.Equal(t, - "sequence", - evtType.Fields[1].Identifier, + cadence.UInt64Type, + fieldTypes["sequence"], ) require.Equal(t, cadence.UInt64(5), @@ -819,12 +854,14 @@ func testVersionBoundaries(t *testing.T, versionBoundaries cadence.Array) { boundaryType, ok := boundary.Type().(*cadence.StructType) require.True(t, ok) - require.Len(t, boundaryType.Fields, 2) + + fieldTypes := boundaryType.FieldsMappedByName() + require.Len(t, fieldTypes, 2) // field 0: blockHeight require.Equal(t, - "blockHeight", - boundaryType.Fields[0].Identifier, + cadence.UInt64Type, + fieldTypes["blockHeight"], ) require.Equal(t, cadence.UInt64(44), @@ -833,8 +870,8 @@ func testVersionBoundaries(t *testing.T, versionBoundaries cadence.Array) { // field 1: version require.Equal(t, - "version", - boundaryType.Fields[1].Identifier, + newNodeVersionBeaconSemverStructType(), + fieldTypes["version"], ) version, ok := fields["version"].(cadence.Struct) require.True(t, ok) @@ -848,12 +885,14 @@ func testSemver(t *testing.T, version cadence.Struct) { semverType, ok := version.Type().(*cadence.StructType) require.True(t, ok) - require.Len(t, semverType.Fields, 4) + + fieldTypes := semverType.FieldsMappedByName() + require.Len(t, fieldTypes, 4) // field 0: preRelease require.Equal(t, - "preRelease", - semverType.Fields[0].Identifier, + cadence.NewOptionalType(cadence.StringType), + fieldTypes["preRelease"], ) require.Equal(t, cadence.NewOptional(cadence.String("")), @@ -862,8 +901,8 @@ func testSemver(t *testing.T, version cadence.Struct) { // field 1: major require.Equal(t, - "major", - semverType.Fields[1].Identifier, + cadence.UInt8Type, + fieldTypes["major"], ) require.Equal(t, cadence.UInt8(2), @@ -872,8 +911,8 @@ func testSemver(t *testing.T, version cadence.Struct) { // field 2: minor require.Equal(t, - "minor", - semverType.Fields[2].Identifier, + cadence.UInt8Type, + fieldTypes["minor"], ) require.Equal(t, cadence.UInt8(13), @@ -882,8 +921,8 @@ func testSemver(t *testing.T, version cadence.Struct) { // field 3: patch require.Equal(t, - "patch", - semverType.Fields[3].Identifier, + cadence.UInt8Type, + fieldTypes["patch"], ) require.Equal(t, cadence.UInt8(7), @@ -1416,10 +1455,10 @@ func newFlowClusterQCVoteStructType() cadence.Type { address, _ := common.HexToAddress("01cf0e2f2f715450") location := common.NewAddressLocation(nil, address, "FlowClusterQC") - return &cadence.StructType{ - Location: location, - QualifiedIdentifier: "FlowClusterQC.Vote", - Fields: []cadence.Field{ + return cadence.NewStructType( + location, + "FlowClusterQC.Vote", + []cadence.Field{ { Identifier: "nodeID", Type: cadence.StringType, @@ -1441,7 +1480,8 @@ func newFlowClusterQCVoteStructType() cadence.Type { Type: cadence.UInt64Type, }, }, - } + nil, + ) } func newFlowClusterQCClusterStructType() *cadence.StructType { @@ -1451,10 +1491,10 @@ func newFlowClusterQCClusterStructType() *cadence.StructType { address, _ := common.HexToAddress("01cf0e2f2f715450") location := common.NewAddressLocation(nil, address, "FlowClusterQC") - return &cadence.StructType{ - Location: location, - QualifiedIdentifier: "FlowClusterQC.Cluster", - Fields: []cadence.Field{ + return cadence.NewStructType( + location, + "FlowClusterQC.Cluster", + []cadence.Field{ { Identifier: "index", Type: cadence.UInt16Type, @@ -1476,7 +1516,8 @@ func newFlowClusterQCClusterStructType() *cadence.StructType { Type: cadence.NewDictionaryType(cadence.StringType, cadence.UInt64Type), }, }, - } + nil, + ) } func newFlowIDTableStakingNodeInfoStructType() *cadence.StructType { @@ -1486,10 +1527,10 @@ func newFlowIDTableStakingNodeInfoStructType() *cadence.StructType { address, _ := common.HexToAddress("01cf0e2f2f715450") location := common.NewAddressLocation(nil, address, "FlowIDTableStaking") - return &cadence.StructType{ - Location: location, - QualifiedIdentifier: "FlowIDTableStaking.NodeInfo", - Fields: []cadence.Field{ + return cadence.NewStructType( + location, + "FlowIDTableStaking.NodeInfo", + []cadence.Field{ { Identifier: "id", Type: cadence.StringType, @@ -1547,7 +1588,8 @@ func newFlowIDTableStakingNodeInfoStructType() *cadence.StructType { Type: cadence.UInt64Type, }, }, - } + nil, + ) } func newFlowEpochEpochSetupEventType() *cadence.EventType { @@ -1557,10 +1599,10 @@ func newFlowEpochEpochSetupEventType() *cadence.EventType { address, _ := common.HexToAddress("01cf0e2f2f715450") location := common.NewAddressLocation(nil, address, "FlowEpoch") - return &cadence.EventType{ - Location: location, - QualifiedIdentifier: "FlowEpoch.EpochSetup", - Fields: []cadence.Field{ + return cadence.NewEventType( + location, + "FlowEpoch.EpochSetup", + []cadence.Field{ { Identifier: "counter", Type: cadence.UInt64Type, @@ -1598,7 +1640,8 @@ func newFlowEpochEpochSetupEventType() *cadence.EventType { Type: cadence.UInt64Type, }, }, - } + nil, + ) } func newFlowEpochEpochCommittedEventType() *cadence.EventType { @@ -1608,10 +1651,10 @@ func newFlowEpochEpochCommittedEventType() *cadence.EventType { address, _ := common.HexToAddress("01cf0e2f2f715450") location := common.NewAddressLocation(nil, address, "FlowEpoch") - return &cadence.EventType{ - Location: location, - QualifiedIdentifier: "FlowEpoch.EpochCommitted", - Fields: []cadence.Field{ + return cadence.NewEventType( + location, + "FlowEpoch.EpochCommitted", + []cadence.Field{ { Identifier: "counter", Type: cadence.UInt64Type, @@ -1625,7 +1668,8 @@ func newFlowEpochEpochCommittedEventType() *cadence.EventType { Type: cadence.NewVariableSizedArrayType(cadence.StringType), }, }, - } + nil, + ) } func newFlowClusterQCClusterQCStructType() *cadence.StructType { @@ -1635,10 +1679,10 @@ func newFlowClusterQCClusterQCStructType() *cadence.StructType { address, _ := common.HexToAddress("01cf0e2f2f715450") location := common.NewAddressLocation(nil, address, "FlowClusterQC") - return &cadence.StructType{ - Location: location, - QualifiedIdentifier: "FlowClusterQC.ClusterQC", - Fields: []cadence.Field{ + return cadence.NewStructType( + location, + "FlowClusterQC.ClusterQC", + []cadence.Field{ { Identifier: "index", Type: cadence.UInt16Type, @@ -1656,7 +1700,8 @@ func newFlowClusterQCClusterQCStructType() *cadence.StructType { Type: cadence.NewVariableSizedArrayType(cadence.StringType), }, }, - } + nil, + ) } func newNodeVersionBeaconVersionBeaconEventType() *cadence.EventType { @@ -1666,10 +1711,10 @@ func newNodeVersionBeaconVersionBeaconEventType() *cadence.EventType { address, _ := common.HexToAddress("01cf0e2f2f715450") location := common.NewAddressLocation(nil, address, "NodeVersionBeacon") - return &cadence.EventType{ - Location: location, - QualifiedIdentifier: "NodeVersionBeacon.VersionBeacon", - Fields: []cadence.Field{ + return cadence.NewEventType( + location, + "NodeVersionBeacon.VersionBeacon", + []cadence.Field{ { Identifier: "versionBoundaries", Type: cadence.NewVariableSizedArrayType(newNodeVersionBeaconVersionBoundaryStructType()), @@ -1679,7 +1724,8 @@ func newNodeVersionBeaconVersionBeaconEventType() *cadence.EventType { Type: cadence.UInt64Type, }, }, - } + nil, + ) } func newNodeVersionBeaconVersionBoundaryStructType() *cadence.StructType { @@ -1689,10 +1735,10 @@ func newNodeVersionBeaconVersionBoundaryStructType() *cadence.StructType { address, _ := common.HexToAddress("01cf0e2f2f715450") location := common.NewAddressLocation(nil, address, "NodeVersionBeacon") - return &cadence.StructType{ - Location: location, - QualifiedIdentifier: "NodeVersionBeacon.VersionBoundary", - Fields: []cadence.Field{ + return cadence.NewStructType( + location, + "NodeVersionBeacon.VersionBoundary", + []cadence.Field{ { Identifier: "blockHeight", Type: cadence.UInt64Type, @@ -1702,7 +1748,8 @@ func newNodeVersionBeaconVersionBoundaryStructType() *cadence.StructType { Type: newNodeVersionBeaconSemverStructType(), }, }, - } + nil, + ) } func newNodeVersionBeaconSemverStructType() *cadence.StructType { @@ -1712,10 +1759,10 @@ func newNodeVersionBeaconSemverStructType() *cadence.StructType { address, _ := common.HexToAddress("01cf0e2f2f715450") location := common.NewAddressLocation(nil, address, "NodeVersionBeacon") - return &cadence.StructType{ - Location: location, - QualifiedIdentifier: "NodeVersionBeacon.Semver", - Fields: []cadence.Field{ + return cadence.NewStructType( + location, + "NodeVersionBeacon.Semver", + []cadence.Field{ { Identifier: "preRelease", Type: cadence.NewOptionalType(cadence.StringType), @@ -1733,7 +1780,8 @@ func newNodeVersionBeaconSemverStructType() *cadence.StructType { Type: cadence.UInt8Type, }, }, - } + nil, + ) } func ufix64FromString(s string) cadence.UFix64 { diff --git a/encoding/ccf/traverse_value.go b/encoding/ccf/traverse_value.go index 3b1208b601..78c8ca74ef 100644 --- a/encoding/ccf/traverse_value.go +++ b/encoding/ccf/traverse_value.go @@ -97,27 +97,27 @@ func (ct *compositeTypes) traverseValue(v cadence.Value) { } case cadence.Struct: - for _, field := range getFieldValues(v) { + for _, field := range getCompositeFieldValues(v) { ct.traverseValue(field) } case cadence.Resource: - for _, field := range getFieldValues(v) { + for _, field := range getCompositeFieldValues(v) { ct.traverseValue(field) } case cadence.Event: - for _, field := range getFieldValues(v) { + for _, field := range getCompositeFieldValues(v) { ct.traverseValue(field) } case cadence.Contract: - for _, field := range getFieldValues(v) { + for _, field := range getCompositeFieldValues(v) { ct.traverseValue(field) } case cadence.Attachment: - for _, field := range getFieldValues(v) { + for _, field := range getCompositeFieldValues(v) { ct.traverseValue(field) } } @@ -163,7 +163,7 @@ func (ct *compositeTypes) traverseType(typ cadence.Type) (checkRuntimeType bool) } check := false - fields := typ.CompositeFields() + fields := getCompositeTypeFields(typ) for _, field := range fields { checkField := ct.traverseType(field.Type) check = check || checkField diff --git a/encoding/json/decode.go b/encoding/json/decode.go index 9e71309baa..1b7c44f60e 100644 --- a/encoding/json/decode.go +++ b/encoding/json/decode.go @@ -25,6 +25,7 @@ import ( "io" "math/big" "strconv" + _ "unsafe" "github.com/onflow/cadence" "github.com/onflow/cadence/runtime/common" @@ -1076,6 +1077,12 @@ func (d *Decoder) decodeAuthorization(authorizationJSON any) cadence.Authorizati panic(errors.NewDefaultUserError("invalid kind in authorization: %s", kind)) } +//go:linkname setCompositeTypeFields github.com/onflow/cadence.setCompositeTypeFields +func setCompositeTypeFields(cadence.CompositeType, []cadence.Field) + +//go:linkname setInterfaceTypeFields github.com/onflow/cadence.setInterfaceTypeFields +func setInterfaceTypeFields(cadence.InterfaceType, []cadence.Field) + func (d *Decoder) decodeNominalType( obj jsonObject, kind, typeID string, @@ -1185,9 +1192,9 @@ func (d *Decoder) decodeNominalType( switch { case compositeType != nil: - compositeType.SetCompositeFields(fields) + setCompositeTypeFields(compositeType, fields) case interfaceType != nil: - interfaceType.SetInterfaceFields(fields) + setInterfaceTypeFields(interfaceType, fields) } return result diff --git a/encoding/json/encode.go b/encoding/json/encode.go index ebe13a029b..f3512868c2 100644 --- a/encoding/json/encode.go +++ b/encoding/json/encode.go @@ -604,15 +604,21 @@ func prepareInclusiveRange(v *cadence.InclusiveRange) jsonValue { } } -//go:linkname getFieldValues github.com/onflow/cadence.getFieldValues -func getFieldValues(cadence.Composite) []cadence.Value +//go:linkname getCompositeFieldValues github.com/onflow/cadence.getCompositeFieldValues +func getCompositeFieldValues(cadence.Composite) []cadence.Value + +//go:linkname getCompositeTypeFields github.com/onflow/cadence.getCompositeTypeFields +func getCompositeTypeFields(cadence.CompositeType) []cadence.Field + +//go:linkname getInterfaceTypeFields github.com/onflow/cadence.getInterfaceTypeFields +func getInterfaceTypeFields(cadence.InterfaceType) []cadence.Field func prepareStruct(v cadence.Struct) jsonValue { return prepareComposite( structTypeStr, v.StructType.ID(), - v.StructType.Fields, - getFieldValues(v), + getCompositeTypeFields(v.StructType), + getCompositeFieldValues(v), ) } @@ -620,8 +626,8 @@ func prepareResource(v cadence.Resource) jsonValue { return prepareComposite( resourceTypeStr, v.ResourceType.ID(), - v.ResourceType.Fields, - getFieldValues(v), + getCompositeTypeFields(v.ResourceType), + getCompositeFieldValues(v), ) } @@ -629,8 +635,8 @@ func prepareEvent(v cadence.Event) jsonValue { return prepareComposite( eventTypeStr, v.EventType.ID(), - v.EventType.Fields, - getFieldValues(v), + getCompositeTypeFields(v.EventType), + getCompositeFieldValues(v), ) } @@ -638,8 +644,8 @@ func prepareContract(v cadence.Contract) jsonValue { return prepareComposite( contractTypeStr, v.ContractType.ID(), - v.ContractType.Fields, - getFieldValues(v), + getCompositeTypeFields(v.ContractType), + getCompositeFieldValues(v), ) } @@ -647,8 +653,8 @@ func prepareEnum(v cadence.Enum) jsonValue { return prepareComposite( enumTypeStr, v.EnumType.ID(), - v.EnumType.Fields, - getFieldValues(v), + getCompositeTypeFields(v.EnumType), + getCompositeFieldValues(v), ) } @@ -656,13 +662,13 @@ func prepareAttachment(v cadence.Attachment) jsonValue { return prepareComposite( attachmentTypeStr, v.AttachmentType.ID(), - v.AttachmentType.Fields, - getFieldValues(v), + getCompositeTypeFields(v.AttachmentType), + getCompositeFieldValues(v), ) } func prepareComposite(kind, id string, fieldTypes []cadence.Field, fields []cadence.Value) jsonValue { - // Ensure there are _at least _ as many field values as field types. + // Ensure there are _at least_ as many field values as field types. // There might be more field values in the case of attachments. if len(fields) < len(fieldTypes) { panic(fmt.Errorf( @@ -860,7 +866,7 @@ func PrepareType(typ cadence.Type, results TypePreparationResults) jsonValue { Kind: "Struct", Type: "", TypeID: string(common.NewTypeIDFromQualifiedName(nil, typ.Location, typ.QualifiedIdentifier)), - Fields: prepareFields(typ.Fields, results), + Fields: prepareFields(getCompositeTypeFields(typ), results), Initializers: prepareInitializers(typ.Initializers, results), } case *cadence.ResourceType: @@ -868,7 +874,7 @@ func PrepareType(typ cadence.Type, results TypePreparationResults) jsonValue { Kind: "Resource", Type: "", TypeID: string(common.NewTypeIDFromQualifiedName(nil, typ.Location, typ.QualifiedIdentifier)), - Fields: prepareFields(typ.Fields, results), + Fields: prepareFields(getCompositeTypeFields(typ), results), Initializers: prepareInitializers(typ.Initializers, results), } case *cadence.EventType: @@ -876,7 +882,7 @@ func PrepareType(typ cadence.Type, results TypePreparationResults) jsonValue { Kind: "Event", Type: "", TypeID: string(common.NewTypeIDFromQualifiedName(nil, typ.Location, typ.QualifiedIdentifier)), - Fields: prepareFields(typ.Fields, results), + Fields: prepareFields(getCompositeTypeFields(typ), results), Initializers: [][]jsonParameterType{prepareParameters(typ.Initializer, results)}, } case *cadence.ContractType: @@ -884,7 +890,7 @@ func PrepareType(typ cadence.Type, results TypePreparationResults) jsonValue { Kind: "Contract", Type: "", TypeID: string(common.NewTypeIDFromQualifiedName(nil, typ.Location, typ.QualifiedIdentifier)), - Fields: prepareFields(typ.Fields, results), + Fields: prepareFields(getCompositeTypeFields(typ), results), Initializers: prepareInitializers(typ.Initializers, results), } case *cadence.StructInterfaceType: @@ -892,7 +898,7 @@ func PrepareType(typ cadence.Type, results TypePreparationResults) jsonValue { Kind: "StructInterface", Type: "", TypeID: string(common.NewTypeIDFromQualifiedName(nil, typ.Location, typ.QualifiedIdentifier)), - Fields: prepareFields(typ.Fields, results), + Fields: prepareFields(getInterfaceTypeFields(typ), results), Initializers: prepareInitializers(typ.Initializers, results), } case *cadence.ResourceInterfaceType: @@ -900,7 +906,7 @@ func PrepareType(typ cadence.Type, results TypePreparationResults) jsonValue { Kind: "ResourceInterface", Type: "", TypeID: string(common.NewTypeIDFromQualifiedName(nil, typ.Location, typ.QualifiedIdentifier)), - Fields: prepareFields(typ.Fields, results), + Fields: prepareFields(getInterfaceTypeFields(typ), results), Initializers: prepareInitializers(typ.Initializers, results), } case *cadence.ContractInterfaceType: @@ -908,7 +914,7 @@ func PrepareType(typ cadence.Type, results TypePreparationResults) jsonValue { Kind: "ContractInterface", Type: "", TypeID: string(common.NewTypeIDFromQualifiedName(nil, typ.Location, typ.QualifiedIdentifier)), - Fields: prepareFields(typ.Fields, results), + Fields: prepareFields(getInterfaceTypeFields(typ), results), Initializers: prepareInitializers(typ.Initializers, results), } case *cadence.FunctionType: @@ -948,7 +954,7 @@ func PrepareType(typ cadence.Type, results TypePreparationResults) jsonValue { return jsonNominalType{ Kind: "Enum", TypeID: string(common.NewTypeIDFromQualifiedName(nil, typ.Location, typ.QualifiedIdentifier)), - Fields: prepareFields(typ.Fields, results), + Fields: prepareFields(getCompositeTypeFields(typ), results), Initializers: prepareInitializers(typ.Initializers, results), Type: PrepareType(typ.RawType, results), } diff --git a/encoding/json/encoding_test.go b/encoding/json/encoding_test.go index 8981f1abab..9ba6776788 100644 --- a/encoding/json/encoding_test.go +++ b/encoding/json/encoding_test.go @@ -1323,10 +1323,10 @@ func TestEncodeStruct(t *testing.T) { t.Parallel() - simpleStructType := &cadence.StructType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooStruct", - Fields: []cadence.Field{ + simpleStructType := cadence.NewStructType( + utils.TestLocation, + "FooStruct", + []cadence.Field{ { Identifier: "a", Type: cadence.IntType, @@ -1336,7 +1336,8 @@ func TestEncodeStruct(t *testing.T) { Type: cadence.StringType, }, }, - } + nil, + ) simpleStruct := encodeTest{ "Simple", @@ -1375,10 +1376,10 @@ func TestEncodeStruct(t *testing.T) { fooResourceType := newFooResourceType() - resourceStructType := &cadence.StructType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooStruct", - Fields: []cadence.Field{ + resourceStructType := cadence.NewStructType( + utils.TestLocation, + "FooStruct", + []cadence.Field{ { Identifier: "a", Type: cadence.StringType, @@ -1388,7 +1389,8 @@ func TestEncodeStruct(t *testing.T) { Type: fooResourceType, }, }, - } + nil, + ) resourceStruct := encodeTest{ "Resources", @@ -1483,10 +1485,10 @@ func TestEncodeEvent(t *testing.T) { t.Parallel() - simpleEventType := &cadence.EventType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooEvent", - Fields: []cadence.Field{ + simpleEventType := cadence.NewEventType( + utils.TestLocation, + "FooEvent", + []cadence.Field{ { Identifier: "a", Type: cadence.IntType, @@ -1496,7 +1498,8 @@ func TestEncodeEvent(t *testing.T) { Type: cadence.StringType, }, }, - } + nil, + ) simpleEvent := encodeTest{ "Simple", @@ -1535,10 +1538,10 @@ func TestEncodeEvent(t *testing.T) { fooResourceType := newFooResourceType() - resourceEventType := &cadence.EventType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooEvent", - Fields: []cadence.Field{ + resourceEventType := cadence.NewEventType( + utils.TestLocation, + "FooEvent", + []cadence.Field{ { Identifier: "a", Type: cadence.StringType, @@ -1548,7 +1551,8 @@ func TestEncodeEvent(t *testing.T) { Type: fooResourceType, }, }, - } + nil, + ) resourceEvent := encodeTest{ "Resources", @@ -1607,10 +1611,10 @@ func TestEncodeContract(t *testing.T) { t.Parallel() - simpleContractType := &cadence.ContractType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooContract", - Fields: []cadence.Field{ + simpleContractType := cadence.NewContractType( + utils.TestLocation, + "FooContract", + []cadence.Field{ { Identifier: "a", Type: cadence.IntType, @@ -1620,7 +1624,8 @@ func TestEncodeContract(t *testing.T) { Type: cadence.StringType, }, }, - } + nil, + ) simpleContract := encodeTest{ "Simple", @@ -1659,10 +1664,10 @@ func TestEncodeContract(t *testing.T) { fooResourceType := newFooResourceType() - resourceContractType := &cadence.ContractType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooContract", - Fields: []cadence.Field{ + resourceContractType := cadence.NewContractType( + utils.TestLocation, + "FooContract", + []cadence.Field{ { Identifier: "a", Type: cadence.StringType, @@ -1672,7 +1677,8 @@ func TestEncodeContract(t *testing.T) { Type: fooResourceType, }, }, - } + nil, + ) resourceContract := encodeTest{ "Resources", @@ -1896,17 +1902,17 @@ func TestEncodeType(t *testing.T) { testEncodeAndDecode( t, cadence.TypeValue{ - StaticType: &cadence.StructType{ - Location: utils.TestLocation, - QualifiedIdentifier: "S", - Fields: []cadence.Field{ + StaticType: cadence.NewStructType( + utils.TestLocation, + "S", + []cadence.Field{ {Identifier: "foo", Type: cadence.IntType}, }, - Initializers: [][]cadence.Parameter{ + [][]cadence.Parameter{ {{Label: "foo", Identifier: "bar", Type: cadence.IntType}}, {{Label: "qux", Identifier: "baz", Type: cadence.StringType}}, }, - }, + ), }, // language=json ` @@ -1957,17 +1963,17 @@ func TestEncodeType(t *testing.T) { testEncodeAndDecode( t, cadence.TypeValue{ - StaticType: &cadence.ResourceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "R", - Fields: []cadence.Field{ + StaticType: cadence.NewResourceType( + utils.TestLocation, + "R", + []cadence.Field{ {Identifier: "foo", Type: cadence.IntType}, }, - Initializers: [][]cadence.Parameter{ + [][]cadence.Parameter{ {{Label: "foo", Identifier: "bar", Type: cadence.IntType}}, {{Label: "qux", Identifier: "baz", Type: cadence.StringType}}, }, - }, + ), }, // language=json ` @@ -2018,17 +2024,17 @@ func TestEncodeType(t *testing.T) { testEncodeAndDecode( t, cadence.TypeValue{ - StaticType: &cadence.ContractType{ - Location: utils.TestLocation, - QualifiedIdentifier: "C", - Fields: []cadence.Field{ + StaticType: cadence.NewContractType( + utils.TestLocation, + "C", + []cadence.Field{ {Identifier: "foo", Type: cadence.IntType}, }, - Initializers: [][]cadence.Parameter{ + [][]cadence.Parameter{ {{Label: "foo", Identifier: "bar", Type: cadence.IntType}}, {{Label: "qux", Identifier: "baz", Type: cadence.StringType}}, }, - }, + ), }, // language=json ` @@ -2079,17 +2085,17 @@ func TestEncodeType(t *testing.T) { testEncodeAndDecode( t, cadence.TypeValue{ - StaticType: &cadence.StructInterfaceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "S", - Fields: []cadence.Field{ + StaticType: cadence.NewStructInterfaceType( + utils.TestLocation, + "S", + []cadence.Field{ {Identifier: "foo", Type: cadence.IntType}, }, - Initializers: [][]cadence.Parameter{ + [][]cadence.Parameter{ {{Label: "foo", Identifier: "bar", Type: cadence.IntType}}, {{Label: "qux", Identifier: "baz", Type: cadence.StringType}}, }, - }, + ), }, // language=json ` @@ -2140,17 +2146,17 @@ func TestEncodeType(t *testing.T) { testEncodeAndDecode( t, cadence.TypeValue{ - StaticType: &cadence.ResourceInterfaceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "R", - Fields: []cadence.Field{ + StaticType: cadence.NewResourceInterfaceType( + utils.TestLocation, + "R", + []cadence.Field{ {Identifier: "foo", Type: cadence.IntType}, }, - Initializers: [][]cadence.Parameter{ + [][]cadence.Parameter{ {{Label: "foo", Identifier: "bar", Type: cadence.IntType}}, {{Label: "qux", Identifier: "baz", Type: cadence.StringType}}, }, - }, + ), }, // language=json ` @@ -2201,17 +2207,17 @@ func TestEncodeType(t *testing.T) { testEncodeAndDecode( t, cadence.TypeValue{ - StaticType: &cadence.ContractInterfaceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "C", - Fields: []cadence.Field{ + StaticType: cadence.NewContractInterfaceType( + utils.TestLocation, + "C", + []cadence.Field{ {Identifier: "foo", Type: cadence.IntType}, }, - Initializers: [][]cadence.Parameter{ + [][]cadence.Parameter{ {{Label: "foo", Identifier: "bar", Type: cadence.IntType}}, {{Label: "qux", Identifier: "baz", Type: cadence.StringType}}, }, - }, + ), }, // language=json ` @@ -2262,17 +2268,17 @@ func TestEncodeType(t *testing.T) { testEncodeAndDecode( t, cadence.TypeValue{ - StaticType: &cadence.EventType{ - Location: utils.TestLocation, - QualifiedIdentifier: "E", - Fields: []cadence.Field{ + StaticType: cadence.NewEventType( + utils.TestLocation, + "E", + []cadence.Field{ {Identifier: "foo", Type: cadence.IntType}, }, - Initializer: []cadence.Parameter{ + []cadence.Parameter{ {Label: "foo", Identifier: "bar", Type: cadence.IntType}, {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, - }, + ), }, // language=json ` @@ -2321,18 +2327,18 @@ func TestEncodeType(t *testing.T) { testEncodeAndDecode( t, cadence.TypeValue{ - StaticType: &cadence.EnumType{ - Location: utils.TestLocation, - QualifiedIdentifier: "E", - RawType: cadence.StringType, - Fields: []cadence.Field{ + StaticType: cadence.NewEnumType( + utils.TestLocation, + "E", + cadence.StringType, + []cadence.Field{ {Identifier: "foo", Type: cadence.IntType}, }, - Initializers: [][]cadence.Parameter{ + [][]cadence.Parameter{ {{Label: "foo", Identifier: "bar", Type: cadence.IntType}}, {{Label: "qux", Identifier: "baz", Type: cadence.StringType}}, }, - }, + ), }, // language=json ` @@ -3255,17 +3261,19 @@ func TestExportRecursiveType(t *testing.T) { t.Parallel() - ty := &cadence.ResourceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ - { - Identifier: "foo", - }, + fields := []cadence.Field{ + { + Identifier: "foo", }, } + ty := cadence.NewResourceType( + utils.TestLocation, + "Foo", + fields, + nil, + ) - ty.Fields[0].Type = &cadence.OptionalType{ + fields[0].Type = &cadence.OptionalType{ Type: ty, } @@ -3304,18 +3312,19 @@ func TestExportTypeValueRecursiveType(t *testing.T) { t.Parallel() - ty := &cadence.ResourceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ - { - Identifier: "foo", - }, + fields := []cadence.Field{ + { + Identifier: "foo", }, - Initializers: [][]cadence.Parameter{}, } + ty := cadence.NewResourceType( + utils.TestLocation, + "Foo", + fields, + [][]cadence.Parameter{}, + ) - ty.Fields[0].Type = &cadence.OptionalType{ + fields[0].Type = &cadence.OptionalType{ Type: ty, } @@ -3355,17 +3364,17 @@ func TestExportTypeValueRecursiveType(t *testing.T) { t.Parallel() - fooTy := &cadence.ResourceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{}, - Initializers: [][]cadence.Parameter{}, - } + fooTy := cadence.NewResourceType( + utils.TestLocation, + "Foo", + []cadence.Field{}, + [][]cadence.Parameter{}, + ) - barTy := &cadence.ResourceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "Bar", - Fields: []cadence.Field{ + barTy := cadence.NewResourceType( + utils.TestLocation, + "Bar", + []cadence.Field{ { Identifier: "foo1", Type: fooTy, @@ -3375,8 +3384,8 @@ func TestExportTypeValueRecursiveType(t *testing.T) { Type: fooTy, }, }, - Initializers: [][]cadence.Parameter{}, - } + [][]cadence.Parameter{}, + ) testEncodeAndDecode( t, @@ -3578,16 +3587,17 @@ func testDecode(t *testing.T, actualJSON string, expectedVal cadence.Value, opti } func newFooResourceType() *cadence.ResourceType { - return &cadence.ResourceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ + return cadence.NewResourceType( + utils.TestLocation, + "Foo", + []cadence.Field{ { Identifier: "bar", Type: cadence.IntType, }, }, - } + nil, + ) } func TestNonUTF8StringEncoding(t *testing.T) { diff --git a/runtime/convertTypes.go b/runtime/convertTypes.go index 427964e468..8315bf2ee6 100644 --- a/runtime/convertTypes.go +++ b/runtime/convertTypes.go @@ -342,8 +342,8 @@ func exportCompositeType( result = cadence.NewMeteredAttachmentType( gauge, t.Location, - ExportMeteredType(gauge, t.GetBaseType(), results), t.QualifiedIdentifier(), + ExportMeteredType(gauge, t.GetBaseType(), results), fields, nil, ) diff --git a/runtime/convertTypes_test.go b/runtime/convertTypes_test.go index 0dcc08970e..fe26743584 100644 --- a/runtime/convertTypes_test.go +++ b/runtime/convertTypes_test.go @@ -53,18 +53,21 @@ func TestRuntimeExportRecursiveType(t *testing.T) { VariableKind: ast.VariableKindVariable, }) - expected := &cadence.ResourceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ - { - Identifier: "foo", - }, + fields := []cadence.Field{ + { + Identifier: "foo", }, } + expected := cadence.NewResourceType( + utils.TestLocation, + "Foo", + fields, + nil, + ) + // NOTE: recursion should be kept - expected.Fields[0].Type = expected + fields[0].Type = expected assert.Equal(t, expected, @@ -108,18 +111,21 @@ func BenchmarkExportType(b *testing.B) { VariableKind: ast.VariableKindVariable, }) - expected := &cadence.ResourceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ - { - Identifier: "foo", - }, + fields := []cadence.Field{ + { + Identifier: "foo", }, } + expected := cadence.NewResourceType( + utils.TestLocation, + "Foo", + fields, + nil, + ) + // NOTE: recursion should be kept - expected.Fields[0].Type = expected + fields[0].Type = expected exportedType := ExportType(ty, map[sema.TypeID]cadence.Type{}) assert.Equal(b, expected, exportedType) diff --git a/runtime/convertValues.go b/runtime/convertValues.go index 025a9e2c8b..83c9126111 100644 --- a/runtime/convertValues.go +++ b/runtime/convertValues.go @@ -399,12 +399,12 @@ func exportCompositeValue( // NOTE: use the exported type's fields to ensure fields in type // and value are in sync - fieldNames := t.CompositeFields() + fields := getCompositeTypeFields(t) - makeFields := func() ([]cadence.Value, error) { - fields := make([]cadence.Value, len(fieldNames)) + makeFieldsValues := func() ([]cadence.Value, error) { + fieldValues := make([]cadence.Value, len(fields)) - for i, field := range fieldNames { + for i, field := range fields { fieldName := field.Identifier var fieldValue interpreter.Value @@ -434,7 +434,7 @@ func exportCompositeValue( if err != nil { return nil, err } - fields[i] = exportedFieldValue + fieldValues[i] = exportedFieldValue } if composite, ok := v.(*interpreter.CompositeValue); ok { @@ -448,11 +448,11 @@ func exportCompositeValue( if err != nil { return nil, err } - fields = append(fields, exportedAttachmentValue) + fieldValues = append(fieldValues, exportedAttachmentValue) } } - return fields, nil + return fieldValues, nil } compositeKind := compositeType.Kind @@ -464,8 +464,8 @@ func exportCompositeValue( case common.CompositeKindStructure: structure, err := cadence.NewMeteredStruct( inter, - len(fieldNames), - makeFields, + len(fields), + makeFieldsValues, ) if err != nil { return nil, err @@ -475,8 +475,8 @@ func exportCompositeValue( case common.CompositeKindResource: resource, err := cadence.NewMeteredResource( inter, - len(fieldNames), - makeFields, + len(fields), + makeFieldsValues, ) if err != nil { return nil, err @@ -486,8 +486,8 @@ func exportCompositeValue( case common.CompositeKindAttachment: attachment, err := cadence.NewMeteredAttachment( inter, - len(fieldNames), - makeFields, + len(fields), + makeFieldsValues, ) if err != nil { return nil, err @@ -497,8 +497,8 @@ func exportCompositeValue( case common.CompositeKindEvent: event, err := cadence.NewMeteredEvent( inter, - len(fieldNames), - makeFields, + len(fields), + makeFieldsValues, ) if err != nil { return nil, err @@ -508,8 +508,8 @@ func exportCompositeValue( case common.CompositeKindContract: contract, err := cadence.NewMeteredContract( inter, - len(fieldNames), - makeFields, + len(fields), + makeFieldsValues, ) if err != nil { return nil, err @@ -519,8 +519,8 @@ func exportCompositeValue( case common.CompositeKindEnum: enum, err := cadence.NewMeteredEnum( inter, - len(fieldNames), - makeFields, + len(fields), + makeFieldsValues, ) if err != nil { return nil, err @@ -776,8 +776,11 @@ func ImportValue( }.importValue(value, expectedType) } -//go:linkname getFieldValues github.com/onflow/cadence.getFieldValues -func getFieldValues(cadence.Composite) []cadence.Value +//go:linkname getCompositeFieldValues github.com/onflow/cadence.getCompositeFieldValues +func getCompositeFieldValues(cadence.Composite) []cadence.Value + +//go:linkname getCompositeTypeFields github.com/onflow/cadence.getCompositeTypeFields +func getCompositeTypeFields(cadence.CompositeType) []cadence.Field func (i valueImporter) importValue(value cadence.Value, expectedType sema.Type) (interpreter.Value, error) { switch v := value.(type) { @@ -850,32 +853,32 @@ func (i valueImporter) importValue(value cadence.Value, expectedType sema.Type) common.CompositeKindStructure, v.StructType.Location, v.StructType.QualifiedIdentifier, - v.StructType.Fields, - getFieldValues(v), + getCompositeTypeFields(v.StructType), + getCompositeFieldValues(v), ) case cadence.Resource: return i.importCompositeValue( common.CompositeKindResource, v.ResourceType.Location, v.ResourceType.QualifiedIdentifier, - v.ResourceType.Fields, - getFieldValues(v), + getCompositeTypeFields(v.ResourceType), + getCompositeFieldValues(v), ) case cadence.Event: return i.importCompositeValue( common.CompositeKindEvent, v.EventType.Location, v.EventType.QualifiedIdentifier, - v.EventType.Fields, - getFieldValues(v), + getCompositeTypeFields(v.EventType), + getCompositeFieldValues(v), ) case cadence.Enum: return i.importCompositeValue( common.CompositeKindEnum, v.EnumType.Location, v.EnumType.QualifiedIdentifier, - v.EnumType.Fields, - getFieldValues(v), + getCompositeTypeFields(v.EnumType), + getCompositeFieldValues(v), ) case *cadence.InclusiveRange: return i.importInclusiveRangeValue(v, expectedType) diff --git a/runtime/convertValues_test.go b/runtime/convertValues_test.go index f4460bf9ae..25848d3db1 100644 --- a/runtime/convertValues_test.go +++ b/runtime/convertValues_test.go @@ -83,22 +83,25 @@ func TestRuntimeExportValue(t *testing.T) { } newSignatureAlgorithmType := func() *cadence.EnumType { - return &cadence.EnumType{ - QualifiedIdentifier: "SignatureAlgorithm", - RawType: cadence.UInt8Type, - Fields: []cadence.Field{ + return cadence.NewEnumType( + nil, + "SignatureAlgorithm", + cadence.UInt8Type, + []cadence.Field{ { Identifier: "rawValue", Type: cadence.UInt8Type, }, }, - } + nil, + ) } newPublicKeyType := func(signatureAlgorithmType cadence.Type) *cadence.StructType { - return &cadence.StructType{ - QualifiedIdentifier: "PublicKey", - Fields: []cadence.Field{ + return cadence.NewStructType( + nil, + "PublicKey", + []cadence.Field{ { Identifier: "publicKey", Type: &cadence.VariableSizedArrayType{ @@ -110,20 +113,23 @@ func TestRuntimeExportValue(t *testing.T) { Type: signatureAlgorithmType, }, }, - } + nil, + ) } newHashAlgorithmType := func() *cadence.EnumType { - return &cadence.EnumType{ - QualifiedIdentifier: "HashAlgorithm", - RawType: cadence.UInt8Type, - Fields: []cadence.Field{ + return cadence.NewEnumType( + nil, + "HashAlgorithm", + cadence.UInt8Type, + []cadence.Field{ { Identifier: "rawValue", Type: cadence.UInt8Type, }, }, - } + nil, + ) } testCharacter, _ := cadence.NewCharacter("a") @@ -493,9 +499,10 @@ func TestRuntimeExportValue(t *testing.T) { }).WithType(hashAlgorithmType), cadence.UFix64(10_00000000), cadence.Bool(false), - }).WithType(&cadence.StructType{ - QualifiedIdentifier: "AccountKey", - Fields: []cadence.Field{ + }).WithType(cadence.NewStructType( + nil, + "AccountKey", + []cadence.Field{ { Identifier: "keyIndex", Type: cadence.IntType, @@ -517,7 +524,8 @@ func TestRuntimeExportValue(t *testing.T) { Type: cadence.BoolType, }, }, - }) + nil, + )) }(), }, { @@ -1459,11 +1467,12 @@ func TestRuntimeExportStructValue(t *testing.T) { } ` - fooStructType := &cadence.StructType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Foo", - Fields: fooFields, - } + fooStructType := cadence.NewStructType( + common.ScriptLocation{}, + "Foo", + fooFields, + nil, + ) actual := exportValueFromScript(t, script) expected := cadence.NewStruct([]cadence.Value{ @@ -1531,11 +1540,11 @@ func TestRuntimeExportResourceArrayValue(t *testing.T) { cadence.NewUInt64(2), cadence.NewInt(4), }).WithType(fooResourceType), - }).WithType(&cadence.VariableSizedArrayType{ - ElementType: &cadence.ResourceType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ + }).WithType(cadence.NewVariableSizedArrayType( + cadence.NewResourceType( + common.ScriptLocation{}, + "Foo", + []cadence.Field{ { Identifier: "uuid", Type: cadence.UInt64Type, @@ -1545,8 +1554,9 @@ func TestRuntimeExportResourceArrayValue(t *testing.T) { Type: cadence.IntType, }, }, - }, - }) + nil, + ), + )) assert.Equal(t, expected, actual) } @@ -1593,10 +1603,10 @@ func TestRuntimeExportResourceDictionaryValue(t *testing.T) { }, }).WithType(&cadence.DictionaryType{ KeyType: cadence.StringType, - ElementType: &cadence.ResourceType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ + ElementType: cadence.NewResourceType( + common.ScriptLocation{}, + "Foo", + []cadence.Field{ { Identifier: "uuid", Type: cadence.UInt64Type, @@ -1606,7 +1616,8 @@ func TestRuntimeExportResourceDictionaryValue(t *testing.T) { Type: cadence.IntType, }, }, - }, + nil, + ), }) assert.Equal(t, expected, actual) @@ -1616,10 +1627,10 @@ func TestRuntimeExportNestedResourceValueFromScript(t *testing.T) { t.Parallel() - barResourceType := &cadence.ResourceType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Bar", - Fields: []cadence.Field{ + barResourceType := cadence.NewResourceType( + common.ScriptLocation{}, + "Bar", + []cadence.Field{ { Identifier: "uuid", Type: cadence.UInt64Type, @@ -1629,12 +1640,13 @@ func TestRuntimeExportNestedResourceValueFromScript(t *testing.T) { Type: cadence.IntType, }, }, - } + nil, + ) - fooResourceType := &cadence.ResourceType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ + fooResourceType := cadence.NewResourceType( + common.ScriptLocation{}, + "Foo", + []cadence.Field{ { Identifier: "uuid", Type: cadence.UInt64Type, @@ -1644,7 +1656,8 @@ func TestRuntimeExportNestedResourceValueFromScript(t *testing.T) { Type: barResourceType, }, }, - } + nil, + ) script := ` access(all) resource Bar { @@ -1697,11 +1710,12 @@ func TestRuntimeExportEventValue(t *testing.T) { } ` - fooEventType := &cadence.EventType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Foo", - Fields: fooFields, - } + fooEventType := cadence.NewEventType( + common.ScriptLocation{}, + "Foo", + fooFields, + nil, + ) actual := exportEventFromScript(t, script) expected := cadence.NewEvent([]cadence.Value{ @@ -1724,10 +1738,10 @@ func TestRuntimeExportEventValue(t *testing.T) { } ` - fooEventType := &cadence.EventType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ + fooEventType := cadence.NewEventType( + common.ScriptLocation{}, + "Foo", + []cadence.Field{ { Identifier: "bar", Type: cadence.NewReferenceType( @@ -1736,7 +1750,8 @@ func TestRuntimeExportEventValue(t *testing.T) { ), }, }, - } + nil, + ) actual := exportEventFromScript(t, script) expected := cadence.NewEvent([]cadence.Value{ @@ -2022,11 +2037,12 @@ func TestRuntimeExportTypeValue(t *testing.T) { actual := exportValueFromScript(t, script) expected := cadence.TypeValue{ - StaticType: &cadence.StructType{ - QualifiedIdentifier: "S", - Location: common.ScriptLocation{}, - Fields: []cadence.Field{}, - }, + StaticType: cadence.NewStructType( + common.ScriptLocation{}, + "S", + []cadence.Field{}, + nil, + ), } assert.Equal(t, expected, actual) @@ -2113,11 +2129,12 @@ func TestRuntimeExportTypeValue(t *testing.T) { cadence.TypeValue{ StaticType: &cadence.IntersectionType{ Types: []cadence.Type{ - &cadence.StructInterfaceType{ - QualifiedIdentifier: "SI", - Location: TestLocation, - Fields: []cadence.Field{}, - }, + cadence.NewStructInterfaceType( + TestLocation, + "SI", + []cadence.Field{}, + nil, + ), }, }, }, @@ -2196,11 +2213,12 @@ func TestRuntimeExportCapabilityValue(t *testing.T) { expected := cadence.NewCapability( 3, cadence.Address{0x1}, - &cadence.StructType{ - QualifiedIdentifier: "S", - Location: TestLocation, - Fields: []cadence.Field{}, - }, + cadence.NewStructType( + TestLocation, + "S", + []cadence.Field{}, + nil, + ), ) assert.Equal(t, expected, actual) @@ -2227,10 +2245,10 @@ func TestRuntimeExportCompositeValueWithFunctionValueField(t *testing.T) { } ` - fooStructType := &cadence.StructType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ + fooStructType := cadence.NewStructType( + common.ScriptLocation{}, + "Foo", + []cadence.Field{ { Identifier: "answer", Type: cadence.IntType, @@ -2242,7 +2260,8 @@ func TestRuntimeExportCompositeValueWithFunctionValueField(t *testing.T) { }, }, }, - } + nil, + ) actual := exportValueFromScript(t, script) @@ -2329,11 +2348,12 @@ var fooResourceFields = []cadence.Field{ } func newFooResourceType() *cadence.ResourceType { - return &cadence.ResourceType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Foo", - Fields: fooResourceFields, - } + return cadence.NewResourceType( + common.ScriptLocation{}, + "Foo", + fooResourceFields, + nil, + ) } func TestRuntimeEnumValue(t *testing.T) { @@ -2343,17 +2363,18 @@ func TestRuntimeEnumValue(t *testing.T) { newEnumValue := func() cadence.Enum { return cadence.NewEnum([]cadence.Value{ cadence.NewInt(3), - }).WithType(&cadence.EnumType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Direction", - Fields: []cadence.Field{ + }).WithType(cadence.NewEnumType( + common.ScriptLocation{}, + "Direction", + cadence.IntType, + []cadence.Field{ { Identifier: sema.EnumRawValueFieldName, Type: cadence.IntType, }, }, - RawType: cadence.IntType, - }) + nil, + )) } t.Run("test export", func(t *testing.T) { @@ -2708,10 +2729,10 @@ func TestRuntimeComplexStructArgumentPassing(t *testing.T) { t.Parallel() // Complex struct value - structType := &cadence.StructType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ + structType := cadence.NewStructType( + common.ScriptLocation{}, + "Foo", + []cadence.Field{ { Identifier: "a", Type: &cadence.OptionalType{ @@ -2767,7 +2788,9 @@ func TestRuntimeComplexStructArgumentPassing(t *testing.T) { Type: cadence.HashableStructType, }, }, - } + nil, + ) + complexStructValue := cadence.NewStruct([]cadence.Value{ cadence.NewOptional( cadence.String("John"), @@ -2867,10 +2890,10 @@ func TestRuntimeComplexStructWithAnyStructFields(t *testing.T) { t.Parallel() // Complex struct value - structType := &cadence.StructType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ + structType := cadence.NewStructType( + common.ScriptLocation{}, + "Foo", + []cadence.Field{ { Identifier: "a", Type: &cadence.OptionalType{ @@ -2902,7 +2925,9 @@ func TestRuntimeComplexStructWithAnyStructFields(t *testing.T) { Type: cadence.AnyStructType, }, }, - } + nil, + ) + complexStructValue := cadence.NewStruct([]cadence.Value{ cadence.NewOptional(cadence.String("John")), cadence.NewDictionary([]cadence.KeyValuePair{ @@ -2974,10 +2999,10 @@ func TestRuntimeComplexStructWithHashableStructFields(t *testing.T) { t.Parallel() // Complex struct value - structType := &cadence.StructType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ + structType := cadence.NewStructType( + common.ScriptLocation{}, + "Foo", + []cadence.Field{ { Identifier: "a", Type: &cadence.OptionalType{ @@ -3009,7 +3034,9 @@ func TestRuntimeComplexStructWithHashableStructFields(t *testing.T) { Type: cadence.HashableStructType, }, }, - } + nil, + ) + complexStructValue := cadence.NewStruct([]cadence.Value{ cadence.NewOptional(cadence.String("John")), cadence.NewDictionary([]cadence.KeyValuePair{ @@ -3082,16 +3109,17 @@ func TestRuntimeMalformedArgumentPassing(t *testing.T) { // Struct with wrong field type newMalformedStructType1 := func() *cadence.StructType { - return &cadence.StructType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ + return cadence.NewStructType( + common.ScriptLocation{}, + "Foo", + []cadence.Field{ { Identifier: "a", Type: cadence.IntType, }, }, - } + nil, + ) } newMalformedStruct1 := func() cadence.Struct { @@ -3105,16 +3133,17 @@ func TestRuntimeMalformedArgumentPassing(t *testing.T) { newMalformedStruct2 := func() cadence.Struct { return cadence.NewStruct([]cadence.Value{ cadence.String("John"), - }).WithType(&cadence.StructType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ + }).WithType(cadence.NewStructType( + common.ScriptLocation{}, + "Foo", + []cadence.Field{ { Identifier: "nonExisting", Type: cadence.StringType, }, }, - }) + nil, + )) } // Struct with nested malformed array value @@ -3123,10 +3152,10 @@ func TestRuntimeMalformedArgumentPassing(t *testing.T) { cadence.NewArray([]cadence.Value{ newMalformedStruct1(), }), - }).WithType(&cadence.StructType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Bar", - Fields: []cadence.Field{ + }).WithType(cadence.NewStructType( + common.ScriptLocation{}, + "Bar", + []cadence.Field{ { Identifier: "a", Type: &cadence.VariableSizedArrayType{ @@ -3134,7 +3163,8 @@ func TestRuntimeMalformedArgumentPassing(t *testing.T) { }, }, }, - }) + nil, + )) } // Struct with nested malformed dictionary value @@ -3146,10 +3176,10 @@ func TestRuntimeMalformedArgumentPassing(t *testing.T) { Value: newMalformedStruct1(), }, }), - }).WithType(&cadence.StructType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Baz", - Fields: []cadence.Field{ + }).WithType(cadence.NewStructType( + common.ScriptLocation{}, + "Baz", + []cadence.Field{ { Identifier: "a", Type: &cadence.DictionaryType{ @@ -3158,7 +3188,8 @@ func TestRuntimeMalformedArgumentPassing(t *testing.T) { }, }, }, - }) + nil, + )) } // Struct with nested array with mismatching element type @@ -3167,10 +3198,10 @@ func TestRuntimeMalformedArgumentPassing(t *testing.T) { cadence.NewArray([]cadence.Value{ cadence.String("mismatching value"), }), - }).WithType(&cadence.StructType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Bar", - Fields: []cadence.Field{ + }).WithType(cadence.NewStructType( + common.ScriptLocation{}, + "Bar", + []cadence.Field{ { Identifier: "a", Type: &cadence.VariableSizedArrayType{ @@ -3178,7 +3209,8 @@ func TestRuntimeMalformedArgumentPassing(t *testing.T) { }, }, }, - }) + nil, + )) } type argumentPassingTest struct { @@ -4004,12 +4036,12 @@ func TestRuntimeTypeValueImport(t *testing.T) { t.Parallel() - typeValue := cadence.NewTypeValue(&cadence.StructType{ - QualifiedIdentifier: "S", - Location: TestLocation, - Fields: []cadence.Field{}, - Initializers: [][]cadence.Parameter{}, - }) + typeValue := cadence.NewTypeValue(cadence.NewStructType( + TestLocation, + "S", + []cadence.Field{}, + [][]cadence.Parameter{}, + )) script := ` access(all) fun main(s: Type) { @@ -4134,12 +4166,12 @@ func TestRuntimeCapabilityValueImport(t *testing.T) { t.Parallel() - borrowType := &cadence.StructType{ - QualifiedIdentifier: "S", - Location: TestLocation, - Fields: []cadence.Field{}, - Initializers: [][]cadence.Parameter{}, - } + borrowType := cadence.NewStructType( + TestLocation, + "S", + []cadence.Field{}, + [][]cadence.Parameter{}, + ) capabilityValue := cadence.NewCapability( 42, @@ -4882,16 +4914,17 @@ func TestRuntimeImportExportComplex(t *testing.T) { ), ) - externalCompositeType := &cadence.StructType{ - Location: TestLocation, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ + externalCompositeType := cadence.NewStructType( + TestLocation, + "Foo", + []cadence.Field{ { Identifier: "dictionary", Type: externalDictionaryType, }, }, - } + nil, + ) internalCompositeValueFields := []interpreter.CompositeField{ { @@ -4988,16 +5021,17 @@ func TestRuntimeStaticTypeAvailability(t *testing.T) { cadence.String("foo"), cadence.String("bar"), }), - }).WithType(&cadence.StructType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ + }).WithType(cadence.NewStructType( + common.ScriptLocation{}, + "Foo", + []cadence.Field{ { Identifier: "a", Type: cadence.AnyStructType, }, }, - }) + nil, + )) _, err := executeTestScript(t, script, structValue) require.NoError(t, err) @@ -5024,16 +5058,17 @@ func TestRuntimeStaticTypeAvailability(t *testing.T) { Value: cadence.String("bar"), }, }), - }).WithType(&cadence.StructType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ + }).WithType(cadence.NewStructType( + common.ScriptLocation{}, + "Foo", + []cadence.Field{ { Identifier: "a", Type: cadence.AnyStructType, }, }, - }) + nil, + )) _, err := executeTestScript(t, script, structValue) require.NoError(t, err) @@ -5297,15 +5332,17 @@ func TestRuntimeDeploymentResultTypeImportExport(t *testing.T) { rt := NewTestInterpreterRuntime() - typeValue := cadence.NewTypeValue(&cadence.StructType{ - QualifiedIdentifier: "DeploymentResult", - Fields: []cadence.Field{ + typeValue := cadence.NewTypeValue(cadence.NewStructType( + nil, + "DeploymentResult", + []cadence.Field{ { Type: cadence.NewOptionalType(cadence.DeployedContractType), Identifier: "deployedContract", }, }, - }) + nil, + )) encodedArg, err := json.Encode(typeValue) require.NoError(t, err) @@ -5356,15 +5393,17 @@ func TestRuntimeDeploymentResultTypeImportExport(t *testing.T) { require.NoError(t, err) assert.Equal(t, - cadence.NewTypeValue(&cadence.StructType{ - QualifiedIdentifier: "DeploymentResult", - Fields: []cadence.Field{ + cadence.NewTypeValue(cadence.NewStructType( + nil, + "DeploymentResult", + []cadence.Field{ { Type: cadence.NewOptionalType(cadence.DeployedContractType), Identifier: "deployedContract", }, }, - }), + nil, + )), result, ) }) diff --git a/runtime/crypto_test.go b/runtime/crypto_test.go index ce98dabd60..6cf6e1cec7 100644 --- a/runtime/crypto_test.go +++ b/runtime/crypto_test.go @@ -361,16 +361,18 @@ func TestRuntimeSignatureAlgorithmImport(t *testing.T) { Arguments: encodeArgs([]cadence.Value{ cadence.NewEnum([]cadence.Value{ cadence.UInt8(algo.RawValue()), - }).WithType(&cadence.EnumType{ - QualifiedIdentifier: "SignatureAlgorithm", - RawType: cadence.UInt8Type, - Fields: []cadence.Field{ + }).WithType(cadence.NewEnumType( + nil, + "SignatureAlgorithm", + cadence.UInt8Type, + []cadence.Field{ { Identifier: "rawValue", Type: cadence.UInt8Type, }, }, - }), + nil, + )), }), }, Context{ @@ -440,16 +442,18 @@ func TestRuntimeHashAlgorithmImport(t *testing.T) { Arguments: encodeArgs([]cadence.Value{ cadence.NewEnum([]cadence.Value{ cadence.UInt8(algo.RawValue()), - }).WithType(&cadence.EnumType{ - QualifiedIdentifier: "HashAlgorithm", - RawType: cadence.UInt8Type, - Fields: []cadence.Field{ + }).WithType(cadence.NewEnumType( + nil, + "HashAlgorithm", + cadence.UInt8Type, + []cadence.Field{ { Identifier: "rawValue", Type: cadence.UInt8Type, }, }, - }), + nil, + )), }), }, Context{ @@ -799,7 +803,7 @@ func TestRuntimeTraversingMerkleProof(t *testing.T) { return hex.DecodeString("b6979620706f8c652cfb6bf6e923f5156eadd5abaf4022a0b19d52ada089475f") } - return nil, errors.New("Unknown input to the hash method") + return nil, errors.New("unknown input to the hash method") }, OnProgramLog: func(message string) { logMessages = append(logMessages, message) diff --git a/runtime/program_params_validation_test.go b/runtime/program_params_validation_test.go index 640bfd3dc6..ba746b9aa2 100644 --- a/runtime/program_params_validation_test.go +++ b/runtime/program_params_validation_test.go @@ -59,19 +59,22 @@ func TestRuntimeScriptParameterTypeValidation(t *testing.T) { newFooStruct := func() cadence.Struct { return cadence.NewStruct([]cadence.Value{}). - WithType(&cadence.StructType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{}, - }) + WithType(cadence.NewStructType( + common.ScriptLocation{}, + "Foo", + []cadence.Field{}, + nil, + )) } newPublicAccountKeys := func() cadence.Struct { return cadence.NewStruct([]cadence.Value{}). - WithType(&cadence.StructType{ - QualifiedIdentifier: "Account.Keys", - Fields: []cadence.Field{}, - }) + WithType(cadence.NewStructType( + nil, + "Account.Keys", + []cadence.Field{}, + nil, + )) } executeScript := func(t *testing.T, script string, arg cadence.Value) (err error) { @@ -666,22 +669,25 @@ func TestRuntimeTransactionParameterTypeValidation(t *testing.T) { newFooStruct := func() cadence.Struct { return cadence.NewStruct([]cadence.Value{}). - WithType(&cadence.StructType{ - Location: common.AddressLocation{ + WithType(cadence.NewStructType( + common.AddressLocation{ Address: common.MustBytesToAddress([]byte{0x1}), Name: "C", }, - QualifiedIdentifier: "C.Foo", - Fields: []cadence.Field{}, - }) + "C.Foo", + []cadence.Field{}, + nil, + )) } newPublicAccountKeys := func() cadence.Struct { return cadence.NewStruct([]cadence.Value{}). - WithType(&cadence.StructType{ - QualifiedIdentifier: "Account.Keys", - Fields: []cadence.Field{}, - }) + WithType(cadence.NewStructType( + nil, + "Account.Keys", + []cadence.Field{}, + nil, + )) } executeTransaction := func( @@ -1293,19 +1299,20 @@ func TestRuntimeTransactionParameterTypeValidation(t *testing.T) { arg := cadence.NewStruct([]cadence.Value{ capability, - }).WithType(&cadence.StructType{ - Location: common.AddressLocation{ + }).WithType(cadence.NewStructType( + common.AddressLocation{ Address: address, Name: "C", }, - QualifiedIdentifier: "C.S", - Fields: []cadence.Field{ + "C.S", + []cadence.Field{ { Identifier: "cap", Type: &cadence.CapabilityType{}, }, }, - }) + nil, + )) err := executeTransaction(t, script, contracts, arg) expectRuntimeError(t, err, &ArgumentNotImportableError{}) diff --git a/runtime/runtime_test.go b/runtime/runtime_test.go index aaba3832c3..c115cfaa7d 100644 --- a/runtime/runtime_test.go +++ b/runtime/runtime_test.go @@ -640,19 +640,20 @@ func TestRuntimeTransactionWithArguments(t *testing.T) { args: encodeArgs([]cadence.Value{ cadence. NewStruct([]cadence.Value{cadence.String("bar")}). - WithType(&cadence.StructType{ - Location: common.AddressLocation{ + WithType(cadence.NewStructType( + common.AddressLocation{ Address: common.MustBytesToAddress([]byte{0x1}), Name: "C", }, - QualifiedIdentifier: "C.Foo", - Fields: []cadence.Field{ + "C.Foo", + []cadence.Field{ { Identifier: "y", Type: cadence.StringType, }, }, - }), + nil, + )), }), expectedLogs: []string{`"bar"`}, }, @@ -688,19 +689,20 @@ func TestRuntimeTransactionWithArguments(t *testing.T) { cadence.NewArray([]cadence.Value{ cadence. NewStruct([]cadence.Value{cadence.String("bar")}). - WithType(&cadence.StructType{ - Location: common.AddressLocation{ + WithType(cadence.NewStructType( + common.AddressLocation{ Address: common.MustBytesToAddress([]byte{0x1}), Name: "C", }, - QualifiedIdentifier: "C.Foo", - Fields: []cadence.Field{ + "C.Foo", + []cadence.Field{ { Identifier: "y", Type: cadence.StringType, }, }, - }), + nil, + )), }), }), expectedLogs: []string{`"bar"`}, @@ -1017,16 +1019,17 @@ func TestRuntimeScriptArguments(t *testing.T) { args: encodeArgs([]cadence.Value{ cadence. NewStruct([]cadence.Value{cadence.String("bar")}). - WithType(&cadence.StructType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ + WithType(cadence.NewStructType( + common.ScriptLocation{}, + "Foo", + []cadence.Field{ { Identifier: "y", Type: cadence.StringType, }, }, - }), + nil, + )), }), expectedLogs: []string{`"bar"`}, }, @@ -1050,16 +1053,17 @@ func TestRuntimeScriptArguments(t *testing.T) { cadence.NewArray([]cadence.Value{ cadence. NewStruct([]cadence.Value{cadence.String("bar")}). - WithType(&cadence.StructType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Foo", - Fields: []cadence.Field{ + WithType(cadence.NewStructType( + common.ScriptLocation{}, + "Foo", + []cadence.Field{ { Identifier: "y", Type: cadence.StringType, }, }, - }), + nil, + )), }), }), expectedLogs: []string{`"bar"`}, diff --git a/types.go b/types.go index ca13683566..c3cee3c263 100644 --- a/types.go +++ b/types.go @@ -426,44 +426,71 @@ func NewField(identifier string, typ Type) Field { } } -// SearchFieldByName searches for the field with the given name in the composite type, -// and returns the value of the field, or nil if the field is not found. +// SearchCompositeFieldTypeByName searches for the field with the given name in the composite type, +// and returns the type of the field, or nil if the field is not found. // // WARNING: This function performs a linear search, so is not efficient for accessing multiple fields. -// Prefer using FieldsMappedByName if you need to access multiple fields. -func SearchFieldByName(v Composite, fieldName string) Value { - fieldValues := v.getFieldValues() - fields := v.GetFields() +// Prefer using CompositeFieldTypesMappedByName if you need to access multiple fields. +func SearchCompositeFieldTypeByName(compositeType CompositeType, fieldName string) Type { + fields := compositeType.compositeFields() - if fieldValues == nil || fields == nil { + if fields == nil { return nil } - for i, field := range v.GetFields() { + for _, field := range fields { if field.Identifier == fieldName { - return fieldValues[i] + return field.Type } } return nil } -func FieldsMappedByName(v Composite) map[string]Value { - fieldValues := v.getFieldValues() - fields := v.GetFields() +func CompositeFieldTypesMappedByName(compositeType CompositeType) map[string]Type { + fields := compositeType.compositeFields() - if fieldValues == nil || fields == nil { + if fields == nil { return nil } - fieldsMap := make(map[string]Value, len(fields)) - for i, fieldValue := range fieldValues { - var fieldName string - if i < len(fields) { - fieldName = fields[i].Identifier - } else if attachment, ok := fieldValue.(Attachment); ok { - fieldName = interpreter.AttachmentMemberName(attachment.Type().ID()) + fieldsMap := make(map[string]Type, len(fields)) + for _, field := range fields { + fieldsMap[field.Identifier] = field.Type + } + + return fieldsMap +} + +// SearchInterfaceFieldTypeByName searches for the field with the given name in the interface type, +// and returns the type of the field, or nil if the field is not found. +// +// WARNING: This function performs a linear search, so is not efficient for accessing multiple fields. +// Prefer using InterfaceFieldTypesMappedByName if you need to access multiple fields. +func SearchInterfaceFieldTypeByName(interfaceType InterfaceType, fieldName string) Type { + fields := interfaceType.interfaceFields() + + if fields == nil { + return nil + } + + for _, field := range fields { + if field.Identifier == fieldName { + return field.Type } - fieldsMap[fieldName] = fieldValue + } + return nil +} + +func InterfaceFieldTypesMappedByName(interfaceType InterfaceType) map[string]Type { + fields := interfaceType.interfaceFields() + + if fields == nil { + return nil + } + + fieldsMap := make(map[string]Type, len(fields)) + for _, field := range fields { + fieldsMap[field.Identifier] = field.Type } return fieldsMap @@ -699,12 +726,28 @@ func NewTypeParameter( type CompositeType interface { Type + isCompositeType() + compositeFields() []Field + setCompositeFields([]Field) + CompositeTypeLocation() common.Location CompositeTypeQualifiedIdentifier() string - CompositeFields() []Field - SetCompositeFields([]Field) CompositeInitializers() [][]Parameter + SearchFieldByName(fieldName string) Type + FieldsMappedByName() map[string]Type +} + +// linked in by packages that need access to CompositeType.setCompositeFields, +// e.g. JSON and CCF codecs +func setCompositeTypeFields(compositeType CompositeType, fields []Field) { //nolint:unused + compositeType.setCompositeFields(fields) +} + +// linked in by packages that need access to CompositeType.compositeFields, +// e.g. JSON and CCF codecs +func getCompositeTypeFields(compositeType CompositeType) []Field { //nolint:unused + return compositeType.compositeFields() } // StructType @@ -712,7 +755,7 @@ type CompositeType interface { type StructType struct { Location common.Location QualifiedIdentifier string - Fields []Field + fields []Field Initializers [][]Parameter } @@ -725,7 +768,7 @@ func NewStructType( return &StructType{ Location: location, QualifiedIdentifier: qualifiedIdentifier, - Fields: fields, + fields: fields, Initializers: initializers, } } @@ -757,12 +800,12 @@ func (t *StructType) CompositeTypeQualifiedIdentifier() string { return t.QualifiedIdentifier } -func (t *StructType) CompositeFields() []Field { - return t.Fields +func (t *StructType) compositeFields() []Field { + return t.fields } -func (t *StructType) SetCompositeFields(fields []Field) { - t.Fields = fields +func (t *StructType) setCompositeFields(fields []Field) { + t.fields = fields } func (t *StructType) CompositeInitializers() [][]Parameter { @@ -779,12 +822,20 @@ func (t *StructType) Equal(other Type) bool { t.QualifiedIdentifier == otherType.QualifiedIdentifier } +func (t *StructType) SearchFieldByName(fieldName string) Type { + return SearchCompositeFieldTypeByName(t, fieldName) +} + +func (t *StructType) FieldsMappedByName() map[string]Type { + return CompositeFieldTypesMappedByName(t) +} + // ResourceType type ResourceType struct { Location common.Location QualifiedIdentifier string - Fields []Field + fields []Field Initializers [][]Parameter } @@ -797,7 +848,7 @@ func NewResourceType( return &ResourceType{ Location: location, QualifiedIdentifier: qualifiedIdentifier, - Fields: fields, + fields: fields, Initializers: initializers, } } @@ -829,12 +880,12 @@ func (t *ResourceType) CompositeTypeQualifiedIdentifier() string { return t.QualifiedIdentifier } -func (t *ResourceType) CompositeFields() []Field { - return t.Fields +func (t *ResourceType) compositeFields() []Field { + return t.fields } -func (t *ResourceType) SetCompositeFields(fields []Field) { - t.Fields = fields +func (t *ResourceType) setCompositeFields(fields []Field) { + t.fields = fields } func (t *ResourceType) CompositeInitializers() [][]Parameter { @@ -851,20 +902,28 @@ func (t *ResourceType) Equal(other Type) bool { t.QualifiedIdentifier == otherType.QualifiedIdentifier } +func (t *ResourceType) SearchFieldByName(fieldName string) Type { + return SearchCompositeFieldTypeByName(t, fieldName) +} + +func (t *ResourceType) FieldsMappedByName() map[string]Type { + return CompositeFieldTypesMappedByName(t) +} + // AttachmentType type AttachmentType struct { Location common.Location BaseType Type QualifiedIdentifier string - Fields []Field + fields []Field Initializers [][]Parameter } func NewAttachmentType( location common.Location, - baseType Type, qualifiedIdentifier string, + baseType Type, fields []Field, initializers [][]Parameter, ) *AttachmentType { @@ -872,7 +931,7 @@ func NewAttachmentType( Location: location, BaseType: baseType, QualifiedIdentifier: qualifiedIdentifier, - Fields: fields, + fields: fields, Initializers: initializers, } } @@ -880,16 +939,16 @@ func NewAttachmentType( func NewMeteredAttachmentType( gauge common.MemoryGauge, location common.Location, - baseType Type, qualifiedIdentifier string, + baseType Type, fields []Field, initializers [][]Parameter, ) *AttachmentType { common.UseMemory(gauge, common.CadenceAttachmentTypeMemoryUsage) return NewAttachmentType( location, - baseType, qualifiedIdentifier, + baseType, fields, initializers, ) @@ -911,12 +970,12 @@ func (t *AttachmentType) CompositeTypeQualifiedIdentifier() string { return t.QualifiedIdentifier } -func (t *AttachmentType) CompositeFields() []Field { - return t.Fields +func (t *AttachmentType) compositeFields() []Field { + return t.fields } -func (t *AttachmentType) SetCompositeFields(fields []Field) { - t.Fields = fields +func (t *AttachmentType) setCompositeFields(fields []Field) { + t.fields = fields } func (t *AttachmentType) CompositeInitializers() [][]Parameter { @@ -937,12 +996,20 @@ func (t *AttachmentType) Equal(other Type) bool { t.QualifiedIdentifier == otherType.QualifiedIdentifier } +func (t *AttachmentType) SearchFieldByName(fieldName string) Type { + return SearchCompositeFieldTypeByName(t, fieldName) +} + +func (t *AttachmentType) FieldsMappedByName() map[string]Type { + return CompositeFieldTypesMappedByName(t) +} + // EventType type EventType struct { Location common.Location QualifiedIdentifier string - Fields []Field + fields []Field Initializer []Parameter } @@ -955,7 +1022,7 @@ func NewEventType( return &EventType{ Location: location, QualifiedIdentifier: qualifiedIdentifier, - Fields: fields, + fields: fields, Initializer: initializer, } } @@ -987,12 +1054,12 @@ func (t *EventType) CompositeTypeQualifiedIdentifier() string { return t.QualifiedIdentifier } -func (t *EventType) CompositeFields() []Field { - return t.Fields +func (t *EventType) compositeFields() []Field { + return t.fields } -func (t *EventType) SetCompositeFields(fields []Field) { - t.Fields = fields +func (t *EventType) setCompositeFields(fields []Field) { + t.fields = fields } func (t *EventType) CompositeInitializers() [][]Parameter { @@ -1009,12 +1076,20 @@ func (t *EventType) Equal(other Type) bool { t.QualifiedIdentifier == otherType.QualifiedIdentifier } +func (t *EventType) SearchFieldByName(fieldName string) Type { + return SearchCompositeFieldTypeByName(t, fieldName) +} + +func (t *EventType) FieldsMappedByName() map[string]Type { + return CompositeFieldTypesMappedByName(t) +} + // ContractType type ContractType struct { Location common.Location QualifiedIdentifier string - Fields []Field + fields []Field Initializers [][]Parameter } @@ -1027,7 +1102,7 @@ func NewContractType( return &ContractType{ Location: location, QualifiedIdentifier: qualifiedIdentifier, - Fields: fields, + fields: fields, Initializers: initializers, } } @@ -1059,12 +1134,12 @@ func (t *ContractType) CompositeTypeQualifiedIdentifier() string { return t.QualifiedIdentifier } -func (t *ContractType) CompositeFields() []Field { - return t.Fields +func (t *ContractType) compositeFields() []Field { + return t.fields } -func (t *ContractType) SetCompositeFields(fields []Field) { - t.Fields = fields +func (t *ContractType) setCompositeFields(fields []Field) { + t.fields = fields } func (t *ContractType) CompositeInitializers() [][]Parameter { @@ -1081,24 +1156,46 @@ func (t *ContractType) Equal(other Type) bool { t.QualifiedIdentifier == otherType.QualifiedIdentifier } +func (t *ContractType) SearchFieldByName(fieldName string) Type { + return SearchCompositeFieldTypeByName(t, fieldName) +} + +func (t *ContractType) FieldsMappedByName() map[string]Type { + return CompositeFieldTypesMappedByName(t) +} + // InterfaceType type InterfaceType interface { Type + isInterfaceType() + interfaceFields() []Field + setInterfaceFields(fields []Field) + InterfaceTypeLocation() common.Location InterfaceTypeQualifiedIdentifier() string - InterfaceFields() []Field - SetInterfaceFields(fields []Field) InterfaceInitializers() [][]Parameter } +// linked in by packages that need access to InterfaceType.interfaceFields, +// e.g. JSON and CCF codecs +func getInterfaceTypeFields(interfaceType InterfaceType) []Field { //nolint:unused + return interfaceType.interfaceFields() +} + +// linked in by packages that need access to InterfaceType.setInterfaceFields, +// e.g. JSON and CCF codecs +func setInterfaceTypeFields(interfaceType InterfaceType, fields []Field) { //nolint:unused + interfaceType.setInterfaceFields(fields) +} + // StructInterfaceType type StructInterfaceType struct { Location common.Location QualifiedIdentifier string - Fields []Field + fields []Field Initializers [][]Parameter } @@ -1111,7 +1208,7 @@ func NewStructInterfaceType( return &StructInterfaceType{ Location: location, QualifiedIdentifier: qualifiedIdentifier, - Fields: fields, + fields: fields, Initializers: initializers, } } @@ -1143,12 +1240,12 @@ func (t *StructInterfaceType) InterfaceTypeQualifiedIdentifier() string { return t.QualifiedIdentifier } -func (t *StructInterfaceType) InterfaceFields() []Field { - return t.Fields +func (t *StructInterfaceType) interfaceFields() []Field { + return t.fields } -func (t *StructInterfaceType) SetInterfaceFields(fields []Field) { - t.Fields = fields +func (t *StructInterfaceType) setInterfaceFields(fields []Field) { + t.fields = fields } func (t *StructInterfaceType) InterfaceInitializers() [][]Parameter { @@ -1170,7 +1267,7 @@ func (t *StructInterfaceType) Equal(other Type) bool { type ResourceInterfaceType struct { Location common.Location QualifiedIdentifier string - Fields []Field + fields []Field Initializers [][]Parameter } @@ -1183,7 +1280,7 @@ func NewResourceInterfaceType( return &ResourceInterfaceType{ Location: location, QualifiedIdentifier: qualifiedIdentifier, - Fields: fields, + fields: fields, Initializers: initializers, } } @@ -1215,12 +1312,12 @@ func (t *ResourceInterfaceType) InterfaceTypeQualifiedIdentifier() string { return t.QualifiedIdentifier } -func (t *ResourceInterfaceType) InterfaceFields() []Field { - return t.Fields +func (t *ResourceInterfaceType) interfaceFields() []Field { + return t.fields } -func (t *ResourceInterfaceType) SetInterfaceFields(fields []Field) { - t.Fields = fields +func (t *ResourceInterfaceType) setInterfaceFields(fields []Field) { + t.fields = fields } func (t *ResourceInterfaceType) InterfaceInitializers() [][]Parameter { @@ -1242,7 +1339,7 @@ func (t *ResourceInterfaceType) Equal(other Type) bool { type ContractInterfaceType struct { Location common.Location QualifiedIdentifier string - Fields []Field + fields []Field Initializers [][]Parameter } @@ -1255,7 +1352,7 @@ func NewContractInterfaceType( return &ContractInterfaceType{ Location: location, QualifiedIdentifier: qualifiedIdentifier, - Fields: fields, + fields: fields, Initializers: initializers, } } @@ -1287,12 +1384,12 @@ func (t *ContractInterfaceType) InterfaceTypeQualifiedIdentifier() string { return t.QualifiedIdentifier } -func (t *ContractInterfaceType) InterfaceFields() []Field { - return t.Fields +func (t *ContractInterfaceType) interfaceFields() []Field { + return t.fields } -func (t *ContractInterfaceType) SetInterfaceFields(fields []Field) { - t.Fields = fields +func (t *ContractInterfaceType) setInterfaceFields(fields []Field) { + t.fields = fields } func (t *ContractInterfaceType) InterfaceInitializers() [][]Parameter { @@ -1939,7 +2036,7 @@ type EnumType struct { Location common.Location QualifiedIdentifier string RawType Type - Fields []Field + fields []Field Initializers [][]Parameter } @@ -1954,7 +2051,7 @@ func NewEnumType( Location: location, QualifiedIdentifier: qualifiedIdentifier, RawType: rawType, - Fields: fields, + fields: fields, Initializers: initializers, } } @@ -1987,12 +2084,12 @@ func (t *EnumType) CompositeTypeQualifiedIdentifier() string { return t.QualifiedIdentifier } -func (t *EnumType) CompositeFields() []Field { - return t.Fields +func (t *EnumType) compositeFields() []Field { + return t.fields } -func (t *EnumType) SetCompositeFields(fields []Field) { - t.Fields = fields +func (t *EnumType) setCompositeFields(fields []Field) { + t.fields = fields } func (t *EnumType) CompositeInitializers() [][]Parameter { @@ -2008,3 +2105,11 @@ func (t *EnumType) Equal(other Type) bool { return t.Location == otherType.Location && t.QualifiedIdentifier == otherType.QualifiedIdentifier } + +func (t *EnumType) SearchFieldByName(fieldName string) Type { + return SearchCompositeFieldTypeByName(t, fieldName) +} + +func (t *EnumType) FieldsMappedByName() map[string]Type { + return CompositeFieldTypesMappedByName(t) +} diff --git a/types_test.go b/types_test.go index 8b1e2f5934..f13bb96b7a 100644 --- a/types_test.go +++ b/types_test.go @@ -2272,10 +2272,10 @@ func TestDecodeFields(t *testing.T) { }, }, }, - ).WithType(&EventType{ - Location: utils.TestLocation, - QualifiedIdentifier: "SimpleEvent", - Fields: []Field{ + ).WithType(NewEventType( + utils.TestLocation, + "SimpleEvent", + []Field{ { Identifier: "intField", Type: IntType, @@ -2369,7 +2369,8 @@ func TestDecodeFields(t *testing.T) { ), }, }, - }) + nil, + )) type eventStruct struct { Int Int `cadence:"intField"` @@ -2491,7 +2492,7 @@ func TestDecodeFields(t *testing.T) { Description: "should err when mapping to invalid type", }, {Value: &struct { - a Int `cadence:"intField"` // nolint: unused + a Int `cadence:"intField"` }{}, ExpectedErr: "cannot set field a", Description: "should err when mapping to private field", diff --git a/values.go b/values.go index f3e20a371d..085507b326 100644 --- a/values.go +++ b/values.go @@ -1521,16 +1521,66 @@ func NewMeteredKeyValuePair(gauge common.MemoryGauge, key, value Value) KeyValue type Composite interface { Value - GetFields() []Field + + isComposite() + getFields() []Field getFieldValues() []Value + + SearchFieldByName(fieldName string) Value + FieldsMappedByName() map[string]Value } -// linked in by packages that need access to getFieldValues, +// linked in by packages that need access to Composite.getFieldValues, // e.g. JSON and CCF codecs -func getFieldValues(composite Composite) []Value { //nolint:unused +func getCompositeFieldValues(composite Composite) []Value { //nolint:unused return composite.getFieldValues() } +// SearchFieldByName searches for the field with the given name in the composite type, +// and returns the value of the field, or nil if the field is not found. +// +// WARNING: This function performs a linear search, so is not efficient for accessing multiple fields. +// Prefer using FieldsMappedByName if you need to access multiple fields. +func SearchFieldByName(v Composite, fieldName string) Value { + fieldValues := v.getFieldValues() + fields := v.getFields() + + if fieldValues == nil || fields == nil { + return nil + } + + for i, field := range fields { + if field.Identifier == fieldName { + return fieldValues[i] + } + } + return nil +} + +func FieldsMappedByName(v Composite) map[string]Value { + fieldValues := v.getFieldValues() + fields := v.getFields() + + if fieldValues == nil || fields == nil { + return nil + } + + fieldsMap := make(map[string]Value, len(fields)) + for i, fieldValue := range fieldValues { + var fieldName string + if i < len(fields) { + fieldName = fields[i].Identifier + } else if attachment, ok := fieldValue.(Attachment); ok { + fieldName = interpreter.AttachmentMemberName(attachment.Type().ID()) + } else { + panic(errors.NewUnreachableError()) + } + fieldsMap[fieldName] = fieldValue + } + + return fieldsMap +} + // Struct type Struct struct { @@ -1563,6 +1613,8 @@ func NewMeteredStruct( func (Struct) isValue() {} +func (Struct) isComposite() {} + func (v Struct) Type() Type { if v.StructType == nil { // Return nil Type instead of Type referencing nil *StructType, @@ -1584,23 +1636,36 @@ func (v Struct) WithType(typ *StructType) Struct { func (v Struct) String() string { return formatComposite( v.StructType.ID(), - v.StructType.Fields, + v.StructType.fields, v.fields, ) } -func (v Struct) GetFields() []Field { +func (v Struct) getFields() []Field { if v.StructType == nil { return nil } - return v.StructType.Fields + return v.StructType.fields } func (v Struct) getFieldValues() []Value { return v.fields } +// SearchFieldByName searches for the field with the given name in the struct, +// and returns the value of the field, or nil if the field is not found. +// +// WARNING: This function performs a linear search, so is not efficient for accessing multiple fields. +// Prefer using FieldsMappedByName if you need to access multiple fields. +func (v Struct) SearchFieldByName(fieldName string) Value { + return SearchFieldByName(v, fieldName) +} + +func (v Struct) FieldsMappedByName() map[string]Value { + return FieldsMappedByName(v) +} + func formatComposite(typeID string, fields []Field, values []Value) string { preparedFields := make([]struct { Name string @@ -1653,6 +1718,8 @@ func NewMeteredResource( func (Resource) isValue() {} +func (Resource) isComposite() {} + func (v Resource) Type() Type { if v.ResourceType == nil { // Return nil Type instead of Type referencing nil *ResourceType, @@ -1674,23 +1741,36 @@ func (v Resource) WithType(typ *ResourceType) Resource { func (v Resource) String() string { return formatComposite( v.ResourceType.ID(), - v.ResourceType.Fields, + v.ResourceType.fields, v.fields, ) } -func (v Resource) GetFields() []Field { +func (v Resource) getFields() []Field { if v.ResourceType == nil { return nil } - return v.ResourceType.Fields + return v.ResourceType.fields } func (v Resource) getFieldValues() []Value { return v.fields } +// SearchFieldByName searches for the field with the given name in the resource, +// and returns the value of the field, or nil if the field is not found. +// +// WARNING: This function performs a linear search, so is not efficient for accessing multiple fields. +// Prefer using FieldsMappedByName if you need to access multiple fields. +func (v Resource) SearchFieldByName(fieldName string) Value { + return SearchFieldByName(v, fieldName) +} + +func (v Resource) FieldsMappedByName() map[string]Value { + return FieldsMappedByName(v) +} + // Attachment type Attachment struct { @@ -1722,6 +1802,8 @@ func NewMeteredAttachment( func (Attachment) isValue() {} +func (Attachment) isComposite() {} + func (v Attachment) Type() Type { if v.AttachmentType == nil { // Return nil Type instead of Type referencing nil *AttachmentType, @@ -1743,23 +1825,36 @@ func (v Attachment) WithType(typ *AttachmentType) Attachment { func (v Attachment) String() string { return formatComposite( v.AttachmentType.ID(), - v.AttachmentType.Fields, + v.AttachmentType.fields, v.fields, ) } -func (v Attachment) GetFields() []Field { +func (v Attachment) getFields() []Field { if v.AttachmentType == nil { return nil } - return v.AttachmentType.Fields + return v.AttachmentType.fields } func (v Attachment) getFieldValues() []Value { return v.fields } +// SearchFieldByName searches for the field with the given name in the attachment, +// and returns the value of the field, or nil if the field is not found. +// +// WARNING: This function performs a linear search, so is not efficient for accessing multiple fields. +// Prefer using FieldsMappedByName if you need to access multiple fields. +func (v Attachment) SearchFieldByName(fieldName string) Value { + return SearchFieldByName(v, fieldName) +} + +func (v Attachment) FieldsMappedByName() map[string]Value { + return FieldsMappedByName(v) +} + // Event type Event struct { @@ -1791,6 +1886,8 @@ func NewMeteredEvent( func (Event) isValue() {} +func (Event) isComposite() {} + func (v Event) Type() Type { if v.EventType == nil { // Return nil Type instead of Type referencing nil *EventType, @@ -1812,23 +1909,36 @@ func (v Event) WithType(typ *EventType) Event { func (v Event) String() string { return formatComposite( v.EventType.ID(), - v.EventType.Fields, + v.EventType.fields, v.fields, ) } -func (v Event) GetFields() []Field { +func (v Event) getFields() []Field { if v.EventType == nil { return nil } - return v.EventType.Fields + return v.EventType.fields } func (v Event) getFieldValues() []Value { return v.fields } +// SearchFieldByName searches for the field with the given name in the event, +// and returns the value of the field, or nil if the field is not found. +// +// WARNING: This function performs a linear search, so is not efficient for accessing multiple fields. +// Prefer using FieldsMappedByName if you need to access multiple fields. +func (v Event) SearchFieldByName(fieldName string) Value { + return SearchFieldByName(v, fieldName) +} + +func (v Event) FieldsMappedByName() map[string]Value { + return FieldsMappedByName(v) +} + // Contract type Contract struct { @@ -1860,6 +1970,8 @@ func NewMeteredContract( func (Contract) isValue() {} +func (Contract) isComposite() {} + func (v Contract) Type() Type { if v.ContractType == nil { // Return nil Type instead of Type referencing nil *ContractType, @@ -1881,23 +1993,36 @@ func (v Contract) WithType(typ *ContractType) Contract { func (v Contract) String() string { return formatComposite( v.ContractType.ID(), - v.ContractType.Fields, + v.ContractType.fields, v.fields, ) } -func (v Contract) GetFields() []Field { +func (v Contract) getFields() []Field { if v.ContractType == nil { return nil } - return v.ContractType.Fields + return v.ContractType.fields } func (v Contract) getFieldValues() []Value { return v.fields } +// SearchFieldByName searches for the field with the given name in the contract, +// and returns the value of the field, or nil if the field is not found. +// +// WARNING: This function performs a linear search, so is not efficient for accessing multiple fields. +// Prefer using FieldsMappedByName if you need to access multiple fields. +func (v Contract) SearchFieldByName(fieldName string) Value { + return SearchFieldByName(v, fieldName) +} + +func (v Contract) FieldsMappedByName() map[string]Value { + return FieldsMappedByName(v) +} + // InclusiveRange type InclusiveRange struct { @@ -2193,6 +2318,8 @@ func NewMeteredEnum( func (Enum) isValue() {} +func (Enum) isComposite() {} + func (v Enum) Type() Type { if v.EnumType == nil { // Return nil Type instead of Type referencing nil *EnumType, @@ -2214,23 +2341,36 @@ func (v Enum) WithType(typ *EnumType) Enum { func (v Enum) String() string { return formatComposite( v.EnumType.ID(), - v.EnumType.Fields, + v.EnumType.fields, v.fields, ) } -func (v Enum) GetFields() []Field { +func (v Enum) getFields() []Field { if v.EnumType == nil { return nil } - return v.EnumType.Fields + return v.EnumType.fields } func (v Enum) getFieldValues() []Value { return v.fields } +// SearchFieldByName searches for the field with the given name in the enum, +// and returns the value of the field, or nil if the field is not found. +// +// WARNING: This function performs a linear search, so is not efficient for accessing multiple fields. +// Prefer using FieldsMappedByName if you need to access multiple fields. +func (v Enum) SearchFieldByName(fieldName string) Value { + return SearchFieldByName(v, fieldName) +} + +func (v Enum) FieldsMappedByName() map[string]Value { + return FieldsMappedByName(v) +} + // Function type Function struct { FunctionType *FunctionType diff --git a/values_test.go b/values_test.go index e3f00d356b..35437dd51c 100644 --- a/values_test.go +++ b/values_test.go @@ -241,16 +241,17 @@ func newValueTestCases() map[string]valueTestCase { }, "struct": { value: NewStruct([]Value{String("bar")}), - exampleType: &StructType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooStruct", - Fields: []Field{ + exampleType: NewStructType( + utils.TestLocation, + "FooStruct", + []Field{ { Identifier: "y", Type: StringType, }, }, - }, + nil, + ), withType: func(value Value, ty Type) Value { return value.(Struct).WithType(ty.(*StructType)) }, @@ -258,16 +259,17 @@ func newValueTestCases() map[string]valueTestCase { }, "resource": { value: NewResource([]Value{NewInt(1)}), - exampleType: &ResourceType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooResource", - Fields: []Field{ + exampleType: NewResourceType( + utils.TestLocation, + "FooResource", + []Field{ { Identifier: "bar", Type: IntType, }, }, - }, + nil, + ), withType: func(value Value, ty Type) Value { return value.(Resource).WithType(ty.(*ResourceType)) }, @@ -280,10 +282,10 @@ func newValueTestCases() map[string]valueTestCase { String("foo"), }, ), - exampleType: &EventType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooEvent", - Fields: []Field{ + exampleType: NewEventType( + utils.TestLocation, + "FooEvent", + []Field{ { Identifier: "a", Type: IntType, @@ -293,7 +295,8 @@ func newValueTestCases() map[string]valueTestCase { Type: StringType, }, }, - }, + nil, + ), withType: func(value Value, ty Type) Value { return value.(Event).WithType(ty.(*EventType)) }, @@ -301,16 +304,17 @@ func newValueTestCases() map[string]valueTestCase { }, "contract": { value: NewContract([]Value{String("bar")}), - exampleType: &ContractType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooContract", - Fields: []Field{ + exampleType: NewContractType( + utils.TestLocation, + "FooContract", + []Field{ { Identifier: "y", Type: StringType, }, }, - }, + nil, + ), withType: func(value Value, ty Type) Value { return value.(Contract).WithType(ty.(*ContractType)) }, @@ -318,16 +322,18 @@ func newValueTestCases() map[string]valueTestCase { }, "enum": { value: NewEnum([]Value{UInt8(1)}), - exampleType: &EnumType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooEnum", - Fields: []Field{ + exampleType: NewEnumType( + utils.TestLocation, + "FooEnum", + nil, + []Field{ { Identifier: sema.EnumRawValueFieldName, Type: UInt8Type, }, }, - }, + nil, + ), withType: func(value Value, ty Type) Value { return value.(Enum).WithType(ty.(*EnumType)) }, @@ -335,16 +341,18 @@ func newValueTestCases() map[string]valueTestCase { }, "attachment": { value: NewAttachment([]Value{NewInt(1)}), - exampleType: &AttachmentType{ - Location: utils.TestLocation, - QualifiedIdentifier: "FooAttachment", - Fields: []Field{ + exampleType: NewAttachmentType( + utils.TestLocation, + "FooAttachment", + nil, + []Field{ { Identifier: "bar", Type: IntType, }, }, - }, + nil, + ), withType: func(value Value, ty Type) Value { return value.(Attachment).WithType(ty.(*AttachmentType)) }, @@ -924,11 +932,11 @@ func TestComposite(t *testing.T) { require.Implements(t, (*Composite)(nil), valueWithType) fieldedValueWithType := valueWithType.(Composite) assert.NotNil(t, fieldedValueWithType.getFieldValues()) - assert.NotNil(t, fieldedValueWithType.GetFields()) + assert.NotNil(t, fieldedValueWithType.getFields()) fieldedValue := value.(Composite) - assert.Nil(t, fieldedValue.GetFields()) + assert.Nil(t, fieldedValue.getFields()) } }) @@ -951,10 +959,10 @@ func TestEvent_GetFieldByName(t *testing.T) { assert.Nil(t, FieldsMappedByName(simpleEvent)) assert.Nil(t, SearchFieldByName(simpleEvent, "a")) - simpleEventWithType := simpleEvent.WithType(&EventType{ - Location: utils.TestLocation, - QualifiedIdentifier: "SimpleEvent", - Fields: []Field{ + simpleEventWithType := simpleEvent.WithType(NewEventType( + utils.TestLocation, + "SimpleEvent", + []Field{ { Identifier: "a", Type: IntType, @@ -964,7 +972,8 @@ func TestEvent_GetFieldByName(t *testing.T) { Type: StringType, }, }, - }) + nil, + )) assert.Equal(t, NewInt(1), SearchFieldByName(simpleEventWithType, "a")) assert.Equal(t, String("foo"), SearchFieldByName(simpleEventWithType, "b"))