diff --git a/encoding/ccf/ccf_test.go b/encoding/ccf/ccf_test.go index e8d7e55ada..7473edad25 100644 --- a/encoding/ccf/ccf_test.go +++ b/encoding/ccf/ccf_test.go @@ -24,6 +24,7 @@ import ( "fmt" "math" "math/big" + "strings" "testing" "github.com/fxamacker/cbor/v2" @@ -100,15 +101,15 @@ func TestEncodeOptional(t *testing.T) { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.NewOptionalType(cadence.NewIntType()), + Type: cadence.NewOptionalType(cadence.IntType), }, { Identifier: "b", - Type: cadence.NewOptionalType(cadence.NewOptionalType(cadence.NewIntType())), + Type: cadence.NewOptionalType(cadence.NewOptionalType(cadence.IntType)), }, { Identifier: "c", - Type: cadence.NewOptionalType(cadence.NewOptionalType(cadence.NewOptionalType(cadence.NewIntType()))), + Type: cadence.NewOptionalType(cadence.NewOptionalType(cadence.NewOptionalType(cadence.IntType))), }, }, } @@ -121,15 +122,15 @@ func TestEncodeOptional(t *testing.T) { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.NewOptionalType(cadence.NewAnyStructType()), + Type: cadence.NewOptionalType(cadence.AnyStructType), }, { Identifier: "b", - Type: cadence.NewOptionalType(cadence.NewOptionalType(cadence.NewAnyStructType())), + Type: cadence.NewOptionalType(cadence.NewOptionalType(cadence.AnyStructType)), }, { Identifier: "c", - Type: cadence.NewOptionalType(cadence.NewOptionalType(cadence.NewOptionalType(cadence.NewAnyStructType()))), + Type: cadence.NewOptionalType(cadence.NewOptionalType(cadence.NewOptionalType(cadence.AnyStructType))), }, }, } @@ -805,7 +806,7 @@ func TestEncodeOptional(t *testing.T) { Fields: []cadence.Field{ { Identifier: "bar", - Type: cadence.IntType{}, + Type: cadence.IntType, }, }, } @@ -2862,7 +2863,7 @@ func TestEncodeArray(t *testing.T) { name: "Empty", val: cadence.NewArray( []cadence.Value{}, - ).WithType(cadence.NewVariableSizedArrayType(cadence.NewIntType())), + ).WithType(cadence.NewVariableSizedArrayType(cadence.IntType)), expected: []byte{ // language=json, format=json-cdc // {"type":"Array","value":[]} @@ -2895,7 +2896,7 @@ func TestEncodeArray(t *testing.T) { cadence.NewInt(1), cadence.NewInt(2), cadence.NewInt(3), - }).WithType(cadence.NewConstantSizedArrayType(3, cadence.NewIntType())), + }).WithType(cadence.NewConstantSizedArrayType(3, cadence.IntType)), expected: []byte{ // language=json, format=json-cdc // {"type":"Array","value":[{"type":"Int","value":"1"},{"type":"Int","value":"2"},{"type":"Int","value":"3"}]} @@ -2950,7 +2951,7 @@ func TestEncodeArray(t *testing.T) { cadence.NewInt(1), cadence.NewInt(2), cadence.NewInt(3), - }).WithType(cadence.NewVariableSizedArrayType(cadence.NewIntType())), + }).WithType(cadence.NewVariableSizedArrayType(cadence.IntType)), expected: []byte{ // language=json, format=json-cdc // {"type":"Array","value":[{"type":"Int","value":"1"},{"type":"Int","value":"2"},{"type":"Int","value":"3"}]} @@ -3000,14 +3001,14 @@ func TestEncodeArray(t *testing.T) { val: cadence.NewArray([]cadence.Value{ cadence.NewArray([]cadence.Value{ cadence.NewInt(1), - }).WithType(cadence.NewVariableSizedArrayType(cadence.NewIntType())), + }).WithType(cadence.NewVariableSizedArrayType(cadence.IntType)), cadence.NewArray([]cadence.Value{ cadence.NewInt(2), - }).WithType(cadence.NewVariableSizedArrayType(cadence.NewIntType())), + }).WithType(cadence.NewVariableSizedArrayType(cadence.IntType)), cadence.NewArray([]cadence.Value{ cadence.NewInt(3), - }).WithType(cadence.NewVariableSizedArrayType(cadence.NewIntType())), - }).WithType(cadence.NewVariableSizedArrayType(cadence.NewVariableSizedArrayType(cadence.NewIntType()))), + }).WithType(cadence.NewVariableSizedArrayType(cadence.IntType)), + }).WithType(cadence.NewVariableSizedArrayType(cadence.NewVariableSizedArrayType(cadence.IntType))), expected: []byte{ // language=json, format=json-cdc // {"value":[{"value":[{"value":"1","type":"Int"}],"type":"Array"},{"value":[{"value":"2","type":"Int"}],"type":"Array"},{"value":[{"value":"3","type":"Int"}],"type":"Array"}],"type":"Array"} @@ -3325,7 +3326,7 @@ func TestEncodeArray(t *testing.T) { cadence.NewInt(1), s, cadence.NewBool(true), - }).WithType(cadence.NewVariableSizedArrayType(cadence.NewAnyStructType())), + }).WithType(cadence.NewVariableSizedArrayType(cadence.AnyStructType)), expected: []byte{ // language=json, format=json-cdc // {"type":"Array","value":[{"type":"Int","value":"1"},{"type":"String","value":"a"},{"type":"Bool","value":true}]} @@ -3397,7 +3398,7 @@ func TestEncodeArray(t *testing.T) { cadence.NewInt8(1), cadence.NewInt16(2), cadence.NewInt32(3), - }).WithType(cadence.NewVariableSizedArrayType(cadence.NewNumberType())), + }).WithType(cadence.NewVariableSizedArrayType(cadence.NumberType)), expected: []byte{ // language=json, format=json-cdc // {"value":[{"value":"1","type":"Int8"},{"value":"2","type":"Int16"},{"value":"3","type":"Int32"}],"type":"Array"} @@ -3466,7 +3467,7 @@ func TestEncodeArray(t *testing.T) { cadence.NewResource([]cadence.Value{ cadence.NewInt(1), }).WithType(fooResourceType), - }).WithType(cadence.NewVariableSizedArrayType(cadence.NewAnyStructType())) + }).WithType(cadence.NewVariableSizedArrayType(cadence.AnyStructType)) }(), expected: []byte{ // language=json, format=json-cdc @@ -3929,7 +3930,7 @@ func TestEncodeArray(t *testing.T) { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.IntType{}, + Type: cadence.IntType, }, }, } @@ -4071,7 +4072,7 @@ func TestEncodeArray(t *testing.T) { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.IntType{}, + Type: cadence.IntType, }, }, } @@ -4224,7 +4225,7 @@ func TestEncodeDictionary(t *testing.T) { name: "empty", val: cadence.NewDictionary( []cadence.KeyValuePair{}, - ).WithType(cadence.NewDictionaryType(cadence.NewStringType(), cadence.NewIntType())), + ).WithType(cadence.NewDictionaryType(cadence.StringType, cadence.IntType)), expected: []byte{ // language=json, format=json-cdc // {"value":[],"type":"Dictionary"} @@ -4271,7 +4272,7 @@ func TestEncodeDictionary(t *testing.T) { Key: cadence.String("a"), Value: cadence.NewInt(1), }, - }).WithType(cadence.NewDictionaryType(cadence.NewStringType(), cadence.NewIntType())), + }).WithType(cadence.NewDictionaryType(cadence.StringType, cadence.IntType)), expectedVal: cadence.NewDictionary([]cadence.KeyValuePair{ { Key: cadence.String("a"), @@ -4285,7 +4286,7 @@ func TestEncodeDictionary(t *testing.T) { Key: cadence.String("c"), Value: cadence.NewInt(3), }, - }).WithType(cadence.NewDictionaryType(cadence.NewStringType(), cadence.NewIntType())), + }).WithType(cadence.NewDictionaryType(cadence.StringType, cadence.IntType)), expected: []byte{ // language=json, format=json-cdc // {"type":"Dictionary","value":[{"key":{"type":"String","value":"a"},"value":{"type":"Int","value":"1"}},{"key":{"type":"String","value":"b"},"value":{"type":"Int","value":"2"}},{"key":{"type":"String","value":"c"},"value":{"type":"Int","value":"3"}}]} @@ -4358,7 +4359,7 @@ func TestEncodeDictionary(t *testing.T) { Key: cadence.String("3"), Value: cadence.NewInt(3), }, - }).WithType(cadence.NewDictionaryType(cadence.NewStringType(), cadence.NewIntType())), + }).WithType(cadence.NewDictionaryType(cadence.StringType, cadence.IntType)), }, { Key: cadence.String("b"), @@ -4367,7 +4368,7 @@ func TestEncodeDictionary(t *testing.T) { Key: cadence.String("2"), Value: cadence.NewInt(2), }, - }).WithType(cadence.NewDictionaryType(cadence.NewStringType(), cadence.NewIntType())), + }).WithType(cadence.NewDictionaryType(cadence.StringType, cadence.IntType)), }, { Key: cadence.String("a"), @@ -4376,11 +4377,11 @@ func TestEncodeDictionary(t *testing.T) { Key: cadence.String("1"), Value: cadence.NewInt(1), }, - }).WithType(cadence.NewDictionaryType(cadence.NewStringType(), cadence.NewIntType())), + }).WithType(cadence.NewDictionaryType(cadence.StringType, cadence.IntType)), }, }).WithType(cadence.NewDictionaryType( - cadence.NewStringType(), - cadence.NewDictionaryType(cadence.NewStringType(), cadence.NewIntType())), + cadence.StringType, + cadence.NewDictionaryType(cadence.StringType, cadence.IntType)), ), expectedVal: cadence.NewDictionary([]cadence.KeyValuePair{ { @@ -4390,7 +4391,7 @@ func TestEncodeDictionary(t *testing.T) { Key: cadence.String("1"), Value: cadence.NewInt(1), }, - }).WithType(cadence.NewDictionaryType(cadence.NewStringType(), cadence.NewIntType())), + }).WithType(cadence.NewDictionaryType(cadence.StringType, cadence.IntType)), }, { Key: cadence.String("b"), @@ -4399,7 +4400,7 @@ func TestEncodeDictionary(t *testing.T) { Key: cadence.String("2"), Value: cadence.NewInt(2), }, - }).WithType(cadence.NewDictionaryType(cadence.NewStringType(), cadence.NewIntType())), + }).WithType(cadence.NewDictionaryType(cadence.StringType, cadence.IntType)), }, { Key: cadence.String("c"), @@ -4408,11 +4409,11 @@ func TestEncodeDictionary(t *testing.T) { Key: cadence.String("3"), Value: cadence.NewInt(3), }, - }).WithType(cadence.NewDictionaryType(cadence.NewStringType(), cadence.NewIntType())), + }).WithType(cadence.NewDictionaryType(cadence.StringType, cadence.IntType)), }, }).WithType(cadence.NewDictionaryType( - cadence.NewStringType(), - cadence.NewDictionaryType(cadence.NewStringType(), cadence.NewIntType())), + cadence.StringType, + cadence.NewDictionaryType(cadence.StringType, cadence.IntType)), ), expected: []byte{ // language=json, format=json-cdc @@ -4530,7 +4531,7 @@ func TestEncodeDictionary(t *testing.T) { }).WithType(fooResourceType), }, }).WithType(cadence.NewDictionaryType( - cadence.NewStringType(), + cadence.StringType, fooResourceType, )), expectedVal: cadence.NewDictionary([]cadence.KeyValuePair{ @@ -4553,7 +4554,7 @@ func TestEncodeDictionary(t *testing.T) { }).WithType(fooResourceType), }, }).WithType(cadence.NewDictionaryType( - cadence.NewStringType(), + cadence.StringType, fooResourceType, )), expected: []byte{ @@ -4675,7 +4676,7 @@ func TestEncodeDictionary(t *testing.T) { Key: cadence.NewBool(true), Value: cadence.NewInt(3), }, - }).WithType(cadence.NewDictionaryType(cadence.NewAnyStructType(), cadence.NewAnyStructType())), + }).WithType(cadence.NewDictionaryType(cadence.AnyStructType, cadence.AnyStructType)), expectedVal: cadence.NewDictionary([]cadence.KeyValuePair{ { Key: cadence.NewBool(true), @@ -4689,7 +4690,7 @@ func TestEncodeDictionary(t *testing.T) { Key: cadence.NewInt(0), Value: cadence.NewInt(1), }, - }).WithType(cadence.NewDictionaryType(cadence.NewAnyStructType(), cadence.NewAnyStructType())), + }).WithType(cadence.NewDictionaryType(cadence.AnyStructType, cadence.AnyStructType)), expected: []byte{ // language=json, format=json-cdc // {"value":[{"key":{"value":"c","type":"String"},"value":{"value":"2","type":"Int"}},{"key":{"value":"0","type":"Int"},"value":{"value":"1","type":"Int"}},{"key":{"value":true,"type":"Bool"},"value":{"value":"3","type":"Int"}}],"type":"Dictionary"} @@ -4832,7 +4833,7 @@ func TestEncodeSortedDictionary(t *testing.T) { Key: cadence.String("b"), Value: cadence.NewInt(2), }, - }).WithType(cadence.NewDictionaryType(cadence.NewStringType(), cadence.NewIntType())) + }).WithType(cadence.NewDictionaryType(cadence.StringType, cadence.IntType)) expectedDict := cadence.NewDictionary([]cadence.KeyValuePair{ { @@ -4847,7 +4848,7 @@ func TestEncodeSortedDictionary(t *testing.T) { Key: cadence.String("c"), Value: cadence.NewInt(3), }, - }).WithType(cadence.NewDictionaryType(cadence.NewStringType(), cadence.NewIntType())) + }).WithType(cadence.NewDictionaryType(cadence.StringType, cadence.IntType)) simpleDict := testCase{ "Simple", @@ -4996,8 +4997,8 @@ func TestEncodeResource(t *testing.T) { common.NewStringLocation(nil, "test"), "Foo", []cadence.Field{ - {Type: cadence.NewIntType(), Identifier: "bar"}, - {Type: cadence.NewUInt64Type(), Identifier: "uuid"}, + {Type: cadence.IntType, Identifier: "bar"}, + {Type: cadence.UInt64Type, Identifier: "uuid"}, }, nil, )) @@ -5112,8 +5113,8 @@ func TestEncodeResource(t *testing.T) { common.NewStringLocation(nil, "test"), "Foo", []cadence.Field{ - {Type: cadence.NewIntType(), Identifier: "bar"}, - {Type: cadence.NewUInt64Type(), Identifier: "uuid"}, + {Type: cadence.IntType, Identifier: "bar"}, + {Type: cadence.UInt64Type, Identifier: "uuid"}, }, nil, )) @@ -5236,8 +5237,8 @@ func TestEncodeResource(t *testing.T) { common.NewStringLocation(nil, "test"), "Bar", []cadence.Field{ - {Type: cadence.NewIntType(), Identifier: "x"}, - {Type: cadence.NewUInt64Type(), Identifier: "uuid"}, + {Type: cadence.IntType, Identifier: "x"}, + {Type: cadence.UInt64Type, Identifier: "uuid"}, }, nil, ) @@ -5257,7 +5258,7 @@ func TestEncodeResource(t *testing.T) { "Foo", []cadence.Field{ {Type: expectedBarResourceType, Identifier: "bar"}, - {Type: cadence.NewUInt64Type(), Identifier: "uuid"}, + {Type: cadence.UInt64Type, Identifier: "uuid"}, }, nil, )) @@ -5465,11 +5466,11 @@ func TestEncodeStruct(t *testing.T) { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.IntType{}, + Type: cadence.IntType, }, { Identifier: "b", - Type: cadence.StringType{}, + Type: cadence.StringType, }, }, } @@ -5713,11 +5714,11 @@ func TestEncodeEvent(t *testing.T) { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.IntType{}, + Type: cadence.IntType, }, { Identifier: "b", - Type: cadence.StringType{}, + Type: cadence.StringType, }, }, } @@ -5816,11 +5817,11 @@ func TestEncodeEvent(t *testing.T) { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.IntType{}, + Type: cadence.IntType, }, { Identifier: "b", - Type: cadence.AnyStructType{}, + Type: cadence.AnyStructType, }, }, } @@ -5830,7 +5831,7 @@ func TestEncodeEvent(t *testing.T) { Fields: []cadence.Field{ { Identifier: "c", - Type: cadence.StringType{}, + Type: cadence.StringType, }, }, } @@ -5976,7 +5977,7 @@ func TestEncodeEvent(t *testing.T) { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.StringType{}, + Type: cadence.StringType, }, { Identifier: "b", @@ -6144,11 +6145,11 @@ func TestEncodeContract(t *testing.T) { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.IntType{}, + Type: cadence.IntType, }, { Identifier: "b", - Type: cadence.StringType{}, + Type: cadence.StringType, }, }, } @@ -6247,7 +6248,7 @@ func TestEncodeContract(t *testing.T) { Fields: []cadence.Field{ { Identifier: "c", - Type: cadence.StringType{}, + Type: cadence.StringType, }, }, } @@ -6257,11 +6258,11 @@ func TestEncodeContract(t *testing.T) { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.IntType{}, + Type: cadence.IntType, }, { Identifier: "b", - Type: cadence.AnyStructType{}, + Type: cadence.AnyStructType, }, }, } @@ -6407,7 +6408,7 @@ func TestEncodeContract(t *testing.T) { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.StringType{}, + Type: cadence.StringType, }, { Identifier: "b", @@ -6558,7 +6559,7 @@ func TestEncodeEnum(t *testing.T) { Fields: []cadence.Field{ { Identifier: "raw", - Type: cadence.UInt8Type{}, + Type: cadence.UInt8Type, }, }, } @@ -6654,8 +6655,8 @@ func TestEncodeValueOfIntersectionType(t *testing.T) { common.NewStringLocation(nil, "test"), "Stats", []cadence.Field{ - cadence.NewField("count", cadence.NewIntType()), - cadence.NewField("sum", cadence.NewIntType()), + cadence.NewField("count", cadence.IntType), + cadence.NewField("sum", cadence.IntType), }, nil, ) @@ -6680,8 +6681,8 @@ func TestEncodeValueOfIntersectionType(t *testing.T) { common.NewStringLocation(nil, "test"), "Stats", []cadence.Field{ - cadence.NewField("sum", cadence.NewIntType()), - cadence.NewField("count", cadence.NewIntType()), + cadence.NewField("sum", cadence.IntType), + cadence.NewField("count", cadence.IntType), }, nil, ) @@ -6868,8 +6869,8 @@ func TestEncodeValueOfIntersectionType(t *testing.T) { common.NewStringLocation(nil, "test"), "Stats", []cadence.Field{ - cadence.NewField("count", cadence.NewIntType()), - cadence.NewField("sum", cadence.NewIntType()), + cadence.NewField("count", cadence.IntType), + cadence.NewField("sum", cadence.IntType), }, nil, ) @@ -6894,8 +6895,8 @@ func TestEncodeValueOfIntersectionType(t *testing.T) { common.NewStringLocation(nil, "test"), "Stats", []cadence.Field{ - cadence.NewField("sum", cadence.NewIntType()), - cadence.NewField("count", cadence.NewIntType()), + cadence.NewField("sum", cadence.IntType), + cadence.NewField("count", cadence.IntType), }, nil, ) @@ -7075,7 +7076,7 @@ func TestEncodeValueOfReferenceType(t *testing.T) { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.StringType{}, + Type: cadence.StringType, }, }, } @@ -7088,7 +7089,7 @@ func TestEncodeValueOfReferenceType(t *testing.T) { cadence.String("a"), cadence.String("b"), }).WithType(cadence.NewVariableSizedArrayType( - cadence.NewReferenceType(cadence.UnauthorizedAccess, cadence.NewStringType()), + cadence.NewReferenceType(cadence.UnauthorizedAccess, cadence.StringType), )), expected: []byte{ // language=json, format=json-cdc @@ -7136,7 +7137,7 @@ func TestEncodeValueOfReferenceType(t *testing.T) { cadence.NewOptional(cadence.String("a")), cadence.NewOptional(nil), }).WithType(cadence.NewVariableSizedArrayType( - cadence.NewReferenceType(cadence.UnauthorizedAccess, cadence.NewOptionalType(cadence.NewStringType())), + cadence.NewReferenceType(cadence.UnauthorizedAccess, cadence.NewOptionalType(cadence.StringType)), )), expected: []byte{ // language=json, format=json-cdc @@ -7182,10 +7183,10 @@ func TestEncodeValueOfReferenceType(t *testing.T) { name: "dictionary of optional reference to Int", val: func() cadence.Value { dictionaryType := &cadence.DictionaryType{ - KeyType: cadence.TheStringType, + KeyType: cadence.StringType, ElementType: &cadence.OptionalType{ Type: &cadence.ReferenceType{ - Type: cadence.TheInt128Type, + Type: cadence.Int128Type, Authorization: cadence.UnauthorizedAccess, }, }, @@ -7262,7 +7263,7 @@ func TestEncodeValueOfReferenceType(t *testing.T) { cadence.String("a"), cadence.NewUInt8(1), }).WithType(cadence.NewVariableSizedArrayType( - cadence.NewReferenceType(cadence.UnauthorizedAccess, cadence.NewAnyStructType()), + cadence.NewReferenceType(cadence.UnauthorizedAccess, cadence.AnyStructType), )), expected: []byte{ // language=json, format=json-cdc @@ -7423,7 +7424,7 @@ func TestEncodeValueOfReferenceType(t *testing.T) { cadence.String("b"), }).WithType(simpleStructType), }).WithType(cadence.NewVariableSizedArrayType( - cadence.NewReferenceType(cadence.UnauthorizedAccess, cadence.NewAnyStructType()), + cadence.NewReferenceType(cadence.UnauthorizedAccess, cadence.AnyStructType), )) }(), expected: []byte{ @@ -7529,7 +7530,7 @@ func TestEncodeValueOfReferenceType(t *testing.T) { }).WithType(cadence.NewVariableSizedArrayType( cadence.NewReferenceType( cadence.UnauthorizedAccess, - cadence.NewOptionalType(cadence.NewAnyStructType()), + cadence.NewOptionalType(cadence.AnyStructType), ))), expected: []byte{ // language=json, format=json-cdc @@ -7601,7 +7602,7 @@ func TestEncodeValueOfReferenceType(t *testing.T) { cadence.NewOptionalType( cadence.NewReferenceType( cadence.UnauthorizedAccess, - cadence.NewAnyStructType(), + cadence.AnyStructType, )))), expected: []byte{ // language=json, format=json-cdc @@ -7674,7 +7675,7 @@ func TestEncodeValueOfReferenceType(t *testing.T) { cadence.NewReferenceType( cadence.UnauthorizedAccess, cadence.NewOptionalType( - cadence.NewAnyStructType(), + cadence.AnyStructType, ))))), expected: []byte{ // language=json, format=json-cdc @@ -7755,68 +7756,7 @@ func TestEncodeSimpleTypes(t *testing.T) { t.Parallel() - type simpleTypes struct { - typ cadence.Type - cborSimpleTypeID int - } - - var tests []encodeTest - - for _, ty := range []simpleTypes{ - {cadence.AnyType{}, ccf.TypeAny}, - {cadence.AnyResourceType{}, ccf.TypeAnyResource}, - {cadence.AnyStructAttachmentType{}, ccf.TypeAnyStructAttachmentType}, - {cadence.AnyResourceAttachmentType{}, ccf.TypeAnyResourceAttachmentType}, - {cadence.MetaType{}, ccf.TypeMetaType}, - {cadence.VoidType{}, ccf.TypeVoid}, - {cadence.NeverType{}, ccf.TypeNever}, - {cadence.BoolType{}, ccf.TypeBool}, - {cadence.StringType{}, ccf.TypeString}, - {cadence.CharacterType{}, ccf.TypeCharacter}, - {cadence.BytesType{}, ccf.TypeBytes}, - {cadence.AddressType{}, ccf.TypeAddress}, - {cadence.SignedNumberType{}, ccf.TypeSignedNumber}, - {cadence.IntegerType{}, ccf.TypeInteger}, - {cadence.SignedIntegerType{}, ccf.TypeSignedInteger}, - {cadence.FixedPointType{}, ccf.TypeFixedPoint}, - {cadence.SignedFixedPointType{}, ccf.TypeSignedFixedPoint}, - {cadence.IntType{}, ccf.TypeInt}, - {cadence.Int8Type{}, ccf.TypeInt8}, - {cadence.Int16Type{}, ccf.TypeInt16}, - {cadence.Int32Type{}, ccf.TypeInt32}, - {cadence.Int64Type{}, ccf.TypeInt64}, - {cadence.Int128Type{}, ccf.TypeInt128}, - {cadence.Int256Type{}, ccf.TypeInt256}, - {cadence.UIntType{}, ccf.TypeUInt}, - {cadence.UInt8Type{}, ccf.TypeUInt8}, - {cadence.UInt16Type{}, ccf.TypeUInt16}, - {cadence.UInt32Type{}, ccf.TypeUInt32}, - {cadence.UInt64Type{}, ccf.TypeUInt64}, - {cadence.UInt128Type{}, ccf.TypeUInt128}, - {cadence.UInt256Type{}, ccf.TypeUInt256}, - {cadence.Word8Type{}, ccf.TypeWord8}, - {cadence.Word16Type{}, ccf.TypeWord16}, - {cadence.Word32Type{}, ccf.TypeWord32}, - {cadence.Word64Type{}, ccf.TypeWord64}, - {cadence.Word128Type{}, ccf.TypeWord128}, - {cadence.Word256Type{}, ccf.TypeWord256}, - {cadence.Fix64Type{}, ccf.TypeFix64}, - {cadence.UFix64Type{}, ccf.TypeUFix64}, - {cadence.BlockType{}, ccf.TypeBlock}, - {cadence.PathType{}, ccf.TypePath}, - {cadence.CapabilityPathType{}, ccf.TypeCapabilityPath}, - {cadence.StoragePathType{}, ccf.TypeStoragePath}, - {cadence.PublicPathType{}, ccf.TypePublicPath}, - {cadence.PrivatePathType{}, ccf.TypePrivatePath}, - {cadence.AccountKeyType{}, ccf.TypeAccountKey}, - {cadence.AuthAccountContractsType{}, ccf.TypeAuthAccountContracts}, - {cadence.AuthAccountKeysType{}, ccf.TypeAuthAccountKeys}, - {cadence.AuthAccountType{}, ccf.TypeAuthAccount}, - {cadence.PublicAccountContractsType{}, ccf.TypePublicAccountContracts}, - {cadence.PublicAccountKeysType{}, ccf.TypePublicAccountKeys}, - {cadence.PublicAccountType{}, ccf.TypePublicAccount}, - {cadence.DeployedContractType{}, ccf.TypeDeployedContract}, - } { + expected := func(ty ccf.SimpleType) []byte { var w bytes.Buffer cborEncMode := func() cbor.EncMode { @@ -7845,17 +7785,136 @@ func TestEncodeSimpleTypes(t *testing.T) { }) require.NoError(t, err) - err = encoder.EncodeInt(ty.cborSimpleTypeID) + err = encoder.EncodeUint64(uint64(ty)) + require.NoError(t, err) + + err = encoder.Flush() require.NoError(t, err) - encoder.Flush() + return w.Bytes() + } + + var tests []encodeTest + + testCases := map[ccf.SimpleType]cadence.Type{ + ccf.SimpleTypeAny: cadence.AnyType, + ccf.SimpleTypeAnyResource: cadence.AnyResourceType, + ccf.SimpleTypeAnyStruct: cadence.AnyStructType, + ccf.SimpleTypeAnyStructAttachmentType: cadence.AnyStructAttachmentType, + ccf.SimpleTypeAnyResourceAttachmentType: cadence.AnyResourceAttachmentType, + ccf.SimpleTypeMetaType: cadence.MetaType, + ccf.SimpleTypeVoid: cadence.VoidType, + ccf.SimpleTypeNever: cadence.NeverType, + ccf.SimpleTypeBool: cadence.BoolType, + ccf.SimpleTypeString: cadence.StringType, + ccf.SimpleTypeCharacter: cadence.CharacterType, + ccf.SimpleTypeBytes: cadence.TheBytesType, + ccf.SimpleTypeAddress: cadence.AddressType, + ccf.SimpleTypeNumber: cadence.NumberType, + ccf.SimpleTypeSignedNumber: cadence.SignedNumberType, + ccf.SimpleTypeInteger: cadence.IntegerType, + ccf.SimpleTypeSignedInteger: cadence.SignedIntegerType, + ccf.SimpleTypeFixedPoint: cadence.FixedPointType, + ccf.SimpleTypeSignedFixedPoint: cadence.SignedFixedPointType, + ccf.SimpleTypeInt: cadence.IntType, + ccf.SimpleTypeInt8: cadence.Int8Type, + ccf.SimpleTypeInt16: cadence.Int16Type, + ccf.SimpleTypeInt32: cadence.Int32Type, + ccf.SimpleTypeInt64: cadence.Int64Type, + ccf.SimpleTypeInt128: cadence.Int128Type, + ccf.SimpleTypeInt256: cadence.Int256Type, + ccf.SimpleTypeUInt: cadence.UIntType, + ccf.SimpleTypeUInt8: cadence.UInt8Type, + ccf.SimpleTypeUInt16: cadence.UInt16Type, + ccf.SimpleTypeUInt32: cadence.UInt32Type, + ccf.SimpleTypeUInt64: cadence.UInt64Type, + ccf.SimpleTypeUInt128: cadence.UInt128Type, + ccf.SimpleTypeUInt256: cadence.UInt256Type, + ccf.SimpleTypeWord8: cadence.Word8Type, + ccf.SimpleTypeWord16: cadence.Word16Type, + ccf.SimpleTypeWord32: cadence.Word32Type, + ccf.SimpleTypeWord64: cadence.Word64Type, + ccf.SimpleTypeWord128: cadence.Word128Type, + ccf.SimpleTypeWord256: cadence.Word256Type, + ccf.SimpleTypeFix64: cadence.Fix64Type, + ccf.SimpleTypeUFix64: cadence.UFix64Type, + ccf.SimpleTypeBlock: cadence.BlockType, + ccf.SimpleTypePath: cadence.PathType, + ccf.SimpleTypeCapabilityPath: cadence.CapabilityPathType, + ccf.SimpleTypeStoragePath: cadence.StoragePathType, + ccf.SimpleTypePublicPath: cadence.PublicPathType, + ccf.SimpleTypePrivatePath: cadence.PrivatePathType, + ccf.SimpleTypeDeployedContract: cadence.DeployedContractType, + ccf.SimpleTypeStorageCapabilityController: cadence.StorageCapabilityControllerType, + ccf.SimpleTypeAccountCapabilityController: cadence.AccountCapabilityControllerType, + ccf.SimpleTypeAccount: cadence.AccountType, + ccf.SimpleTypeAccount_Contracts: cadence.Account_ContractsType, + ccf.SimpleTypeAccount_Keys: cadence.Account_KeysType, + ccf.SimpleTypeAccount_Inbox: cadence.Account_InboxType, + ccf.SimpleTypeAccount_StorageCapabilities: cadence.Account_StorageCapabilitiesType, + ccf.SimpleTypeAccount_AccountCapabilities: cadence.Account_AccountCapabilitiesType, + ccf.SimpleTypeAccount_Capabilities: cadence.Account_CapabilitiesType, + ccf.SimpleTypeAccount_Storage: cadence.Account_StorageType, + ccf.SimpleTypeMutate: cadence.MutateType, + ccf.SimpleTypeInsert: cadence.InsertType, + ccf.SimpleTypeRemove: cadence.RemoveType, + ccf.SimpleTypeIdentity: cadence.IdentityType, + ccf.SimpleTypeStorage: cadence.StorageType, + ccf.SimpleTypeSaveValue: cadence.SaveValueType, + ccf.SimpleTypeLoadValue: cadence.LoadValueType, + ccf.SimpleTypeBorrowValue: cadence.BorrowValueType, + ccf.SimpleTypeContracts: cadence.ContractsType, + ccf.SimpleTypeAddContract: cadence.AddContractType, + ccf.SimpleTypeUpdateContract: cadence.UpdateContractType, + ccf.SimpleTypeRemoveContract: cadence.RemoveContractType, + ccf.SimpleTypeKeys: cadence.KeysType, + ccf.SimpleTypeAddKey: cadence.AddKeyType, + ccf.SimpleTypeRevokeKey: cadence.RevokeKeyType, + ccf.SimpleTypeInbox: cadence.InboxType, + ccf.SimpleTypePublishInboxCapability: cadence.PublishInboxCapabilityType, + ccf.SimpleTypeUnpublishInboxCapability: cadence.UnpublishInboxCapabilityType, + ccf.SimpleTypeClaimInboxCapability: cadence.ClaimInboxCapabilityType, + ccf.SimpleTypeCapabilities: cadence.CapabilitiesType, + ccf.SimpleTypeStorageCapabilities: cadence.StorageCapabilitiesType, + ccf.SimpleTypeAccountCapabilities: cadence.AccountCapabilitiesType, + ccf.SimpleTypePublishCapability: cadence.PublishCapabilityType, + ccf.SimpleTypeUnpublishCapability: cadence.UnpublishCapabilityType, + ccf.SimpleTypeGetStorageCapabilityController: cadence.GetStorageCapabilityControllerType, + ccf.SimpleTypeIssueStorageCapabilityController: cadence.IssueStorageCapabilityControllerType, + ccf.SimpleTypeGetAccountCapabilityController: cadence.GetAccountCapabilityControllerType, + ccf.SimpleTypeIssueAccountCapabilityController: cadence.IssueAccountCapabilityControllerType, + ccf.SimpleTypeCapabilitiesMapping: cadence.CapabilitiesMappingType, + ccf.SimpleTypeAccountMapping: cadence.AccountMappingType, + } + + var missingTests []string + + for ty := ccf.SimpleType(0); ty < ccf.SimpleType_Count; ty++ { + if ty == ccf.SimpleTypeFunction { + continue + } + + _, ok := testCases[ty] + + name := ty.String() + if ok || strings.Contains(name, "(") { + continue + } + missingTests = append(missingTests, name) + } + + if len(missingTests) > 0 { + assert.Failf(t, "missing test cases", strings.Join(missingTests, ", ")) + } + + for simpleType, cadenceType := range testCases { tests = append(tests, encodeTest{ - name: fmt.Sprintf("with static %s", ty.typ.ID()), + name: fmt.Sprintf("with static %s", cadenceType.ID()), val: cadence.TypeValue{ - StaticType: ty.typ, + StaticType: cadenceType, }, - expected: w.Bytes(), + expected: expected(simpleType), // language=json, format=json-cdc // {"type":"Type","value":{"staticType":{"kind":"[ty.ID()]"}}} // @@ -7877,7 +7936,7 @@ func TestEncodeType(t *testing.T) { testEncodeAndDecode( t, cadence.TypeValue{ - StaticType: &cadence.OptionalType{Type: cadence.IntType{}}, + StaticType: &cadence.OptionalType{Type: cadence.IntType}, }, []byte{ // language=json, format=json-cdc @@ -7914,7 +7973,7 @@ func TestEncodeType(t *testing.T) { cadence.TypeValue{ StaticType: &cadence.OptionalType{ Type: &cadence.OptionalType{ - Type: cadence.IntType{}, + Type: cadence.IntType, }, }, }, @@ -7953,7 +8012,7 @@ func TestEncodeType(t *testing.T) { t, cadence.TypeValue{ StaticType: &cadence.VariableSizedArrayType{ - ElementType: cadence.IntType{}, + ElementType: cadence.IntType, }, }, []byte{ @@ -7990,7 +8049,7 @@ func TestEncodeType(t *testing.T) { t, cadence.TypeValue{ StaticType: &cadence.ConstantSizedArrayType{ - ElementType: cadence.IntType{}, + ElementType: cadence.IntType, Size: 3, }, }, @@ -8032,8 +8091,8 @@ func TestEncodeType(t *testing.T) { t, cadence.TypeValue{ StaticType: &cadence.DictionaryType{ - ElementType: cadence.StringType{}, - KeyType: cadence.IntType{}, + ElementType: cadence.StringType, + KeyType: cadence.IntType, }, }, []byte{ @@ -8128,13 +8187,13 @@ func TestEncodeType(t *testing.T) { Location: utils.TestLocation, QualifiedIdentifier: "S", Fields: []cadence.Field{ - {Identifier: "foo", Type: cadence.IntType{}}, - {Identifier: "bar", Type: cadence.IntType{}}, + {Identifier: "foo", Type: cadence.IntType}, + {Identifier: "bar", Type: cadence.IntType}, }, Initializers: [][]cadence.Parameter{ { - {Label: "foo", Identifier: "bar", Type: cadence.IntType{}}, - {Label: "qux", Identifier: "baz", Type: cadence.StringType{}}, + {Label: "foo", Identifier: "bar", Type: cadence.IntType}, + {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, }, }, @@ -8251,13 +8310,13 @@ func TestEncodeType(t *testing.T) { Location: utils.TestLocation, QualifiedIdentifier: "S", Fields: []cadence.Field{ - {Identifier: "foo", Type: cadence.IntType{}}, - {Identifier: "bar", Type: cadence.IntType{}}, + {Identifier: "foo", Type: cadence.IntType}, + {Identifier: "bar", Type: cadence.IntType}, }, Initializers: [][]cadence.Parameter{ { - {Label: "foo", Identifier: "bar", Type: cadence.IntType{}}, - {Label: "qux", Identifier: "baz", Type: cadence.StringType{}}, + {Label: "foo", Identifier: "bar", Type: cadence.IntType}, + {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, }, }, @@ -8352,13 +8411,13 @@ func TestEncodeType(t *testing.T) { Location: utils.TestLocation, QualifiedIdentifier: "S", Fields: []cadence.Field{ - {Identifier: "bar", Type: cadence.IntType{}}, - {Identifier: "foo", Type: cadence.IntType{}}, + {Identifier: "bar", Type: cadence.IntType}, + {Identifier: "foo", Type: cadence.IntType}, }, Initializers: [][]cadence.Parameter{ { - {Label: "foo", Identifier: "bar", Type: cadence.IntType{}}, - {Label: "qux", Identifier: "baz", Type: cadence.StringType{}}, + {Label: "foo", Identifier: "bar", Type: cadence.IntType}, + {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, }, }, @@ -8513,12 +8572,12 @@ func TestEncodeType(t *testing.T) { Location: utils.TestLocation, QualifiedIdentifier: "R", Fields: []cadence.Field{ - {Identifier: "foo", Type: cadence.IntType{}}, + {Identifier: "foo", Type: cadence.IntType}, }, Initializers: [][]cadence.Parameter{ { - {Label: "foo", Identifier: "bar", Type: cadence.IntType{}}, - {Label: "qux", Identifier: "baz", Type: cadence.StringType{}}, + {Label: "foo", Identifier: "bar", Type: cadence.IntType}, + {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, }, }, @@ -8611,12 +8670,12 @@ func TestEncodeType(t *testing.T) { Location: utils.TestLocation, QualifiedIdentifier: "C", Fields: []cadence.Field{ - {Identifier: "foo", Type: cadence.IntType{}}, + {Identifier: "foo", Type: cadence.IntType}, }, Initializers: [][]cadence.Parameter{ { - {Label: "foo", Identifier: "bar", Type: cadence.IntType{}}, - {Label: "qux", Identifier: "baz", Type: cadence.StringType{}}, + {Label: "foo", Identifier: "bar", Type: cadence.IntType}, + {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, }, }, @@ -8709,12 +8768,12 @@ func TestEncodeType(t *testing.T) { Location: utils.TestLocation, QualifiedIdentifier: "S", Fields: []cadence.Field{ - {Identifier: "foo", Type: cadence.IntType{}}, + {Identifier: "foo", Type: cadence.IntType}, }, Initializers: [][]cadence.Parameter{ { - {Label: "foo", Identifier: "bar", Type: cadence.IntType{}}, - {Label: "qux", Identifier: "baz", Type: cadence.StringType{}}, + {Label: "foo", Identifier: "bar", Type: cadence.IntType}, + {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, }, }, @@ -8807,12 +8866,12 @@ func TestEncodeType(t *testing.T) { Location: utils.TestLocation, QualifiedIdentifier: "R", Fields: []cadence.Field{ - {Identifier: "foo", Type: cadence.IntType{}}, + {Identifier: "foo", Type: cadence.IntType}, }, Initializers: [][]cadence.Parameter{ { - {Label: "foo", Identifier: "bar", Type: cadence.IntType{}}, - {Label: "qux", Identifier: "baz", Type: cadence.StringType{}}, + {Label: "foo", Identifier: "bar", Type: cadence.IntType}, + {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, }, }, @@ -8905,12 +8964,12 @@ func TestEncodeType(t *testing.T) { Location: utils.TestLocation, QualifiedIdentifier: "C", Fields: []cadence.Field{ - {Identifier: "foo", Type: cadence.IntType{}}, + {Identifier: "foo", Type: cadence.IntType}, }, Initializers: [][]cadence.Parameter{ { - {Label: "foo", Identifier: "bar", Type: cadence.IntType{}}, - {Label: "qux", Identifier: "baz", Type: cadence.StringType{}}, + {Label: "foo", Identifier: "bar", Type: cadence.IntType}, + {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, }, }, @@ -9003,11 +9062,11 @@ func TestEncodeType(t *testing.T) { Location: utils.TestLocation, QualifiedIdentifier: "E", Fields: []cadence.Field{ - {Identifier: "foo", Type: cadence.IntType{}}, + {Identifier: "foo", Type: cadence.IntType}, }, Initializer: []cadence.Parameter{ - {Label: "foo", Identifier: "bar", Type: cadence.IntType{}}, - {Label: "qux", Identifier: "baz", Type: cadence.StringType{}}, + {Label: "foo", Identifier: "bar", Type: cadence.IntType}, + {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, }, }, @@ -9098,14 +9157,14 @@ func TestEncodeType(t *testing.T) { StaticType: &cadence.EnumType{ Location: utils.TestLocation, QualifiedIdentifier: "E", - RawType: cadence.StringType{}, + RawType: cadence.StringType, Fields: []cadence.Field{ - {Identifier: "foo", Type: cadence.IntType{}}, + {Identifier: "foo", Type: cadence.IntType}, }, Initializers: [][]cadence.Parameter{ { - {Label: "foo", Identifier: "bar", Type: cadence.IntType{}}, - {Label: "qux", Identifier: "baz", Type: cadence.StringType{}}, + {Label: "foo", Identifier: "bar", Type: cadence.IntType}, + {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, }, }, @@ -9198,7 +9257,7 @@ func TestEncodeType(t *testing.T) { cadence.TypeValue{ StaticType: &cadence.ReferenceType{ Authorization: cadence.UnauthorizedAccess, - Type: cadence.IntType{}, + Type: cadence.IntType, }, }, []byte{ @@ -9240,12 +9299,12 @@ func TestEncodeType(t *testing.T) { cadence.TypeValue{ StaticType: &cadence.FunctionType{ TypeParameters: []cadence.TypeParameter{ - {Name: "T", TypeBound: cadence.AnyStructType{}}, + {Name: "T", TypeBound: cadence.AnyStructType}, }, Parameters: []cadence.Parameter{ - {Label: "qux", Identifier: "baz", Type: cadence.StringType{}}, + {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, - ReturnType: cadence.IntType{}, + ReturnType: cadence.IntType, }, }, []byte{ @@ -9315,9 +9374,9 @@ func TestEncodeType(t *testing.T) { {Name: "T"}, }, Parameters: []cadence.Parameter{ - {Label: "qux", Identifier: "baz", Type: cadence.StringType{}}, + {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, - ReturnType: cadence.IntType{}, + ReturnType: cadence.IntType, }, }, []byte{ @@ -9415,7 +9474,7 @@ func TestEncodeType(t *testing.T) { t, cadence.TypeValue{ StaticType: &cadence.CapabilityType{ - BorrowType: cadence.IntType{}, + BorrowType: cadence.IntType, }, }, []byte{ @@ -9516,7 +9575,7 @@ func TestEncodeType(t *testing.T) { cadence.TypeValue{ StaticType: &cadence.IntersectionType{ Types: []cadence.Type{ - cadence.StringType{}, + cadence.StringType, }, }, }, @@ -9549,7 +9608,7 @@ func TestEncodeType(t *testing.T) { cadence.TypeValue{ StaticType: &cadence.IntersectionType{ Types: []cadence.Type{ - cadence.StringType{}, + cadence.StringType, }, }, }, @@ -9565,8 +9624,8 @@ func TestEncodeType(t *testing.T) { cadence.TypeValue{ StaticType: &cadence.IntersectionType{ Types: []cadence.Type{ - cadence.NewAnyStructType(), - cadence.StringType{}, + cadence.AnyStructType, + cadence.StringType, }, }, }, @@ -9603,8 +9662,8 @@ func TestEncodeType(t *testing.T) { cadence.TypeValue{ StaticType: &cadence.IntersectionType{ Types: []cadence.Type{ - cadence.StringType{}, - cadence.NewAnyStructType(), + cadence.StringType, + cadence.AnyStructType, }, }, }, @@ -9831,7 +9890,7 @@ func TestEncodeCapability(t *testing.T) { Fields: []cadence.Field{ { Identifier: "bar", - Type: cadence.IntType{}, + Type: cadence.IntType, }, }, } @@ -9839,7 +9898,7 @@ func TestEncodeCapability(t *testing.T) { capability1 := cadence.Capability{ ID: 42, Address: cadence.BytesToAddress([]byte{1, 2, 3, 4, 5}), - BorrowType: cadence.IntType{}, + BorrowType: cadence.IntType, } capability2 := cadence.Capability{ @@ -9964,7 +10023,7 @@ func TestEncodeCapability(t *testing.T) { cadence.Capability{ ID: 42, Address: cadence.BytesToAddress([]byte{1, 2, 3, 4, 5}), - BorrowType: cadence.IntType{}, + BorrowType: cadence.IntType, }, []byte{ // language=edn, format=ccf @@ -10002,12 +10061,12 @@ func TestEncodeCapability(t *testing.T) { capability1 := cadence.Capability{ ID: 42, Address: cadence.BytesToAddress([]byte{1, 2, 3, 4, 5}), - BorrowType: cadence.IntType{}, + BorrowType: cadence.IntType, } capability2 := cadence.Capability{ ID: 43, Address: cadence.BytesToAddress([]byte{1, 2, 3, 4, 5}), - BorrowType: cadence.IntType{}, + BorrowType: cadence.IntType, } testEncodeAndDecode( @@ -10015,7 +10074,7 @@ func TestEncodeCapability(t *testing.T) { cadence.NewArray([]cadence.Value{ capability1, capability2, - }).WithType(cadence.NewVariableSizedArrayType(cadence.NewCapabilityType(cadence.NewIntType()))), + }).WithType(cadence.NewVariableSizedArrayType(cadence.NewCapabilityType(cadence.IntType))), []byte{ // language=edn, format=ccf // 130([139(144([137(4)])), [[h'0000000102030405', 42], [h'0000000102030405', 43]]]) @@ -11137,7 +11196,7 @@ func TestEncodePath(t *testing.T) { storagePath, privatePath, publicPath, - }).WithType(cadence.NewVariableSizedArrayType(cadence.NewStoragePathType())) + }).WithType(cadence.NewVariableSizedArrayType(cadence.StoragePathType)) testEncodeAndDecode( t, @@ -11209,7 +11268,7 @@ func TestEncodePath(t *testing.T) { storagePath, privatePath, publicPath, - }).WithType(cadence.NewVariableSizedArrayType(cadence.NewPathType())) + }).WithType(cadence.NewVariableSizedArrayType(cadence.PathType)) testEncodeAndDecode( t, @@ -11525,7 +11584,7 @@ func newResourceStructType() *cadence.StructType { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.StringType{}, + Type: cadence.StringType, }, { Identifier: "b", @@ -11542,7 +11601,7 @@ func newFooResourceType() *cadence.ResourceType { Fields: []cadence.Field{ { Identifier: "bar", - Type: cadence.IntType{}, + Type: cadence.IntType, }, }, } @@ -11555,11 +11614,11 @@ func newFoooResourceTypeWithAbstractField() *cadence.ResourceType { Fields: []cadence.Field{ { Identifier: "bar", - Type: cadence.IntType{}, + Type: cadence.IntType, }, { Identifier: "baz", - Type: cadence.AnyStructType{}, + Type: cadence.AnyStructType, }, }, } @@ -11952,7 +12011,7 @@ func TestExportFunctionValue(t *testing.T) { cadence.Function{ FunctionType: &cadence.FunctionType{ Parameters: []cadence.Parameter{}, - ReturnType: cadence.VoidType{}, + ReturnType: cadence.VoidType, }, }, []byte{ @@ -12817,15 +12876,15 @@ func newFlowFeesFeesDeductedEventType() *cadence.EventType { Fields: []cadence.Field{ { Identifier: "amount", - Type: cadence.UFix64Type{}, + Type: cadence.UFix64Type, }, { Identifier: "inclusionEffort", - Type: cadence.UFix64Type{}, + Type: cadence.UFix64Type, }, { Identifier: "executionEffort", - Type: cadence.UFix64Type{}, + Type: cadence.UFix64Type, }, }, } @@ -12861,7 +12920,7 @@ func newFlowFeesTokensWithdrawnEventType() *cadence.EventType { Fields: []cadence.Field{ { Identifier: "amount", - Type: cadence.UFix64Type{}, + Type: cadence.UFix64Type, }, }, } @@ -12893,12 +12952,12 @@ func newFlowTokenTokensDepositedEventType() *cadence.EventType { Fields: []cadence.Field{ { Identifier: "amount", - Type: cadence.UFix64Type{}, + Type: cadence.UFix64Type, }, { Identifier: "to", Type: &cadence.OptionalType{ - Type: cadence.NewAddressType(), + Type: cadence.AddressType, }, }, }, @@ -12951,7 +13010,7 @@ func newFlowTokenTokensMintedEventType() *cadence.EventType { Fields: []cadence.Field{ { Identifier: "amount", - Type: cadence.UFix64Type{}, + Type: cadence.UFix64Type, }, }, } @@ -12983,12 +13042,12 @@ func newFlowTokenTokensWithdrawnEventType() *cadence.EventType { Fields: []cadence.Field{ { Identifier: "amount", - Type: cadence.UFix64Type{}, + Type: cadence.UFix64Type, }, { Identifier: "from", Type: &cadence.OptionalType{ - Type: cadence.NewAddressType(), + Type: cadence.AddressType, }, }, }, @@ -13025,15 +13084,15 @@ func newFlowIDTableStakingDelegatorRewardsPaidEventType() *cadence.EventType { Fields: []cadence.Field{ { Identifier: "nodeID", - Type: cadence.StringType{}, + Type: cadence.StringType, }, { Identifier: "delegatorID", - Type: cadence.UInt32Type{}, + Type: cadence.UInt32Type, }, { Identifier: "amount", - Type: cadence.UFix64Type{}, + Type: cadence.UFix64Type, }, }, } @@ -13069,19 +13128,19 @@ func newFlowIDTableStakingEpochTotalRewardsPaidEventType() *cadence.EventType { Fields: []cadence.Field{ { Identifier: "total", - Type: cadence.UFix64Type{}, + Type: cadence.UFix64Type, }, { Identifier: "fromFees", - Type: cadence.UFix64Type{}, + Type: cadence.UFix64Type, }, { Identifier: "minted", - Type: cadence.UFix64Type{}, + Type: cadence.UFix64Type, }, { Identifier: "feesBurned", - Type: cadence.UFix64Type{}, + Type: cadence.UFix64Type, }, }, } @@ -13119,7 +13178,7 @@ func newFlowIDTableStakingNewWeeklyPayoutEventType() *cadence.EventType { Fields: []cadence.Field{ { Identifier: "newPayout", - Type: cadence.UFix64Type{}, + Type: cadence.UFix64Type, }, }, } @@ -13151,11 +13210,11 @@ func newFlowIDTableStakingRewardsPaidEventType() *cadence.EventType { Fields: []cadence.Field{ { Identifier: "nodeID", - Type: cadence.StringType{}, + Type: cadence.StringType, }, { Identifier: "amount", - Type: cadence.UFix64Type{}, + Type: cadence.UFix64Type, }, }, } @@ -14247,13 +14306,13 @@ func TestCyclicReferenceValue(t *testing.T) { }).WithType(&cadence.VariableSizedArrayType{ ElementType: &cadence.ReferenceType{ Authorization: cadence.Unauthorized{}, - Type: cadence.AnyStructType{}, + Type: cadence.AnyStructType, }, }), }).WithType(&cadence.VariableSizedArrayType{ ElementType: &cadence.ReferenceType{ Authorization: cadence.Unauthorized{}, - Type: cadence.AnyStructType{}, + Type: cadence.AnyStructType, }, }) @@ -14359,8 +14418,8 @@ func TestSortOptions(t *testing.T) { common.NewStringLocation(nil, "test"), "Stats", []cadence.Field{ - cadence.NewField("count", cadence.NewIntType()), - cadence.NewField("sum", cadence.NewIntType()), + cadence.NewField("count", cadence.IntType), + cadence.NewField("sum", cadence.IntType), }, nil, ) @@ -14386,8 +14445,8 @@ func TestSortOptions(t *testing.T) { common.NewStringLocation(nil, "test"), "Stats", []cadence.Field{ - cadence.NewField("count", cadence.NewIntType()), - cadence.NewField("sum", cadence.NewIntType()), + cadence.NewField("count", cadence.IntType), + cadence.NewField("sum", cadence.IntType), }, nil, ) @@ -14575,8 +14634,8 @@ func TestSortOptions(t *testing.T) { common.NewStringLocation(nil, "test"), "Stats", []cadence.Field{ - cadence.NewField("sum", cadence.NewIntType()), - cadence.NewField("count", cadence.NewIntType()), + cadence.NewField("sum", cadence.IntType), + cadence.NewField("count", cadence.IntType), }, nil, ) @@ -14764,8 +14823,8 @@ func TestSortOptions(t *testing.T) { common.NewStringLocation(nil, "test"), "Stats", []cadence.Field{ - cadence.NewField("count", cadence.NewIntType()), - cadence.NewField("sum", cadence.NewIntType()), + cadence.NewField("count", cadence.IntType), + cadence.NewField("sum", cadence.IntType), }, nil, ) @@ -14953,8 +15012,8 @@ func TestSortOptions(t *testing.T) { common.NewStringLocation(nil, "test"), "Stats", []cadence.Field{ - cadence.NewField("sum", cadence.NewIntType()), - cadence.NewField("count", cadence.NewIntType()), + cadence.NewField("sum", cadence.IntType), + cadence.NewField("count", cadence.IntType), }, nil, ) diff --git a/encoding/ccf/ccf_type_id_test.go b/encoding/ccf/ccf_type_id_test.go index dd5c2fb08f..5a94ff4539 100644 --- a/encoding/ccf/ccf_type_id_test.go +++ b/encoding/ccf/ccf_type_id_test.go @@ -122,7 +122,7 @@ func simpleStructType() *cadence.StructType { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.IntType{}, + Type: cadence.IntType, }, }, } @@ -135,11 +135,11 @@ func simpleStructType2() *cadence.StructType { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.IntType{}, + Type: cadence.IntType, }, { Identifier: "b", - Type: cadence.StringType{}, + Type: cadence.StringType, }, }, } diff --git a/encoding/ccf/decode.go b/encoding/ccf/decode.go index 34980a9601..4774eea634 100644 --- a/encoding/ccf/decode.go +++ b/encoding/ccf/decode.go @@ -410,13 +410,10 @@ func (d *Decoder) decodeValue(t cadence.Type, types *cadenceTypeByCCFTypeID) (ca // If type t for the value to be decoded is a concrete type (e.g. IntType), // value MUST NOT be ccf-type-and-value-message. - switch t := t.(type) { + switch t { case cadence.VoidType: return d.decodeVoid() - case *cadence.OptionalType: - return d.decodeOptional(t, types) - case cadence.BoolType: return d.decodeBool() @@ -495,27 +492,6 @@ func (d *Decoder) decodeValue(t cadence.Type, types *cadenceTypeByCCFTypeID) (ca case cadence.UFix64Type: return d.decodeUFix64() - case *cadence.VariableSizedArrayType: - return d.decodeArray(t, false, 0, types) - - case *cadence.ConstantSizedArrayType: - return d.decodeArray(t, true, uint64(t.Size), types) - - case *cadence.DictionaryType: - return d.decodeDictionary(t, types) - - case *cadence.ResourceType: - return d.decodeResource(t, types) - - case *cadence.StructType: - return d.decodeStruct(t, types) - - case *cadence.EventType: - return d.decodeEvent(t, types) - - case *cadence.ContractType: - return d.decodeContract(t, types) - case cadence.StoragePathType: return d.decodePath() @@ -536,6 +512,32 @@ func (d *Decoder) decodeValue(t cadence.Type, types *cadenceTypeByCCFTypeID) (ca return nil, err } return cadence.NewMeteredTypeValue(d.gauge, typeValue), nil + } + + switch t := t.(type) { + case *cadence.OptionalType: + return d.decodeOptional(t, types) + + case *cadence.VariableSizedArrayType: + return d.decodeArray(t, false, 0, types) + + case *cadence.ConstantSizedArrayType: + return d.decodeArray(t, true, uint64(t.Size), types) + + case *cadence.DictionaryType: + return d.decodeDictionary(t, types) + + case *cadence.ResourceType: + return d.decodeResource(t, types) + + case *cadence.StructType: + return d.decodeStruct(t, types) + + case *cadence.EventType: + return d.decodeEvent(t, types) + + case *cadence.ContractType: + return d.decodeContract(t, types) case *cadence.CapabilityType: return d.decodeCapability(t, types) diff --git a/encoding/ccf/decode_type.go b/encoding/ccf/decode_type.go index ff35c43578..9cdd048423 100644 --- a/encoding/ccf/decode_type.go +++ b/encoding/ccf/decode_type.go @@ -109,175 +109,12 @@ func (d *Decoder) decodeSimpleTypeID() (cadence.Type, error) { return nil, err } - switch simpleTypeID { - case TypeBool: - return cadence.TheBoolType, nil - - case TypeString: - return cadence.TheStringType, nil - - case TypeCharacter: - return cadence.TheCharacterType, nil - - case TypeAddress: - return cadence.TheAddressType, nil - - case TypeInt: - return cadence.TheIntType, nil - - case TypeInt8: - return cadence.TheInt8Type, nil - - case TypeInt16: - return cadence.TheInt16Type, nil - - case TypeInt32: - return cadence.TheInt32Type, nil - - case TypeInt64: - return cadence.TheInt64Type, nil - - case TypeInt128: - return cadence.TheInt128Type, nil - - case TypeInt256: - return cadence.TheInt256Type, nil - - case TypeUInt: - return cadence.TheUIntType, nil - - case TypeUInt8: - return cadence.TheUInt8Type, nil - - case TypeUInt16: - return cadence.TheUInt16Type, nil - - case TypeUInt32: - return cadence.TheUInt32Type, nil - - case TypeUInt64: - return cadence.TheUInt64Type, nil - - case TypeUInt128: - return cadence.TheUInt128Type, nil - - case TypeUInt256: - return cadence.TheUInt256Type, nil - - case TypeWord8: - return cadence.TheWord8Type, nil - - case TypeWord16: - return cadence.TheWord16Type, nil - - case TypeWord32: - return cadence.TheWord32Type, nil - - case TypeWord64: - return cadence.TheWord64Type, nil - - case TypeWord128: - return cadence.TheWord128Type, nil - - case TypeWord256: - return cadence.TheWord256Type, nil - - case TypeFix64: - return cadence.TheFix64Type, nil - - case TypeUFix64: - return cadence.TheUFix64Type, nil - - case TypePath: - return cadence.ThePathType, nil - - case TypeCapabilityPath: - return cadence.TheCapabilityPathType, nil - - case TypeStoragePath: - return cadence.TheStoragePathType, nil - - case TypePublicPath: - return cadence.ThePublicPathType, nil - - case TypePrivatePath: - return cadence.ThePrivatePathType, nil - - case TypeAuthAccount: - return cadence.TheAuthAccountType, nil - - case TypePublicAccount: - return cadence.ThePublicAccountType, nil - - case TypeAuthAccountKeys: - return cadence.TheAuthAccountKeysType, nil - - case TypePublicAccountKeys: - return cadence.ThePublicAccountKeysType, nil - - case TypeAuthAccountContracts: - return cadence.TheAuthAccountContractsType, nil - - case TypePublicAccountContracts: - return cadence.ThePublicAccountContractsType, nil - - case TypeDeployedContract: - return cadence.TheDeployedContractType, nil - - case TypeAccountKey: - return cadence.TheAccountKeyType, nil - - case TypeBlock: - return cadence.TheBlockType, nil - - case TypeAny: - return cadence.TheAnyType, nil - - case TypeAnyStruct: - return cadence.TheAnyStructType, nil - - case TypeAnyResource: - return cadence.TheAnyResourceType, nil - - case TypeMetaType: - return cadence.TheMetaType, nil - - case TypeNever: - return cadence.TheNeverType, nil - - case TypeNumber: - return cadence.TheNumberType, nil - - case TypeSignedNumber: - return cadence.TheSignedNumberType, nil - - case TypeInteger: - return cadence.TheIntegerType, nil - - case TypeSignedInteger: - return cadence.TheSignedIntegerType, nil - - case TypeFixedPoint: - return cadence.TheFixedPointType, nil - - case TypeSignedFixedPoint: - return cadence.TheSignedFixedPointType, nil - - case TypeBytes: - return cadence.TheBytesType, nil - - case TypeVoid: - return cadence.TheVoidType, nil - - case TypeAnyStructAttachmentType: - return cadence.TheAnyStructAttachmentType, nil - - case TypeAnyResourceAttachmentType: - return cadence.TheAnyResourceAttachmentType, nil - - default: + ty := typeBySimpleTypeID(SimpleType(simpleTypeID)) + if ty == nil { return nil, fmt.Errorf("unsupported encoded simple type ID %d", simpleTypeID) } + + return ty, nil } // decodeOptionalType decodes optional-type or optional-type-value as diff --git a/encoding/ccf/encode.go b/encoding/ccf/encode.go index e72c8b3642..f3fa139021 100644 --- a/encoding/ccf/encode.go +++ b/encoding/ccf/encode.go @@ -1305,9 +1305,9 @@ func (e *Encoder) encodeTypeValueRef(id ccfTypeID) error { // // ; cbor-tag-simple-type-value // #6.185(simple-type-id) -func (e *Encoder) encodeSimpleTypeValue(id uint64) error { +func (e *Encoder) encodeSimpleTypeValue(id SimpleType) error { rawTagNum := []byte{0xd8, CBORTagSimpleTypeValue} - return e.encodeSimpleTypeWithRawTag(id, rawTagNum) + return e.encodeSimpleTypeWithRawTag(uint64(id), rawTagNum) } // encodeOptionalTypeValue encodes cadence.OptionalType as @@ -2015,9 +2015,10 @@ func isOptionalNeverType(t cadence.Type) bool { return false } - if ot.Type.Equal(cadence.NewNeverType()) { + if ot.Type.Equal(cadence.NeverType) { return true } + t = ot.Type } } diff --git a/encoding/ccf/encode_type.go b/encoding/ccf/encode_type.go index 70f8bc0966..970784e846 100644 --- a/encoding/ccf/encode_type.go +++ b/encoding/ccf/encode_type.go @@ -79,7 +79,7 @@ func (e *Encoder) encodeInlineType(typ cadence.Type, tids ccfTypeIDByCadenceType return e.encodeCapabilityType(typ, tids) case *cadence.FunctionType: - return e.encodeSimpleType(TypeFunction) + return e.encodeSimpleType(SimpleTypeFunction) default: panic(cadenceErrors.NewUnexpectedError("unsupported type %s (%T)", typ.ID(), typ)) @@ -99,9 +99,9 @@ func (e *Encoder) encodeNullableInlineType(typ cadence.Type, tids ccfTypeIDByCad // // ; cbor-tag-simple-type // #6.137(simple-type-id) -func (e *Encoder) encodeSimpleType(id uint64) error { +func (e *Encoder) encodeSimpleType(id SimpleType) error { rawTagNum := []byte{0xd8, CBORTagSimpleType} - return e.encodeSimpleTypeWithRawTag(id, rawTagNum) + return e.encodeSimpleTypeWithRawTag(uint64(id), rawTagNum) } // encodeSimpleTypeWithRawTag encodes simple type with given tag number as diff --git a/encoding/ccf/service_events_test.go b/encoding/ccf/service_events_test.go index bbabd721d8..b2ba61358a 100644 --- a/encoding/ccf/service_events_test.go +++ b/encoding/ccf/service_events_test.go @@ -584,7 +584,7 @@ func createEpochNodes() cadence.Array { ufix64FromString("0.00000000"), // delegators - cadence.NewArray([]cadence.Value{}).WithType(cadence.NewVariableSizedArrayType(cadence.NewUInt32Type())), + cadence.NewArray([]cadence.Value{}).WithType(cadence.NewVariableSizedArrayType(cadence.UInt32Type)), // delegatorIDCounter cadence.UInt32(0), @@ -628,7 +628,7 @@ func createEpochNodes() cadence.Array { ufix64FromString("0.00000000"), // delegators - cadence.NewArray([]cadence.Value{}).WithType(cadence.NewVariableSizedArrayType(cadence.NewUInt32Type())), + cadence.NewArray([]cadence.Value{}).WithType(cadence.NewVariableSizedArrayType(cadence.UInt32Type)), // delegatorIDCounter cadence.UInt32(0), @@ -672,7 +672,7 @@ func createEpochNodes() cadence.Array { ufix64FromString("0.00000000"), // delegators - cadence.NewArray([]cadence.Value{}).WithType(cadence.NewVariableSizedArrayType(cadence.NewUInt32Type())), + cadence.NewArray([]cadence.Value{}).WithType(cadence.NewVariableSizedArrayType(cadence.UInt32Type)), // delegatorIDCounter cadence.UInt32(0), @@ -716,7 +716,7 @@ func createEpochNodes() cadence.Array { ufix64FromString("0.00000000"), // delegators - cadence.NewArray([]cadence.Value{}).WithType(cadence.NewVariableSizedArrayType(cadence.NewUInt32Type())), + cadence.NewArray([]cadence.Value{}).WithType(cadence.NewVariableSizedArrayType(cadence.UInt32Type)), // delegatorIDCounter cadence.UInt32(0), @@ -760,7 +760,7 @@ func createEpochNodes() cadence.Array { ufix64FromString("0.00000000"), // delegators - cadence.NewArray([]cadence.Value{}).WithType(cadence.NewVariableSizedArrayType(cadence.NewUInt32Type())), + cadence.NewArray([]cadence.Value{}).WithType(cadence.NewVariableSizedArrayType(cadence.UInt32Type)), // delegatorIDCounter cadence.UInt32(0), @@ -804,7 +804,7 @@ func createEpochNodes() cadence.Array { ufix64FromString("0.00000000"), // delegators - cadence.NewArray([]cadence.Value{}).WithType(cadence.NewVariableSizedArrayType(cadence.NewUInt32Type())), + cadence.NewArray([]cadence.Value{}).WithType(cadence.NewVariableSizedArrayType(cadence.UInt32Type)), // delegatorIDCounter cadence.UInt32(0), @@ -848,7 +848,7 @@ func createEpochNodes() cadence.Array { ufix64FromString("0.00000000"), // delegators - cadence.NewArray([]cadence.Value{}).WithType(cadence.NewVariableSizedArrayType(cadence.NewUInt32Type())), + cadence.NewArray([]cadence.Value{}).WithType(cadence.NewVariableSizedArrayType(cadence.UInt32Type)), // delegatorIDCounter cadence.UInt32(0), @@ -891,16 +891,16 @@ func createEpochCollectors() cadence.Array { Key: cadence.String("0000000000000000000000000000000000000000000000000000000000000002"), Value: cadence.UInt64(100), }, - }).WithType(cadence.NewMeteredDictionaryType(nil, cadence.StringType{}, cadence.UInt64Type{})), + }).WithType(cadence.NewMeteredDictionaryType(nil, cadence.StringType, cadence.UInt64Type)), // totalWeight cadence.NewUInt64(100), // generatedVotes - cadence.NewDictionary(nil).WithType(cadence.NewDictionaryType(cadence.StringType{}, voteType)), + cadence.NewDictionary(nil).WithType(cadence.NewDictionaryType(cadence.StringType, voteType)), // uniqueVoteMessageTotalWeights - cadence.NewDictionary(nil).WithType(cadence.NewDictionaryType(cadence.StringType{}, cadence.UInt64Type{})), + cadence.NewDictionary(nil).WithType(cadence.NewDictionaryType(cadence.StringType, cadence.UInt64Type)), }).WithType(clusterType) cluster2 := cadence.NewStruct([]cadence.Value{ @@ -917,16 +917,16 @@ func createEpochCollectors() cadence.Array { Key: cadence.String("0000000000000000000000000000000000000000000000000000000000000004"), Value: cadence.UInt64(100), }, - }).WithType(cadence.NewMeteredDictionaryType(nil, cadence.StringType{}, cadence.UInt64Type{})), + }).WithType(cadence.NewMeteredDictionaryType(nil, cadence.StringType, cadence.UInt64Type)), // totalWeight cadence.NewUInt64(0), // generatedVotes - cadence.NewDictionary(nil).WithType(cadence.NewDictionaryType(cadence.StringType{}, voteType)), + cadence.NewDictionary(nil).WithType(cadence.NewDictionaryType(cadence.StringType, voteType)), // uniqueVoteMessageTotalWeights - cadence.NewDictionary(nil).WithType(cadence.NewDictionaryType(cadence.StringType{}, cadence.UInt64Type{})), + cadence.NewDictionary(nil).WithType(cadence.NewDictionaryType(cadence.StringType, cadence.UInt64Type)), }).WithType(clusterType) return cadence.NewArray([]cadence.Value{ @@ -947,7 +947,7 @@ func createEpochCommittedEvent() cadence.Event { cadence.NewArray([]cadence.Value{ cadence.String("a39cd1e1bf7e2fb0609b7388ce5215a6a4c01eef2aee86e1a007faa28a6b2a3dc876e11bb97cdb26c3846231d2d01e4d"), cadence.String("91673ad9c717d396c9a0953617733c128049ac1a639653d4002ab245b121df1939430e313bcbfd06948f6a281f6bf853"), - }).WithType(cadence.NewVariableSizedArrayType(cadence.StringType{})), + }).WithType(cadence.NewVariableSizedArrayType(cadence.StringType)), // voteMessage cadence.String("irrelevant_for_these_purposes"), @@ -956,7 +956,7 @@ func createEpochCommittedEvent() cadence.Event { cadence.NewArray([]cadence.Value{ cadence.String("0000000000000000000000000000000000000000000000000000000000000001"), cadence.String("0000000000000000000000000000000000000000000000000000000000000002"), - }).WithType(cadence.NewVariableSizedArrayType(cadence.StringType{})), + }).WithType(cadence.NewVariableSizedArrayType(cadence.StringType)), }).WithType(clusterQCType) cluster2 := cadence.NewStruct([]cadence.Value{ @@ -967,7 +967,7 @@ func createEpochCommittedEvent() cadence.Event { cadence.NewArray([]cadence.Value{ cadence.String("b2bff159971852ed63e72c37991e62c94822e52d4fdcd7bf29aaf9fb178b1c5b4ce20dd9594e029f3574cb29533b857a"), cadence.String("9931562f0248c9195758da3de4fb92f24fa734cbc20c0cb80280163560e0e0348f843ac89ecbd3732e335940c1e8dccb"), - }).WithType(cadence.NewVariableSizedArrayType(cadence.StringType{})), + }).WithType(cadence.NewVariableSizedArrayType(cadence.StringType)), // voteMessage cadence.String("irrelevant_for_these_purposes"), @@ -976,7 +976,7 @@ func createEpochCommittedEvent() cadence.Event { cadence.NewArray([]cadence.Value{ cadence.String("0000000000000000000000000000000000000000000000000000000000000003"), cadence.String("0000000000000000000000000000000000000000000000000000000000000004"), - }).WithType(cadence.NewVariableSizedArrayType(cadence.StringType{})), + }).WithType(cadence.NewVariableSizedArrayType(cadence.StringType)), }).WithType(clusterQCType) return cadence.NewEvent([]cadence.Value{ @@ -993,7 +993,7 @@ func createEpochCommittedEvent() cadence.Event { cadence.NewArray([]cadence.Value{ cadence.String("8c588266db5f5cda629e83f8aa04ae9413593fac19e4865d06d291c9d14fbdd9bdb86a7a12f9ef8590c79cb635e3163315d193087e9336092987150d0cd2b14ac6365f7dc93eec573752108b8c12368abb65f0652d9f644e5aed611c37926950"), cadence.String("87a339e4e5c74f089da20a33f515d8c8f4464ab53ede5a74aa2432cd1ae66d522da0c122249ee176cd747ddc83ca81090498389384201614caf51eac392c1c0a916dfdcfbbdf7363f9552b6468434add3d3f6dc91a92bbe3ee368b59b7828488"), - }).WithType(cadence.NewVariableSizedArrayType(cadence.StringType{})), + }).WithType(cadence.NewVariableSizedArrayType(cadence.StringType)), }).WithType(newFlowEpochEpochCommittedEventType()) } @@ -1048,23 +1048,23 @@ func newFlowClusterQCVoteStructType() cadence.Type { Fields: []cadence.Field{ { Identifier: "nodeID", - Type: cadence.StringType{}, + Type: cadence.StringType, }, { Identifier: "signature", - Type: cadence.NewOptionalType(cadence.StringType{}), + Type: cadence.NewOptionalType(cadence.StringType), }, { Identifier: "message", - Type: cadence.NewOptionalType(cadence.StringType{}), + Type: cadence.NewOptionalType(cadence.StringType), }, { Identifier: "clusterIndex", - Type: cadence.UInt16Type{}, + Type: cadence.UInt16Type, }, { Identifier: "weight", - Type: cadence.UInt64Type{}, + Type: cadence.UInt64Type, }, }, } @@ -1083,23 +1083,23 @@ func newFlowClusterQCClusterStructType() *cadence.StructType { Fields: []cadence.Field{ { Identifier: "index", - Type: cadence.UInt16Type{}, + Type: cadence.UInt16Type, }, { Identifier: "nodeWeights", - Type: cadence.NewDictionaryType(cadence.StringType{}, cadence.UInt64Type{}), + Type: cadence.NewDictionaryType(cadence.StringType, cadence.UInt64Type), }, { Identifier: "totalWeight", - Type: cadence.UInt64Type{}, + Type: cadence.UInt64Type, }, { Identifier: "generatedVotes", - Type: cadence.NewDictionaryType(cadence.StringType{}, newFlowClusterQCVoteStructType()), + Type: cadence.NewDictionaryType(cadence.StringType, newFlowClusterQCVoteStructType()), }, { Identifier: "uniqueVoteMessageTotalWeights", - Type: cadence.NewDictionaryType(cadence.StringType{}, cadence.UInt64Type{}), + Type: cadence.NewDictionaryType(cadence.StringType, cadence.UInt64Type), }, }, } @@ -1118,59 +1118,59 @@ func newFlowIDTableStakingNodeInfoStructType() *cadence.StructType { Fields: []cadence.Field{ { Identifier: "id", - Type: cadence.StringType{}, + Type: cadence.StringType, }, { Identifier: "role", - Type: cadence.UInt8Type{}, + Type: cadence.UInt8Type, }, { Identifier: "networkingAddress", - Type: cadence.StringType{}, + Type: cadence.StringType, }, { Identifier: "networkingKey", - Type: cadence.StringType{}, + Type: cadence.StringType, }, { Identifier: "stakingKey", - Type: cadence.StringType{}, + Type: cadence.StringType, }, { Identifier: "tokensStaked", - Type: cadence.UFix64Type{}, + Type: cadence.UFix64Type, }, { Identifier: "tokensCommitted", - Type: cadence.UFix64Type{}, + Type: cadence.UFix64Type, }, { Identifier: "tokensUnstaking", - Type: cadence.UFix64Type{}, + Type: cadence.UFix64Type, }, { Identifier: "tokensUnstaked", - Type: cadence.UFix64Type{}, + Type: cadence.UFix64Type, }, { Identifier: "tokensRewarded", - Type: cadence.UFix64Type{}, + Type: cadence.UFix64Type, }, { Identifier: "delegators", - Type: cadence.NewVariableSizedArrayType(cadence.NewUInt32Type()), + Type: cadence.NewVariableSizedArrayType(cadence.UInt32Type), }, { Identifier: "delegatorIDCounter", - Type: cadence.UInt32Type{}, + Type: cadence.UInt32Type, }, { Identifier: "tokensRequestedToUnstake", - Type: cadence.UFix64Type{}, + Type: cadence.UFix64Type, }, { Identifier: "initialWeight", - Type: cadence.UInt64Type{}, + Type: cadence.UInt64Type, }, }, } @@ -1189,7 +1189,7 @@ func newFlowEpochEpochSetupEventType() *cadence.EventType { Fields: []cadence.Field{ { Identifier: "counter", - Type: cadence.UInt64Type{}, + Type: cadence.UInt64Type, }, { Identifier: "nodeInfo", @@ -1197,11 +1197,11 @@ func newFlowEpochEpochSetupEventType() *cadence.EventType { }, { Identifier: "firstView", - Type: cadence.UInt64Type{}, + Type: cadence.UInt64Type, }, { Identifier: "finalView", - Type: cadence.UInt64Type{}, + Type: cadence.UInt64Type, }, { Identifier: "collectorClusters", @@ -1209,19 +1209,19 @@ func newFlowEpochEpochSetupEventType() *cadence.EventType { }, { Identifier: "randomSource", - Type: cadence.StringType{}, + Type: cadence.StringType, }, { Identifier: "DKGPhase1FinalView", - Type: cadence.UInt64Type{}, + Type: cadence.UInt64Type, }, { Identifier: "DKGPhase2FinalView", - Type: cadence.UInt64Type{}, + Type: cadence.UInt64Type, }, { Identifier: "DKGPhase3FinalView", - Type: cadence.UInt64Type{}, + Type: cadence.UInt64Type, }, }, } @@ -1240,7 +1240,7 @@ func newFlowEpochEpochCommittedEventType() *cadence.EventType { Fields: []cadence.Field{ { Identifier: "counter", - Type: cadence.UInt64Type{}, + Type: cadence.UInt64Type, }, { Identifier: "clusterQCs", @@ -1248,7 +1248,7 @@ func newFlowEpochEpochCommittedEventType() *cadence.EventType { }, { Identifier: "dkgPubKeys", - Type: cadence.NewVariableSizedArrayType(cadence.StringType{}), + Type: cadence.NewVariableSizedArrayType(cadence.StringType), }, }, } @@ -1267,19 +1267,19 @@ func newFlowClusterQCClusterQCStructType() *cadence.StructType { Fields: []cadence.Field{ { Identifier: "index", - Type: cadence.UInt16Type{}, + Type: cadence.UInt16Type, }, { Identifier: "voteSignatures", - Type: cadence.NewVariableSizedArrayType(cadence.StringType{}), + Type: cadence.NewVariableSizedArrayType(cadence.StringType), }, { Identifier: "voteMessage", - Type: cadence.StringType{}, + Type: cadence.StringType, }, { Identifier: "voterIDs", - Type: cadence.NewVariableSizedArrayType(cadence.StringType{}), + Type: cadence.NewVariableSizedArrayType(cadence.StringType), }, }, } @@ -1302,7 +1302,7 @@ func newNodeVersionBeaconVersionBeaconEventType() *cadence.EventType { }, { Identifier: "sequence", - Type: cadence.UInt64Type{}, + Type: cadence.UInt64Type, }, }, } @@ -1321,7 +1321,7 @@ func newNodeVersionBeaconVersionBoundaryStructType() *cadence.StructType { Fields: []cadence.Field{ { Identifier: "blockHeight", - Type: cadence.UInt64Type{}, + Type: cadence.UInt64Type, }, { Identifier: "version", @@ -1344,19 +1344,19 @@ func newNodeVersionBeaconSemverStructType() *cadence.StructType { Fields: []cadence.Field{ { Identifier: "preRelease", - Type: cadence.NewOptionalType(cadence.StringType{}), + Type: cadence.NewOptionalType(cadence.StringType), }, { Identifier: "major", - Type: cadence.UInt8Type{}, + Type: cadence.UInt8Type, }, { Identifier: "minor", - Type: cadence.UInt8Type{}, + Type: cadence.UInt8Type, }, { Identifier: "patch", - Type: cadence.UInt8Type{}, + Type: cadence.UInt8Type, }, }, } diff --git a/encoding/ccf/simple_type_utils.go b/encoding/ccf/simple_type_utils.go deleted file mode 100644 index 1f28866fd5..0000000000 --- a/encoding/ccf/simple_type_utils.go +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Cadence - The resource-oriented smart contract programming language - * - * Copyright Dapper Labs, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ccf - -import "github.com/onflow/cadence" - -// IMPORTANT: -// -// Don't change existing simple type IDs. -// -// When new simple cadence.Type is added, -// - add new ID to the end of existing IDs, -// - add new simple cadence.Type and its ID in simpleTypeIDByType() - -const ( // Cadence simple type IDs - TypeBool = iota - TypeString - TypeCharacter - TypeAddress - TypeInt - TypeInt8 - TypeInt16 - TypeInt32 - TypeInt64 - TypeInt128 - TypeInt256 - TypeUInt - TypeUInt8 - TypeUInt16 - TypeUInt32 - TypeUInt64 - TypeUInt128 - TypeUInt256 - TypeWord8 - TypeWord16 - TypeWord32 - TypeWord64 - TypeFix64 - TypeUFix64 - TypePath - TypeCapabilityPath - TypeStoragePath - TypePublicPath - TypePrivatePath - TypeAuthAccount - TypePublicAccount - TypeAuthAccountKeys - TypePublicAccountKeys - TypeAuthAccountContracts - TypePublicAccountContracts - TypeDeployedContract - TypeAccountKey - TypeBlock - TypeAny - TypeAnyStruct - TypeAnyResource - TypeMetaType - TypeNever - TypeNumber - TypeSignedNumber - TypeInteger - TypeSignedInteger - TypeFixedPoint - TypeSignedFixedPoint - TypeBytes - TypeVoid - TypeFunction - TypeWord128 - TypeWord256 - TypeAnyStructAttachmentType - TypeAnyResourceAttachmentType -) - -// NOTE: cadence.FunctionType isn't included in simpleTypeIDByType -// because this function is used by both inline-type and type-value. -// cadence.FunctionType needs to be handled differently when this -// function is used by inline-type and type-value. -func simpleTypeIDByType(typ cadence.Type) (uint64, bool) { - switch typ.(type) { - case cadence.AnyType: - return TypeAny, true - - case cadence.AnyStructType: - return TypeAnyStruct, true - - case cadence.AnyResourceType: - return TypeAnyResource, true - - case cadence.AddressType: - return TypeAddress, true - - case cadence.MetaType: - return TypeMetaType, true - - case cadence.VoidType: - return TypeVoid, true - - case cadence.NeverType: - return TypeNever, true - - case cadence.BoolType: - return TypeBool, true - - case cadence.StringType: - return TypeString, true - - case cadence.CharacterType: - return TypeCharacter, true - - case cadence.BytesType: - return TypeBytes, true - - case cadence.NumberType: - return TypeNumber, true - - case cadence.SignedNumberType: - return TypeSignedNumber, true - - case cadence.IntegerType: - return TypeInteger, true - - case cadence.SignedIntegerType: - return TypeSignedInteger, true - - case cadence.FixedPointType: - return TypeFixedPoint, true - - case cadence.SignedFixedPointType: - return TypeSignedFixedPoint, true - - case cadence.IntType: - return TypeInt, true - - case cadence.Int8Type: - return TypeInt8, true - - case cadence.Int16Type: - return TypeInt16, true - - case cadence.Int32Type: - return TypeInt32, true - - case cadence.Int64Type: - return TypeInt64, true - - case cadence.Int128Type: - return TypeInt128, true - - case cadence.Int256Type: - return TypeInt256, true - - case cadence.UIntType: - return TypeUInt, true - - case cadence.UInt8Type: - return TypeUInt8, true - - case cadence.UInt16Type: - return TypeUInt16, true - - case cadence.UInt32Type: - return TypeUInt32, true - - case cadence.UInt64Type: - return TypeUInt64, true - - case cadence.UInt128Type: - return TypeUInt128, true - - case cadence.UInt256Type: - return TypeUInt256, true - - case cadence.Word8Type: - return TypeWord8, true - - case cadence.Word16Type: - return TypeWord16, true - - case cadence.Word32Type: - return TypeWord32, true - - case cadence.Word64Type: - return TypeWord64, true - - case cadence.Word128Type: - return TypeWord128, true - - case cadence.Word256Type: - return TypeWord256, true - - case cadence.Fix64Type: - return TypeFix64, true - - case cadence.UFix64Type: - return TypeUFix64, true - - case cadence.BlockType: - return TypeBlock, true - - case cadence.PathType: - return TypePath, true - - case cadence.CapabilityPathType: - return TypeCapabilityPath, true - - case cadence.StoragePathType: - return TypeStoragePath, true - - case cadence.PublicPathType: - return TypePublicPath, true - - case cadence.PrivatePathType: - return TypePrivatePath, true - - case cadence.AccountKeyType: - return TypeAccountKey, true - - case cadence.AuthAccountContractsType: - return TypeAuthAccountContracts, true - - case cadence.AuthAccountKeysType: - return TypeAuthAccountKeys, true - - case cadence.AuthAccountType: - return TypeAuthAccount, true - - case cadence.PublicAccountContractsType: - return TypePublicAccountContracts, true - - case cadence.PublicAccountKeysType: - return TypePublicAccountKeys, true - - case cadence.PublicAccountType: - return TypePublicAccount, true - - case cadence.DeployedContractType: - return TypeDeployedContract, true - - case cadence.AnyStructAttachmentType: - return TypeAnyStructAttachmentType, true - - case cadence.AnyResourceAttachmentType: - return TypeAnyResourceAttachmentType, true - } - - return 0, false -} diff --git a/encoding/ccf/simpletype.go b/encoding/ccf/simpletype.go new file mode 100644 index 0000000000..67c57f55d2 --- /dev/null +++ b/encoding/ccf/simpletype.go @@ -0,0 +1,516 @@ +/* + * Cadence - The resource-oriented smart contract programming language + * + * Copyright Dapper Labs, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ccf + +//go:generate go run golang.org/x/tools/cmd/stringer -type=SimpleType + +import "github.com/onflow/cadence" + +// Simple type ID is a compact representation of a type +// which doesn't need additional information. + +// IMPORTANT: +// +// Don't change existing simple type IDs. +// +// When new simple cadence.Type is added, +// - ADD new ID to the end of existing IDs, +// - ADD new simple cadence.Type and its ID +// to simpleTypeIDByType *and* typeBySimpleTypeID + +type SimpleType uint64 + +const ( // Cadence simple type IDs + SimpleTypeBool SimpleType = iota + SimpleTypeString + SimpleTypeCharacter + SimpleTypeAddress + SimpleTypeInt + SimpleTypeInt8 + SimpleTypeInt16 + SimpleTypeInt32 + SimpleTypeInt64 + SimpleTypeInt128 + SimpleTypeInt256 + SimpleTypeUInt + SimpleTypeUInt8 + SimpleTypeUInt16 + SimpleTypeUInt32 + SimpleTypeUInt64 + SimpleTypeUInt128 + SimpleTypeUInt256 + SimpleTypeWord8 + SimpleTypeWord16 + SimpleTypeWord32 + SimpleTypeWord64 + SimpleTypeFix64 + SimpleTypeUFix64 + SimpleTypePath + SimpleTypeCapabilityPath + SimpleTypeStoragePath + SimpleTypePublicPath + SimpleTypePrivatePath + _ // DO NOT REUSE: was AuthAccount + _ // DO NOT REUSE: was PublicAccount + _ // DO NOT REUSE: was AuthAccountKeys + _ // DO NOT REUSE: was PublicAccountKeys + _ // DO NOT REUSE: was AuthAccountContracts + _ // DO NOT REUSE: was PublicAccountContracts + SimpleTypeDeployedContract + _ // DO NOT REUSE: was AccountKey + SimpleTypeBlock + SimpleTypeAny + SimpleTypeAnyStruct + SimpleTypeAnyResource + SimpleTypeMetaType + SimpleTypeNever + SimpleTypeNumber + SimpleTypeSignedNumber + SimpleTypeInteger + SimpleTypeSignedInteger + SimpleTypeFixedPoint + SimpleTypeSignedFixedPoint + SimpleTypeBytes + SimpleTypeVoid + SimpleTypeFunction + SimpleTypeWord128 + SimpleTypeWord256 + SimpleTypeAnyStructAttachmentType + SimpleTypeAnyResourceAttachmentType + SimpleTypeStorageCapabilityController + SimpleTypeAccountCapabilityController + SimpleTypeAccount + SimpleTypeAccount_Contracts + SimpleTypeAccount_Keys + SimpleTypeAccount_Inbox + SimpleTypeAccount_StorageCapabilities + SimpleTypeAccount_AccountCapabilities + SimpleTypeAccount_Capabilities + SimpleTypeAccount_Storage + SimpleTypeMutate + SimpleTypeInsert + SimpleTypeRemove + SimpleTypeIdentity + SimpleTypeStorage + SimpleTypeSaveValue + SimpleTypeLoadValue + SimpleTypeBorrowValue + SimpleTypeContracts + SimpleTypeAddContract + SimpleTypeUpdateContract + SimpleTypeRemoveContract + SimpleTypeKeys + SimpleTypeAddKey + SimpleTypeRevokeKey + SimpleTypeInbox + SimpleTypePublishInboxCapability + SimpleTypeUnpublishInboxCapability + SimpleTypeClaimInboxCapability + SimpleTypeCapabilities + SimpleTypeStorageCapabilities + SimpleTypeAccountCapabilities + SimpleTypePublishCapability + SimpleTypeUnpublishCapability + SimpleTypeGetStorageCapabilityController + SimpleTypeIssueStorageCapabilityController + SimpleTypeGetAccountCapabilityController + SimpleTypeIssueAccountCapabilityController + SimpleTypeCapabilitiesMapping + SimpleTypeAccountMapping + + // !!! *WARNING* !!! + // ADD NEW TYPES *BEFORE* THIS WARNING. + // DO *NOT* ADD NEW TYPES AFTER THIS LINE! + SimpleType_Count +) + +// NOTE: cadence.FunctionType isn't included in simpleTypeIDByType +// because this function is used by both inline-type and type-value. +// cadence.FunctionType needs to be handled differently when this +// function is used by inline-type and type-value. +func simpleTypeIDByType(typ cadence.Type) (SimpleType, bool) { + + switch typ { + case cadence.AnyType: + return SimpleTypeAny, true + case cadence.AnyStructType: + return SimpleTypeAnyStruct, true + case cadence.AnyResourceType: + return SimpleTypeAnyResource, true + case cadence.AddressType: + return SimpleTypeAddress, true + case cadence.MetaType: + return SimpleTypeMetaType, true + case cadence.VoidType: + return SimpleTypeVoid, true + case cadence.NeverType: + return SimpleTypeNever, true + case cadence.BoolType: + return SimpleTypeBool, true + case cadence.StringType: + return SimpleTypeString, true + case cadence.CharacterType: + return SimpleTypeCharacter, true + case cadence.NumberType: + return SimpleTypeNumber, true + case cadence.SignedNumberType: + return SimpleTypeSignedNumber, true + case cadence.IntegerType: + return SimpleTypeInteger, true + case cadence.SignedIntegerType: + return SimpleTypeSignedInteger, true + case cadence.FixedPointType: + return SimpleTypeFixedPoint, true + case cadence.SignedFixedPointType: + return SimpleTypeSignedFixedPoint, true + case cadence.IntType: + return SimpleTypeInt, true + case cadence.Int8Type: + return SimpleTypeInt8, true + case cadence.Int16Type: + return SimpleTypeInt16, true + case cadence.Int32Type: + return SimpleTypeInt32, true + case cadence.Int64Type: + return SimpleTypeInt64, true + case cadence.Int128Type: + return SimpleTypeInt128, true + case cadence.Int256Type: + return SimpleTypeInt256, true + case cadence.UIntType: + return SimpleTypeUInt, true + case cadence.UInt8Type: + return SimpleTypeUInt8, true + case cadence.UInt16Type: + return SimpleTypeUInt16, true + case cadence.UInt32Type: + return SimpleTypeUInt32, true + case cadence.UInt64Type: + return SimpleTypeUInt64, true + case cadence.UInt128Type: + return SimpleTypeUInt128, true + case cadence.UInt256Type: + return SimpleTypeUInt256, true + case cadence.Word8Type: + return SimpleTypeWord8, true + case cadence.Word16Type: + return SimpleTypeWord16, true + case cadence.Word32Type: + return SimpleTypeWord32, true + case cadence.Word64Type: + return SimpleTypeWord64, true + case cadence.Word128Type: + return SimpleTypeWord128, true + case cadence.Word256Type: + return SimpleTypeWord256, true + case cadence.Fix64Type: + return SimpleTypeFix64, true + case cadence.UFix64Type: + return SimpleTypeUFix64, true + case cadence.BlockType: + return SimpleTypeBlock, true + case cadence.PathType: + return SimpleTypePath, true + case cadence.CapabilityPathType: + return SimpleTypeCapabilityPath, true + case cadence.StoragePathType: + return SimpleTypeStoragePath, true + case cadence.PublicPathType: + return SimpleTypePublicPath, true + case cadence.PrivatePathType: + return SimpleTypePrivatePath, true + case cadence.DeployedContractType: + return SimpleTypeDeployedContract, true + case cadence.AnyStructAttachmentType: + return SimpleTypeAnyStructAttachmentType, true + case cadence.AnyResourceAttachmentType: + return SimpleTypeAnyResourceAttachmentType, true + case cadence.StorageCapabilityControllerType: + return SimpleTypeStorageCapabilityController, true + case cadence.AccountCapabilityControllerType: + return SimpleTypeAccountCapabilityController, true + case cadence.AccountType: + return SimpleTypeAccount, true + case cadence.Account_ContractsType: + return SimpleTypeAccount_Contracts, true + case cadence.Account_KeysType: + return SimpleTypeAccount_Keys, true + case cadence.Account_InboxType: + return SimpleTypeAccount_Inbox, true + case cadence.Account_StorageCapabilitiesType: + return SimpleTypeAccount_StorageCapabilities, true + case cadence.Account_AccountCapabilitiesType: + return SimpleTypeAccount_AccountCapabilities, true + case cadence.Account_CapabilitiesType: + return SimpleTypeAccount_Capabilities, true + case cadence.Account_StorageType: + return SimpleTypeAccount_Storage, true + case cadence.MutateType: + return SimpleTypeMutate, true + case cadence.InsertType: + return SimpleTypeInsert, true + case cadence.RemoveType: + return SimpleTypeRemove, true + case cadence.IdentityType: + return SimpleTypeIdentity, true + case cadence.StorageType: + return SimpleTypeStorage, true + case cadence.SaveValueType: + return SimpleTypeSaveValue, true + case cadence.LoadValueType: + return SimpleTypeLoadValue, true + case cadence.BorrowValueType: + return SimpleTypeBorrowValue, true + case cadence.ContractsType: + return SimpleTypeContracts, true + case cadence.AddContractType: + return SimpleTypeAddContract, true + case cadence.UpdateContractType: + return SimpleTypeUpdateContract, true + case cadence.RemoveContractType: + return SimpleTypeRemoveContract, true + case cadence.KeysType: + return SimpleTypeKeys, true + case cadence.AddKeyType: + return SimpleTypeAddKey, true + case cadence.RevokeKeyType: + return SimpleTypeRevokeKey, true + case cadence.InboxType: + return SimpleTypeInbox, true + case cadence.PublishInboxCapabilityType: + return SimpleTypePublishInboxCapability, true + case cadence.UnpublishInboxCapabilityType: + return SimpleTypeUnpublishInboxCapability, true + case cadence.ClaimInboxCapabilityType: + return SimpleTypeClaimInboxCapability, true + case cadence.CapabilitiesType: + return SimpleTypeCapabilities, true + case cadence.StorageCapabilitiesType: + return SimpleTypeStorageCapabilities, true + case cadence.AccountCapabilitiesType: + return SimpleTypeAccountCapabilities, true + case cadence.PublishCapabilityType: + return SimpleTypePublishCapability, true + case cadence.UnpublishCapabilityType: + return SimpleTypeUnpublishCapability, true + case cadence.GetStorageCapabilityControllerType: + return SimpleTypeGetStorageCapabilityController, true + case cadence.IssueStorageCapabilityControllerType: + return SimpleTypeIssueStorageCapabilityController, true + case cadence.GetAccountCapabilityControllerType: + return SimpleTypeGetAccountCapabilityController, true + case cadence.IssueAccountCapabilityControllerType: + return SimpleTypeIssueAccountCapabilityController, true + case cadence.CapabilitiesMappingType: + return SimpleTypeCapabilitiesMapping, true + case cadence.AccountMappingType: + return SimpleTypeAccountMapping, true + + } + + switch typ.(type) { + case cadence.BytesType: + return SimpleTypeBytes, true + } + + return 0, false +} + +func typeBySimpleTypeID(simpleTypeID SimpleType) cadence.Type { + switch simpleTypeID { + case SimpleTypeBool: + return cadence.BoolType + case SimpleTypeString: + return cadence.StringType + case SimpleTypeCharacter: + return cadence.CharacterType + case SimpleTypeAddress: + return cadence.AddressType + case SimpleTypeInt: + return cadence.IntType + case SimpleTypeInt8: + return cadence.Int8Type + case SimpleTypeInt16: + return cadence.Int16Type + case SimpleTypeInt32: + return cadence.Int32Type + case SimpleTypeInt64: + return cadence.Int64Type + case SimpleTypeInt128: + return cadence.Int128Type + case SimpleTypeInt256: + return cadence.Int256Type + case SimpleTypeUInt: + return cadence.UIntType + case SimpleTypeUInt8: + return cadence.UInt8Type + case SimpleTypeUInt16: + return cadence.UInt16Type + case SimpleTypeUInt32: + return cadence.UInt32Type + case SimpleTypeUInt64: + return cadence.UInt64Type + case SimpleTypeUInt128: + return cadence.UInt128Type + case SimpleTypeUInt256: + return cadence.UInt256Type + case SimpleTypeWord8: + return cadence.Word8Type + case SimpleTypeWord16: + return cadence.Word16Type + case SimpleTypeWord32: + return cadence.Word32Type + case SimpleTypeWord64: + return cadence.Word64Type + case SimpleTypeWord128: + return cadence.Word128Type + case SimpleTypeWord256: + return cadence.Word256Type + case SimpleTypeFix64: + return cadence.Fix64Type + case SimpleTypeUFix64: + return cadence.UFix64Type + case SimpleTypePath: + return cadence.PathType + case SimpleTypeCapabilityPath: + return cadence.CapabilityPathType + case SimpleTypeStoragePath: + return cadence.StoragePathType + case SimpleTypePublicPath: + return cadence.PublicPathType + case SimpleTypePrivatePath: + return cadence.PrivatePathType + case SimpleTypeDeployedContract: + return cadence.DeployedContractType + case SimpleTypeBlock: + return cadence.BlockType + case SimpleTypeAny: + return cadence.AnyType + case SimpleTypeAnyStruct: + return cadence.AnyStructType + case SimpleTypeAnyResource: + return cadence.AnyResourceType + case SimpleTypeMetaType: + return cadence.MetaType + case SimpleTypeNever: + return cadence.NeverType + case SimpleTypeNumber: + return cadence.NumberType + case SimpleTypeSignedNumber: + return cadence.SignedNumberType + case SimpleTypeInteger: + return cadence.IntegerType + case SimpleTypeSignedInteger: + return cadence.SignedIntegerType + case SimpleTypeFixedPoint: + return cadence.FixedPointType + case SimpleTypeSignedFixedPoint: + return cadence.SignedFixedPointType + case SimpleTypeBytes: + return cadence.TheBytesType + case SimpleTypeVoid: + return cadence.VoidType + case SimpleTypeAnyStructAttachmentType: + return cadence.AnyStructAttachmentType + case SimpleTypeAnyResourceAttachmentType: + return cadence.AnyResourceAttachmentType + case SimpleTypeStorageCapabilityController: + return cadence.StorageCapabilityControllerType + case SimpleTypeAccountCapabilityController: + return cadence.AccountCapabilityControllerType + case SimpleTypeAccount: + return cadence.AccountType + case SimpleTypeAccount_Contracts: + return cadence.Account_ContractsType + case SimpleTypeAccount_Keys: + return cadence.Account_KeysType + case SimpleTypeAccount_Inbox: + return cadence.Account_InboxType + case SimpleTypeAccount_StorageCapabilities: + return cadence.Account_StorageCapabilitiesType + case SimpleTypeAccount_AccountCapabilities: + return cadence.Account_AccountCapabilitiesType + case SimpleTypeAccount_Capabilities: + return cadence.Account_CapabilitiesType + case SimpleTypeAccount_Storage: + return cadence.Account_StorageType + case SimpleTypeMutate: + return cadence.MutateType + case SimpleTypeInsert: + return cadence.InsertType + case SimpleTypeRemove: + return cadence.RemoveType + case SimpleTypeIdentity: + return cadence.IdentityType + case SimpleTypeStorage: + return cadence.StorageType + case SimpleTypeSaveValue: + return cadence.SaveValueType + case SimpleTypeLoadValue: + return cadence.LoadValueType + case SimpleTypeBorrowValue: + return cadence.BorrowValueType + case SimpleTypeContracts: + return cadence.ContractsType + case SimpleTypeAddContract: + return cadence.AddContractType + case SimpleTypeUpdateContract: + return cadence.UpdateContractType + case SimpleTypeRemoveContract: + return cadence.RemoveContractType + case SimpleTypeKeys: + return cadence.KeysType + case SimpleTypeAddKey: + return cadence.AddKeyType + case SimpleTypeRevokeKey: + return cadence.RevokeKeyType + case SimpleTypeInbox: + return cadence.InboxType + case SimpleTypePublishInboxCapability: + return cadence.PublishInboxCapabilityType + case SimpleTypeUnpublishInboxCapability: + return cadence.UnpublishInboxCapabilityType + case SimpleTypeClaimInboxCapability: + return cadence.ClaimInboxCapabilityType + case SimpleTypeCapabilities: + return cadence.CapabilitiesType + case SimpleTypeStorageCapabilities: + return cadence.StorageCapabilitiesType + case SimpleTypeAccountCapabilities: + return cadence.AccountCapabilitiesType + case SimpleTypePublishCapability: + return cadence.PublishCapabilityType + case SimpleTypeUnpublishCapability: + return cadence.UnpublishCapabilityType + case SimpleTypeGetStorageCapabilityController: + return cadence.GetStorageCapabilityControllerType + case SimpleTypeIssueStorageCapabilityController: + return cadence.IssueStorageCapabilityControllerType + case SimpleTypeGetAccountCapabilityController: + return cadence.GetAccountCapabilityControllerType + case SimpleTypeIssueAccountCapabilityController: + return cadence.IssueAccountCapabilityControllerType + case SimpleTypeCapabilitiesMapping: + return cadence.CapabilitiesMappingType + case SimpleTypeAccountMapping: + return cadence.AccountMappingType + } + + return nil +} diff --git a/encoding/ccf/simpletype_string.go b/encoding/ccf/simpletype_string.go new file mode 100644 index 0000000000..9ea3c5876e --- /dev/null +++ b/encoding/ccf/simpletype_string.go @@ -0,0 +1,126 @@ +// Code generated by "stringer -type=SimpleType"; DO NOT EDIT. + +package ccf + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[SimpleTypeBool-0] + _ = x[SimpleTypeString-1] + _ = x[SimpleTypeCharacter-2] + _ = x[SimpleTypeAddress-3] + _ = x[SimpleTypeInt-4] + _ = x[SimpleTypeInt8-5] + _ = x[SimpleTypeInt16-6] + _ = x[SimpleTypeInt32-7] + _ = x[SimpleTypeInt64-8] + _ = x[SimpleTypeInt128-9] + _ = x[SimpleTypeInt256-10] + _ = x[SimpleTypeUInt-11] + _ = x[SimpleTypeUInt8-12] + _ = x[SimpleTypeUInt16-13] + _ = x[SimpleTypeUInt32-14] + _ = x[SimpleTypeUInt64-15] + _ = x[SimpleTypeUInt128-16] + _ = x[SimpleTypeUInt256-17] + _ = x[SimpleTypeWord8-18] + _ = x[SimpleTypeWord16-19] + _ = x[SimpleTypeWord32-20] + _ = x[SimpleTypeWord64-21] + _ = x[SimpleTypeFix64-22] + _ = x[SimpleTypeUFix64-23] + _ = x[SimpleTypePath-24] + _ = x[SimpleTypeCapabilityPath-25] + _ = x[SimpleTypeStoragePath-26] + _ = x[SimpleTypePublicPath-27] + _ = x[SimpleTypePrivatePath-28] + _ = x[SimpleTypeDeployedContract-35] + _ = x[SimpleTypeBlock-37] + _ = x[SimpleTypeAny-38] + _ = x[SimpleTypeAnyStruct-39] + _ = x[SimpleTypeAnyResource-40] + _ = x[SimpleTypeMetaType-41] + _ = x[SimpleTypeNever-42] + _ = x[SimpleTypeNumber-43] + _ = x[SimpleTypeSignedNumber-44] + _ = x[SimpleTypeInteger-45] + _ = x[SimpleTypeSignedInteger-46] + _ = x[SimpleTypeFixedPoint-47] + _ = x[SimpleTypeSignedFixedPoint-48] + _ = x[SimpleTypeBytes-49] + _ = x[SimpleTypeVoid-50] + _ = x[SimpleTypeFunction-51] + _ = x[SimpleTypeWord128-52] + _ = x[SimpleTypeWord256-53] + _ = x[SimpleTypeAnyStructAttachmentType-54] + _ = x[SimpleTypeAnyResourceAttachmentType-55] + _ = x[SimpleTypeStorageCapabilityController-56] + _ = x[SimpleTypeAccountCapabilityController-57] + _ = x[SimpleTypeAccount-58] + _ = x[SimpleTypeAccount_Contracts-59] + _ = x[SimpleTypeAccount_Keys-60] + _ = x[SimpleTypeAccount_Inbox-61] + _ = x[SimpleTypeAccount_StorageCapabilities-62] + _ = x[SimpleTypeAccount_AccountCapabilities-63] + _ = x[SimpleTypeAccount_Capabilities-64] + _ = x[SimpleTypeAccount_Storage-65] + _ = x[SimpleTypeMutate-66] + _ = x[SimpleTypeInsert-67] + _ = x[SimpleTypeRemove-68] + _ = x[SimpleTypeIdentity-69] + _ = x[SimpleTypeStorage-70] + _ = x[SimpleTypeSaveValue-71] + _ = x[SimpleTypeLoadValue-72] + _ = x[SimpleTypeBorrowValue-73] + _ = x[SimpleTypeContracts-74] + _ = x[SimpleTypeAddContract-75] + _ = x[SimpleTypeUpdateContract-76] + _ = x[SimpleTypeRemoveContract-77] + _ = x[SimpleTypeKeys-78] + _ = x[SimpleTypeAddKey-79] + _ = x[SimpleTypeRevokeKey-80] + _ = x[SimpleTypeInbox-81] + _ = x[SimpleTypePublishInboxCapability-82] + _ = x[SimpleTypeUnpublishInboxCapability-83] + _ = x[SimpleTypeClaimInboxCapability-84] + _ = x[SimpleTypeCapabilities-85] + _ = x[SimpleTypeStorageCapabilities-86] + _ = x[SimpleTypeAccountCapabilities-87] + _ = x[SimpleTypePublishCapability-88] + _ = x[SimpleTypeUnpublishCapability-89] + _ = x[SimpleTypeGetStorageCapabilityController-90] + _ = x[SimpleTypeIssueStorageCapabilityController-91] + _ = x[SimpleTypeGetAccountCapabilityController-92] + _ = x[SimpleTypeIssueAccountCapabilityController-93] + _ = x[SimpleTypeCapabilitiesMapping-94] + _ = x[SimpleTypeAccountMapping-95] + _ = x[SimpleType_Count-96] +} + +const ( + _SimpleType_name_0 = "SimpleTypeBoolSimpleTypeStringSimpleTypeCharacterSimpleTypeAddressSimpleTypeIntSimpleTypeInt8SimpleTypeInt16SimpleTypeInt32SimpleTypeInt64SimpleTypeInt128SimpleTypeInt256SimpleTypeUIntSimpleTypeUInt8SimpleTypeUInt16SimpleTypeUInt32SimpleTypeUInt64SimpleTypeUInt128SimpleTypeUInt256SimpleTypeWord8SimpleTypeWord16SimpleTypeWord32SimpleTypeWord64SimpleTypeFix64SimpleTypeUFix64SimpleTypePathSimpleTypeCapabilityPathSimpleTypeStoragePathSimpleTypePublicPathSimpleTypePrivatePath" + _SimpleType_name_1 = "SimpleTypeDeployedContract" + _SimpleType_name_2 = "SimpleTypeBlockSimpleTypeAnySimpleTypeAnyStructSimpleTypeAnyResourceSimpleTypeMetaTypeSimpleTypeNeverSimpleTypeNumberSimpleTypeSignedNumberSimpleTypeIntegerSimpleTypeSignedIntegerSimpleTypeFixedPointSimpleTypeSignedFixedPointSimpleTypeBytesSimpleTypeVoidSimpleTypeFunctionSimpleTypeWord128SimpleTypeWord256SimpleTypeAnyStructAttachmentTypeSimpleTypeAnyResourceAttachmentTypeSimpleTypeStorageCapabilityControllerSimpleTypeAccountCapabilityControllerSimpleTypeAccountSimpleTypeAccount_ContractsSimpleTypeAccount_KeysSimpleTypeAccount_InboxSimpleTypeAccount_StorageCapabilitiesSimpleTypeAccount_AccountCapabilitiesSimpleTypeAccount_CapabilitiesSimpleTypeAccount_StorageSimpleTypeMutateSimpleTypeInsertSimpleTypeRemoveSimpleTypeIdentitySimpleTypeStorageSimpleTypeSaveValueSimpleTypeLoadValueSimpleTypeBorrowValueSimpleTypeContractsSimpleTypeAddContractSimpleTypeUpdateContractSimpleTypeRemoveContractSimpleTypeKeysSimpleTypeAddKeySimpleTypeRevokeKeySimpleTypeInboxSimpleTypePublishInboxCapabilitySimpleTypeUnpublishInboxCapabilitySimpleTypeClaimInboxCapabilitySimpleTypeCapabilitiesSimpleTypeStorageCapabilitiesSimpleTypeAccountCapabilitiesSimpleTypePublishCapabilitySimpleTypeUnpublishCapabilitySimpleTypeGetStorageCapabilityControllerSimpleTypeIssueStorageCapabilityControllerSimpleTypeGetAccountCapabilityControllerSimpleTypeIssueAccountCapabilityControllerSimpleTypeCapabilitiesMappingSimpleTypeAccountMappingSimpleType_Count" +) + +var ( + _SimpleType_index_0 = [...]uint16{0, 14, 30, 49, 66, 79, 93, 108, 123, 138, 154, 170, 184, 199, 215, 231, 247, 264, 281, 296, 312, 328, 344, 359, 375, 389, 413, 434, 454, 475} + _SimpleType_index_2 = [...]uint16{0, 15, 28, 47, 68, 86, 101, 117, 139, 156, 179, 199, 225, 240, 254, 272, 289, 306, 339, 374, 411, 448, 465, 492, 514, 537, 574, 611, 641, 666, 682, 698, 714, 732, 749, 768, 787, 808, 827, 848, 872, 896, 910, 926, 945, 960, 992, 1026, 1056, 1078, 1107, 1136, 1163, 1192, 1232, 1274, 1314, 1356, 1385, 1409, 1425} +) + +func (i SimpleType) String() string { + switch { + case i <= 28: + return _SimpleType_name_0[_SimpleType_index_0[i]:_SimpleType_index_0[i+1]] + case i == 35: + return _SimpleType_name_1 + case 37 <= i && i <= 96: + i -= 37 + return _SimpleType_name_2[_SimpleType_index_2[i]:_SimpleType_index_2[i+1]] + default: + return "SimpleType(" + strconv.FormatInt(int64(i), 10) + ")" + } +} diff --git a/encoding/ccf/simpletype_test.go b/encoding/ccf/simpletype_test.go new file mode 100644 index 0000000000..ed05bd2404 --- /dev/null +++ b/encoding/ccf/simpletype_test.go @@ -0,0 +1,74 @@ +/* + * Cadence - The resource-oriented smart contract programming language + * + * Copyright Dapper Labs, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ccf + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/onflow/cadence" + "github.com/onflow/cadence/runtime" + "github.com/onflow/cadence/runtime/interpreter" + "github.com/onflow/cadence/runtime/sema" +) + +func TestTypeConversion(t *testing.T) { + t.Parallel() + + // Missing types are not problematic, + // just a missed optimization (more compact encoding) + + test := func(ty interpreter.PrimitiveStaticType, semaType sema.Type) { + + t.Run(semaType.QualifiedString(), func(t *testing.T) { + + t.Parallel() + + cadenceType := runtime.ExportType(semaType, map[sema.TypeID]cadence.Type{}) + + simpleTypeID, ok := simpleTypeIDByType(cadenceType) + require.True(t, ok) + + ty2 := typeBySimpleTypeID(simpleTypeID) + require.Equal(t, cadence.PrimitiveType(ty), ty2) + }) + } + + for ty := interpreter.PrimitiveStaticType(1); ty < interpreter.PrimitiveStaticType_Count; ty++ { + if !ty.IsDefined() { + continue + } + + semaType := ty.SemaType() + + // Some primitive static types are deprecated, + // and only exist for migration purposes, + // so do not have an equivalent sema type + if semaType == nil { + continue + } + + if _, ok := semaType.(*sema.CapabilityType); ok { + continue + } + + test(ty, semaType) + } +} diff --git a/encoding/ccf/traverse_value.go b/encoding/ccf/traverse_value.go index bb6192cc00..bd05246bfd 100644 --- a/encoding/ccf/traverse_value.go +++ b/encoding/ccf/traverse_value.go @@ -180,12 +180,19 @@ func (ct *compositeTypes) traverseType(typ cadence.Type) (checkRuntimeType bool) // Return true to check runtime type. return true + case cadence.BytesType, + *cadence.FunctionType: + // TODO: Maybe there are more types that we can skip checking runtime type for composite type. + + return false + } + + switch typ { case cadence.VoidType, cadence.BoolType, cadence.NeverType, cadence.CharacterType, cadence.StringType, - cadence.BytesType, cadence.AddressType, cadence.IntType, cadence.Int8Type, @@ -214,20 +221,19 @@ func (ct *compositeTypes) traverseType(typ cadence.Type) (checkRuntimeType bool) cadence.PublicPathType, cadence.PrivatePathType, cadence.MetaType, - *cadence.FunctionType, cadence.NumberType, cadence.SignedNumberType, cadence.IntegerType, cadence.SignedIntegerType, cadence.FixedPointType, cadence.SignedFixedPointType: + // TODO: Maybe there are more types that we can skip checking runtime type for composite type. return false - - default: - return true } + + return true } func (ct *compositeTypes) add(t cadence.Type) bool { diff --git a/encoding/json/decode.go b/encoding/json/decode.go index 282119d5c2..9f4fbfece6 100644 --- a/encoding/json/decode.go +++ b/encoding/json/decode.go @@ -29,6 +29,7 @@ import ( "github.com/onflow/cadence" "github.com/onflow/cadence/runtime/common" "github.com/onflow/cadence/runtime/errors" + "github.com/onflow/cadence/runtime/interpreter" "github.com/onflow/cadence/runtime/sema" ) @@ -1170,6 +1171,41 @@ func (d *Decoder) decodeIntersectionType( type typeDecodingResults map[string]cadence.Type +var simpleTypes = func() map[string]cadence.Type { + typeMap := make(map[string]cadence.Type, interpreter.PrimitiveStaticType_Count) + + // Bytes is not a primitive static type + typeMap["Bytes"] = cadence.TheBytesType + + for ty := interpreter.PrimitiveStaticType(1); ty < interpreter.PrimitiveStaticType_Count; ty++ { + if !ty.IsDefined() { + continue + } + + cadenceType := cadence.PrimitiveType(ty) + if !canEncodeAsSimpleType(cadenceType) { + continue + } + + semaType := ty.SemaType() + + // Some primitive static types are deprecated, + // and only exist for migration purposes, + // so do not have an equivalent sema type + if semaType == nil { + continue + } + + typeMap[string(semaType.ID())] = cadenceType + } + + return typeMap +}() + +func canEncodeAsSimpleType(primitiveType cadence.PrimitiveType) bool { + return primitiveType != cadence.PrimitiveType(interpreter.PrimitiveStaticTypeCapability) +} + func (d *Decoder) decodeType(valueJSON any, results typeDecodingResults) cadence.Type { if valueJSON == "" { return nil @@ -1240,117 +1276,12 @@ func (d *Decoder) decodeType(valueJSON any, results typeDecodingResults) cadence d.decodeAuthorization(obj.Get(authorizationKey)), d.decodeType(obj.Get(typeKey), results), ) - case "Any": - return cadence.TheAnyType - case "AnyStruct": - return cadence.TheAnyStructType - case "AnyStructAttachment": - return cadence.TheAnyStructAttachmentType - case "AnyResource": - return cadence.TheAnyResourceType - case "AnyResourceAttachment": - return cadence.TheAnyResourceAttachmentType - case "Type": - return cadence.TheMetaType - case "Void": - return cadence.TheVoidType - case "Never": - return cadence.TheNeverType - case "Bool": - return cadence.TheBoolType - case "String": - return cadence.TheStringType - case "Character": - return cadence.TheCharacterType - case "Bytes": - return cadence.TheBytesType - case "Address": - return cadence.TheAddressType - case "Number": - return cadence.TheNumberType - case "SignedNumber": - return cadence.TheSignedNumberType - case "Integer": - return cadence.TheIntegerType - case "SignedInteger": - return cadence.TheSignedIntegerType - case "FixedPoint": - return cadence.TheFixedPointType - case "SignedFixedPoint": - return cadence.TheSignedFixedPointType - case "Int": - return cadence.TheIntType - case "Int8": - return cadence.TheInt8Type - case "Int16": - return cadence.TheInt16Type - case "Int32": - return cadence.TheInt32Type - case "Int64": - return cadence.TheInt64Type - case "Int128": - return cadence.TheInt128Type - case "Int256": - return cadence.TheInt256Type - case "UInt": - return cadence.TheUIntType - case "UInt8": - return cadence.TheUInt8Type - case "UInt16": - return cadence.TheUInt16Type - case "UInt32": - return cadence.TheUInt32Type - case "UInt64": - return cadence.TheUInt64Type - case "UInt128": - return cadence.TheUInt128Type - case "UInt256": - return cadence.TheUInt256Type - case "Word8": - return cadence.TheWord8Type - case "Word16": - return cadence.TheWord16Type - case "Word32": - return cadence.TheWord32Type - case "Word64": - return cadence.TheWord64Type - case "Word128": - return cadence.TheWord128Type - case "Word256": - return cadence.TheWord256Type - case "Fix64": - return cadence.TheFix64Type - case "UFix64": - return cadence.TheUFix64Type - case "Path": - return cadence.ThePathType - case "CapabilityPath": - return cadence.TheCapabilityPathType - case "StoragePath": - return cadence.TheStoragePathType - case "PublicPath": - return cadence.ThePublicPathType - case "PrivatePath": - return cadence.ThePrivatePathType - case "AuthAccount": - return cadence.TheAuthAccountType - case "PublicAccount": - return cadence.ThePublicAccountType - case "AuthAccount.Keys": - return cadence.TheAuthAccountKeysType - case "PublicAccount.Keys": - return cadence.ThePublicAccountKeysType - case "AuthAccount.Contracts": - return cadence.TheAuthAccountContractsType - case "PublicAccount.Contracts": - return cadence.ThePublicAccountContractsType - case "DeployedContract": - return cadence.TheDeployedContractType - case "AccountKey": - return cadence.TheAccountKeyType - case "Block": - return cadence.TheBlockType default: + simpleType, ok := simpleTypes[kindValue] + if ok { + return simpleType + } + fieldsValue := obj.Get(fieldsKey) typeIDValue := toString(obj.Get(typeIDKey)) initValue := obj.Get(initializersKey) diff --git a/encoding/json/encode.go b/encoding/json/encode.go index ac56c21a85..38c07d18b8 100644 --- a/encoding/json/encode.go +++ b/encoding/json/encode.go @@ -765,61 +765,7 @@ func prepareType(typ cadence.Type, results typePreparationResults) jsonValue { } switch typ := typ.(type) { - case cadence.AnyType, - cadence.AnyStructType, - cadence.AnyStructAttachmentType, - cadence.AnyResourceType, - cadence.AnyResourceAttachmentType, - cadence.AddressType, - cadence.MetaType, - cadence.VoidType, - cadence.NeverType, - cadence.BoolType, - cadence.StringType, - cadence.CharacterType, - cadence.BytesType, - cadence.NumberType, - cadence.SignedNumberType, - cadence.IntegerType, - cadence.SignedIntegerType, - cadence.FixedPointType, - cadence.SignedFixedPointType, - cadence.IntType, - cadence.Int8Type, - cadence.Int16Type, - cadence.Int32Type, - cadence.Int64Type, - cadence.Int128Type, - cadence.Int256Type, - cadence.UIntType, - cadence.UInt8Type, - cadence.UInt16Type, - cadence.UInt32Type, - cadence.UInt64Type, - cadence.UInt128Type, - cadence.UInt256Type, - cadence.Word8Type, - cadence.Word16Type, - cadence.Word32Type, - cadence.Word64Type, - cadence.Word128Type, - cadence.Word256Type, - cadence.Fix64Type, - cadence.UFix64Type, - cadence.BlockType, - cadence.PathType, - cadence.CapabilityPathType, - cadence.StoragePathType, - cadence.PublicPathType, - cadence.PrivatePathType, - cadence.AccountKeyType, - cadence.AuthAccountContractsType, - cadence.AuthAccountKeysType, - cadence.AuthAccountType, - cadence.PublicAccountContractsType, - cadence.PublicAccountKeysType, - cadence.PublicAccountType, - cadence.DeployedContractType: + case cadence.BytesType: return jsonSimpleType{ Kind: typ.ID(), } @@ -942,11 +888,15 @@ func prepareType(typ cadence.Type, results typePreparationResults) jsonValue { Initializers: prepareInitializers(typ.Initializers, results), Type: prepareType(typ.RawType, results), } + case cadence.PrimitiveType: + return jsonSimpleType{ + Kind: typ.ID(), + } case nil: return "" - default: - panic(fmt.Errorf("unsupported type: %T, %v", typ, typ)) } + + panic(fmt.Errorf("unsupported type: %T, %s", typ, typ)) } type typePreparationResults map[cadence.Type]struct{} diff --git a/encoding/json/encoding_test.go b/encoding/json/encoding_test.go index 7627154612..5aa668f6d9 100644 --- a/encoding/json/encoding_test.go +++ b/encoding/json/encoding_test.go @@ -16,7 +16,7 @@ * limitations under the License. */ -package json_test +package json import ( "fmt" @@ -34,7 +34,6 @@ import ( "github.com/onflow/cadence/runtime/tests/checker" "github.com/onflow/cadence" - "github.com/onflow/cadence/encoding/json" "github.com/onflow/cadence/runtime/sema" "github.com/onflow/cadence/runtime/tests/utils" ) @@ -203,7 +202,7 @@ func TestDecodeInvalidAddress(t *testing.T) { msg := `{"type":"Address","value":"000000000102030405"}` - _, err := json.Decode(nil, []byte(msg)) + _, err := Decode(nil, []byte(msg)) require.ErrorContains(t, err, "invalid address prefix: (shown as hex) expected 3078, got 3030") } @@ -1334,11 +1333,11 @@ func TestEncodeStruct(t *testing.T) { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.IntType{}, + Type: cadence.IntType, }, { Identifier: "b", - Type: cadence.StringType{}, + Type: cadence.StringType, }, }, } @@ -1386,7 +1385,7 @@ func TestEncodeStruct(t *testing.T) { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.StringType{}, + Type: cadence.StringType, }, { Identifier: "b", @@ -1458,11 +1457,11 @@ func TestEncodeEvent(t *testing.T) { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.IntType{}, + Type: cadence.IntType, }, { Identifier: "b", - Type: cadence.StringType{}, + Type: cadence.StringType, }, }, } @@ -1510,7 +1509,7 @@ func TestEncodeEvent(t *testing.T) { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.StringType{}, + Type: cadence.StringType, }, { Identifier: "b", @@ -1582,11 +1581,11 @@ func TestEncodeContract(t *testing.T) { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.IntType{}, + Type: cadence.IntType, }, { Identifier: "b", - Type: cadence.StringType{}, + Type: cadence.StringType, }, }, } @@ -1634,7 +1633,7 @@ func TestEncodeContract(t *testing.T) { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.StringType{}, + Type: cadence.StringType, }, { Identifier: "b", @@ -1703,59 +1702,8 @@ func TestEncodeSimpleTypes(t *testing.T) { var tests []encodeTest for _, ty := range []cadence.Type{ - cadence.AnyType{}, - cadence.AnyStructType{}, - cadence.AnyStructAttachmentType{}, - cadence.AnyResourceType{}, - cadence.AnyResourceAttachmentType{}, - cadence.MetaType{}, - cadence.VoidType{}, - cadence.NeverType{}, - cadence.BoolType{}, - cadence.StringType{}, - cadence.CharacterType{}, - cadence.BytesType{}, - cadence.AddressType{}, - cadence.SignedNumberType{}, - cadence.IntegerType{}, - cadence.SignedIntegerType{}, - cadence.FixedPointType{}, - cadence.IntType{}, - cadence.Int8Type{}, - cadence.Int16Type{}, - cadence.Int32Type{}, - cadence.Int64Type{}, - cadence.Int128Type{}, - cadence.Int256Type{}, - cadence.UIntType{}, - cadence.UInt8Type{}, - cadence.UInt16Type{}, - cadence.UInt32Type{}, - cadence.UInt64Type{}, - cadence.UInt128Type{}, - cadence.UInt256Type{}, - cadence.Word8Type{}, - cadence.Word16Type{}, - cadence.Word32Type{}, - cadence.Word64Type{}, - cadence.Word128Type{}, - cadence.Word256Type{}, - cadence.Fix64Type{}, - cadence.UFix64Type{}, - cadence.BlockType{}, - cadence.PathType{}, - cadence.CapabilityPathType{}, - cadence.StoragePathType{}, - cadence.PublicPathType{}, - cadence.PrivatePathType{}, - cadence.AccountKeyType{}, - cadence.AuthAccountContractsType{}, - cadence.AuthAccountKeysType{}, - cadence.AuthAccountType{}, - cadence.PublicAccountContractsType{}, - cadence.PublicAccountKeysType{}, - cadence.PublicAccountType{}, - cadence.DeployedContractType{}, + cadence.AnyType, + cadence.TheBytesType, } { tests = append(tests, encodeTest{ name: fmt.Sprintf("with static %s", ty.ID()), @@ -1779,7 +1727,7 @@ func TestEncodeType(t *testing.T) { testEncodeAndDecode( t, cadence.TypeValue{ - StaticType: &cadence.OptionalType{Type: cadence.IntType{}}, + StaticType: &cadence.OptionalType{Type: cadence.IntType}, }, // language=json ` @@ -1804,7 +1752,7 @@ func TestEncodeType(t *testing.T) { testEncodeAndDecode( t, cadence.TypeValue{ - StaticType: &cadence.VariableSizedArrayType{ElementType: cadence.IntType{}}, + StaticType: &cadence.VariableSizedArrayType{ElementType: cadence.IntType}, }, // language=json ` @@ -1830,7 +1778,7 @@ func TestEncodeType(t *testing.T) { t, cadence.TypeValue{ StaticType: &cadence.ConstantSizedArrayType{ - ElementType: cadence.IntType{}, + ElementType: cadence.IntType, Size: 3, }, }, @@ -1859,8 +1807,8 @@ func TestEncodeType(t *testing.T) { t, cadence.TypeValue{ StaticType: &cadence.DictionaryType{ - ElementType: cadence.StringType{}, - KeyType: cadence.IntType{}, + ElementType: cadence.StringType, + KeyType: cadence.IntType, }, }, // language=json @@ -1893,11 +1841,11 @@ func TestEncodeType(t *testing.T) { Location: utils.TestLocation, QualifiedIdentifier: "S", Fields: []cadence.Field{ - {Identifier: "foo", Type: cadence.IntType{}}, + {Identifier: "foo", Type: cadence.IntType}, }, Initializers: [][]cadence.Parameter{ - {{Label: "foo", Identifier: "bar", Type: cadence.IntType{}}}, - {{Label: "qux", Identifier: "baz", Type: cadence.StringType{}}}, + {{Label: "foo", Identifier: "bar", Type: cadence.IntType}}, + {{Label: "qux", Identifier: "baz", Type: cadence.StringType}}, }, }, }, @@ -1954,11 +1902,11 @@ func TestEncodeType(t *testing.T) { Location: utils.TestLocation, QualifiedIdentifier: "R", Fields: []cadence.Field{ - {Identifier: "foo", Type: cadence.IntType{}}, + {Identifier: "foo", Type: cadence.IntType}, }, Initializers: [][]cadence.Parameter{ - {{Label: "foo", Identifier: "bar", Type: cadence.IntType{}}}, - {{Label: "qux", Identifier: "baz", Type: cadence.StringType{}}}, + {{Label: "foo", Identifier: "bar", Type: cadence.IntType}}, + {{Label: "qux", Identifier: "baz", Type: cadence.StringType}}, }, }, }, @@ -2015,11 +1963,11 @@ func TestEncodeType(t *testing.T) { Location: utils.TestLocation, QualifiedIdentifier: "C", Fields: []cadence.Field{ - {Identifier: "foo", Type: cadence.IntType{}}, + {Identifier: "foo", Type: cadence.IntType}, }, Initializers: [][]cadence.Parameter{ - {{Label: "foo", Identifier: "bar", Type: cadence.IntType{}}}, - {{Label: "qux", Identifier: "baz", Type: cadence.StringType{}}}, + {{Label: "foo", Identifier: "bar", Type: cadence.IntType}}, + {{Label: "qux", Identifier: "baz", Type: cadence.StringType}}, }, }, }, @@ -2076,11 +2024,11 @@ func TestEncodeType(t *testing.T) { Location: utils.TestLocation, QualifiedIdentifier: "S", Fields: []cadence.Field{ - {Identifier: "foo", Type: cadence.IntType{}}, + {Identifier: "foo", Type: cadence.IntType}, }, Initializers: [][]cadence.Parameter{ - {{Label: "foo", Identifier: "bar", Type: cadence.IntType{}}}, - {{Label: "qux", Identifier: "baz", Type: cadence.StringType{}}}, + {{Label: "foo", Identifier: "bar", Type: cadence.IntType}}, + {{Label: "qux", Identifier: "baz", Type: cadence.StringType}}, }, }, }, @@ -2137,11 +2085,11 @@ func TestEncodeType(t *testing.T) { Location: utils.TestLocation, QualifiedIdentifier: "R", Fields: []cadence.Field{ - {Identifier: "foo", Type: cadence.IntType{}}, + {Identifier: "foo", Type: cadence.IntType}, }, Initializers: [][]cadence.Parameter{ - {{Label: "foo", Identifier: "bar", Type: cadence.IntType{}}}, - {{Label: "qux", Identifier: "baz", Type: cadence.StringType{}}}, + {{Label: "foo", Identifier: "bar", Type: cadence.IntType}}, + {{Label: "qux", Identifier: "baz", Type: cadence.StringType}}, }, }, }, @@ -2198,11 +2146,11 @@ func TestEncodeType(t *testing.T) { Location: utils.TestLocation, QualifiedIdentifier: "C", Fields: []cadence.Field{ - {Identifier: "foo", Type: cadence.IntType{}}, + {Identifier: "foo", Type: cadence.IntType}, }, Initializers: [][]cadence.Parameter{ - {{Label: "foo", Identifier: "bar", Type: cadence.IntType{}}}, - {{Label: "qux", Identifier: "baz", Type: cadence.StringType{}}}, + {{Label: "foo", Identifier: "bar", Type: cadence.IntType}}, + {{Label: "qux", Identifier: "baz", Type: cadence.StringType}}, }, }, }, @@ -2259,11 +2207,11 @@ func TestEncodeType(t *testing.T) { Location: utils.TestLocation, QualifiedIdentifier: "E", Fields: []cadence.Field{ - {Identifier: "foo", Type: cadence.IntType{}}, + {Identifier: "foo", Type: cadence.IntType}, }, Initializer: []cadence.Parameter{ - {Label: "foo", Identifier: "bar", Type: cadence.IntType{}}, - {Label: "qux", Identifier: "baz", Type: cadence.StringType{}}, + {Label: "foo", Identifier: "bar", Type: cadence.IntType}, + {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, }, }, @@ -2317,13 +2265,13 @@ func TestEncodeType(t *testing.T) { StaticType: &cadence.EnumType{ Location: utils.TestLocation, QualifiedIdentifier: "E", - RawType: cadence.StringType{}, + RawType: cadence.StringType, Fields: []cadence.Field{ - {Identifier: "foo", Type: cadence.IntType{}}, + {Identifier: "foo", Type: cadence.IntType}, }, Initializers: [][]cadence.Parameter{ - {{Label: "foo", Identifier: "bar", Type: cadence.IntType{}}}, - {{Label: "qux", Identifier: "baz", Type: cadence.StringType{}}}, + {{Label: "foo", Identifier: "bar", Type: cadence.IntType}}, + {{Label: "qux", Identifier: "baz", Type: cadence.StringType}}, }, }, }, @@ -2380,7 +2328,7 @@ func TestEncodeType(t *testing.T) { cadence.TypeValue{ StaticType: &cadence.ReferenceType{ Authorization: cadence.UnauthorizedAccess, - Type: cadence.IntType{}, + Type: cadence.IntType, }, }, // language=json @@ -2413,7 +2361,7 @@ func TestEncodeType(t *testing.T) { Authorization: cadence.EntitlementMapAuthorization{ TypeID: "foo", }, - Type: cadence.IntType{}, + Type: cadence.IntType, }, }, // language=json @@ -2455,7 +2403,7 @@ func TestEncodeType(t *testing.T) { Kind: cadence.Conjunction, Entitlements: []common.TypeID{"X", "Y"}, }, - Type: cadence.IntType{}, + Type: cadence.IntType, }, }, // language=json @@ -2504,7 +2452,7 @@ func TestEncodeType(t *testing.T) { Kind: cadence.Disjunction, Entitlements: []common.TypeID{"X", "Y"}, }, - Type: cadence.IntType{}, + Type: cadence.IntType, }, }, // language=json @@ -2550,12 +2498,12 @@ func TestEncodeType(t *testing.T) { cadence.TypeValue{ StaticType: &cadence.FunctionType{ TypeParameters: []cadence.TypeParameter{ - {Name: "T", TypeBound: cadence.AnyStructType{}}, + {Name: "T", TypeBound: cadence.AnyStructType}, }, Parameters: []cadence.Parameter{ - {Label: "qux", Identifier: "baz", Type: cadence.StringType{}}, + {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, - ReturnType: cadence.IntType{}, + ReturnType: cadence.IntType, }, }, // language=json @@ -2603,9 +2551,9 @@ func TestEncodeType(t *testing.T) { StaticType: &cadence.FunctionType{ Purity: cadence.FunctionPurityView, Parameters: []cadence.Parameter{ - {Label: "qux", Identifier: "baz", Type: cadence.StringType{}}, + {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, - ReturnType: cadence.IntType{}, + ReturnType: cadence.IntType, TypeParameters: []cadence.TypeParameter{}, }, }, @@ -2656,9 +2604,9 @@ func TestEncodeType(t *testing.T) { cadence.TypeValue{ StaticType: &cadence.FunctionType{ Parameters: []cadence.Parameter{ - {Label: "qux", Identifier: "baz", Type: cadence.StringType{}}, + {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, - ReturnType: cadence.IntType{}, + ReturnType: cadence.IntType, }, }, ) @@ -2680,14 +2628,14 @@ func TestEncodeType(t *testing.T) { value := cadence.TypeValue{ StaticType: &cadence.FunctionType{ Parameters: []cadence.Parameter{ - {Label: "qux", Identifier: "baz", Type: cadence.StringType{}}, + {Label: "qux", Identifier: "baz", Type: cadence.StringType}, }, - ReturnType: cadence.IntType{}, + ReturnType: cadence.IntType, TypeParameters: []cadence.TypeParameter{}, }, } - decodedValue, err := json.Decode(nil, []byte(encodedValue)) + decodedValue, err := Decode(nil, []byte(encodedValue)) require.NoError(t, err) require.Equal(t, value, decodedValue) }) @@ -2698,7 +2646,7 @@ func TestEncodeType(t *testing.T) { t, cadence.TypeValue{ StaticType: &cadence.CapabilityType{ - BorrowType: cadence.IntType{}, + BorrowType: cadence.IntType, }, }, // language=json @@ -2726,7 +2674,7 @@ func TestEncodeType(t *testing.T) { cadence.TypeValue{ StaticType: &cadence.IntersectionType{ Types: []cadence.Type{ - cadence.StringType{}, + cadence.StringType, }, }, }, @@ -2773,7 +2721,7 @@ func TestEncodeCapability(t *testing.T) { cadence.NewCapability( 6, cadence.BytesToAddress([]byte{1, 2, 3, 4, 5}), - cadence.IntType{}, + cadence.IntType, ), // language=json ` @@ -2802,14 +2750,14 @@ func TestDecodeFixedPoints(t *testing.T) { maxFrac int64 minFrac int64 }{ - cadence.Fix64Type{}: { + cadence.Fix64Type: { constructor: func(i int) cadence.Value { return cadence.Fix64(int64(i)) }, maxInt: sema.Fix64TypeMaxInt, minInt: sema.Fix64TypeMinInt, maxFrac: sema.Fix64TypeMaxFractional, minFrac: sema.Fix64TypeMinFractional, }, - cadence.UFix64Type{}: { + cadence.UFix64Type: { constructor: func(i int) cadence.Value { return cadence.UFix64(uint64(i)) }, maxInt: int64(sema.UFix64TypeMaxInt), minInt: sema.UFix64TypeMinInt, @@ -2967,7 +2915,7 @@ func TestDecodeFixedPoints(t *testing.T) { // language=json enc := fmt.Sprintf(`{"type": "%s", "value": "%s"}`, ty.ID(), tt.input) - actual, err := json.Decode(nil, []byte(enc)) + actual, err := Decode(nil, []byte(enc)) if tt.check != nil { tt.check(t, actual, err) @@ -2985,7 +2933,7 @@ func TestDecodeFixedPoints(t *testing.T) { t.Parallel() // language=json - _, err := json.Decode(nil, []byte(`{"type": "Fix64", "value": "1.-1"}`)) + _, err := Decode(nil, []byte(`{"type": "Fix64", "value": "1.-1"}`)) assert.Error(t, err) }) @@ -2994,7 +2942,7 @@ func TestDecodeFixedPoints(t *testing.T) { t.Parallel() // language=json - _, err := json.Decode(nil, []byte(`{"type": "Fix64", "value": "1.+1"}`)) + _, err := Decode(nil, []byte(`{"type": "Fix64", "value": "1.+1"}`)) assert.Error(t, err) }) @@ -3003,7 +2951,7 @@ func TestDecodeFixedPoints(t *testing.T) { t.Parallel() // language=json - _, err := json.Decode(nil, []byte(`{"type": "Fix64", "value": ".1"}`)) + _, err := Decode(nil, []byte(`{"type": "Fix64", "value": ".1"}`)) assert.Error(t, err) }) @@ -3012,7 +2960,7 @@ func TestDecodeFixedPoints(t *testing.T) { t.Parallel() // language=json - _, err := json.Decode(nil, []byte(`{"type": "Fix64", "value": "1."}`)) + _, err := Decode(nil, []byte(`{"type": "Fix64", "value": "1."}`)) assert.Error(t, err) }) } @@ -3234,7 +3182,7 @@ func TestEncodePath(t *testing.T) { t.Run("invalid", func(t *testing.T) { t.Parallel() - _, err := json.Decode(nil, []byte( + _, err := Decode(nil, []byte( // language=json `{"type":"Path","value":{"domain":"Storage","identifier":"foo"}}`, )) @@ -3276,7 +3224,7 @@ func TestDecodeInvalidType(t *testing.T) { } } ` - _, err := json.Decode(nil, []byte(encodedValue)) + _, err := Decode(nil, []byte(encodedValue)) require.Error(t, err) assert.Equal(t, "failed to decode JSON-Cadence value: invalid type ID for built-in: ``", err.Error()) }) @@ -3294,7 +3242,7 @@ func TestDecodeInvalidType(t *testing.T) { } } ` - _, err := json.Decode(nil, []byte(encodedValue)) + _, err := Decode(nil, []byte(encodedValue)) require.Error(t, err) assert.Equal(t, "failed to decode JSON-Cadence value: invalid type ID `I`: invalid identifier location type ID: missing location", err.Error()) }) @@ -3312,7 +3260,7 @@ func TestDecodeInvalidType(t *testing.T) { } } ` - _, err := json.Decode(nil, []byte(encodedValue)) + _, err := Decode(nil, []byte(encodedValue)) require.Error(t, err) assert.Equal(t, "failed to decode JSON-Cadence value: invalid type ID for built-in: `N.PublicKey`", err.Error()) }) @@ -3324,7 +3272,7 @@ func testEncodeAndDecode(t *testing.T, val cadence.Value, expectedJSON string) { } func testEncode(t *testing.T, val cadence.Value, expectedJSON string) (actualJSON string) { - actualJSONBytes, err := json.Encode(val) + actualJSONBytes, err := Encode(val) require.NoError(t, err) actualJSON = string(actualJSONBytes) @@ -3334,8 +3282,8 @@ func testEncode(t *testing.T, val cadence.Value, expectedJSON string) (actualJSO return actualJSON } -func testDecode(t *testing.T, actualJSON string, expectedVal cadence.Value, options ...json.Option) { - decodedVal, err := json.Decode(nil, []byte(actualJSON), options...) +func testDecode(t *testing.T, actualJSON string, expectedVal cadence.Value, options ...Option) { + decodedVal, err := Decode(nil, []byte(actualJSON), options...) require.NoError(t, err) assert.Equal( @@ -3352,7 +3300,7 @@ func newFooResourceType() *cadence.ResourceType { Fields: []cadence.Field{ { Identifier: "bar", - Type: cadence.IntType{}, + Type: cadence.IntType, }, }, } @@ -3370,10 +3318,10 @@ func TestNonUTF8StringEncoding(t *testing.T) { // Avoid using the `NewMeteredString()` constructor to skip the validation stringValue := cadence.String(nonUTF8String) - encodedValue, err := json.Encode(stringValue) + encodedValue, err := Encode(stringValue) require.NoError(t, err) - decodedValue, err := json.Decode(nil, encodedValue) + decodedValue, err := Decode(nil, encodedValue) require.NoError(t, err) // Decoded value must be a valid utf8 string @@ -3399,7 +3347,7 @@ func TestDecodeBackwardsCompatibilityTypeID(t *testing.T) { cadence.TypeValue{ StaticType: cadence.TypeID("&Int"), }, - json.WithAllowUnstructuredStaticTypes(true), + WithAllowUnstructuredStaticTypes(true), ) }) @@ -3407,7 +3355,7 @@ func TestDecodeBackwardsCompatibilityTypeID(t *testing.T) { t.Parallel() - _, err := json.Decode(nil, []byte(encoded)) + _, err := Decode(nil, []byte(encoded)) require.Error(t, err) }) @@ -3538,7 +3486,7 @@ func TestExportFunctionValue(t *testing.T) { cadence.Function{ FunctionType: &cadence.FunctionType{ Parameters: []cadence.Parameter{}, - ReturnType: cadence.VoidType{}, + ReturnType: cadence.VoidType, }, }, // language=json @@ -3591,7 +3539,7 @@ func TestImportFunctionValue(t *testing.T) { cadence.Function{ FunctionType: &cadence.FunctionType{ Parameters: []cadence.Parameter{}, - ReturnType: cadence.VoidType{}, + ReturnType: cadence.VoidType, }, }, ) @@ -3628,10 +3576,56 @@ func TestImportFunctionValue(t *testing.T) { {Name: "T"}, }, Parameters: []cadence.Parameter{}, - ReturnType: cadence.VoidType{}, + ReturnType: cadence.VoidType, }, }, ) }) } + +func TestSimpleTypes(t *testing.T) { + t.Parallel() + + test := func(cadenceType cadence.PrimitiveType, semaType sema.Type) { + + t.Run(semaType.QualifiedString(), func(t *testing.T) { + t.Parallel() + + prepared := prepareType(cadenceType, typePreparationResults{}) + require.IsType(t, jsonSimpleType{}, prepared) + + encoded, err := Encode(cadence.NewTypeValue(cadenceType)) + require.NoError(t, err) + + decoded, err := Decode(nil, encoded) + require.NoError(t, err) + + require.IsType(t, cadence.TypeValue{}, decoded) + typeValue := decoded.(cadence.TypeValue) + require.Equal(t, cadenceType, typeValue.StaticType) + }) + } + + for ty := interpreter.PrimitiveStaticType(1); ty < interpreter.PrimitiveStaticType_Count; ty++ { + if !ty.IsDefined() { + continue + } + + semaType := ty.SemaType() + + // Some primitive static types are deprecated, + // and only exist for migration purposes, + // so do not have an equivalent sema type + if semaType == nil { + continue + } + + cadenceType := cadence.PrimitiveType(ty) + if !canEncodeAsSimpleType(cadenceType) { + continue + } + + test(cadenceType, semaType) + } +} diff --git a/runtime/account_test.go b/runtime/account_test.go index d36f94ac48..b4bfa6d0b0 100644 --- a/runtime/account_test.go +++ b/runtime/account_test.go @@ -87,9 +87,8 @@ func TestRuntimeReturnPublicAccount(t *testing.T) { rt := newTestInterpreterRuntime() script := []byte(` - access(all) fun main(): PublicAccount { - let acc = getAccount(0x02) - return acc + access(all) fun main(): &Account { + return getAccount(0x02) } `) @@ -121,9 +120,8 @@ func TestRuntimeReturnAuthAccount(t *testing.T) { rt := newTestInterpreterRuntime() script := []byte(` - access(all) fun main(): AuthAccount { - let acc = getAuthAccount(0x02) - return acc + access(all) fun main(): auth(Storage) &Account { + return getAuthAccount(0x02) } `) @@ -164,8 +162,8 @@ func TestRuntimeStoreAccountAPITypes(t *testing.T) { script := []byte(fmt.Sprintf(` transaction { - prepare(signer: AuthAccount) { - signer.save<%s>(panic("")) + prepare(signer: auth(SaveValue) &Account) { + signer.storage.save<%s>(panic("")) } } `, ty.String())) @@ -267,7 +265,7 @@ func TestRuntimeAuthAccountKeys(t *testing.T) { test := accountKeyTestCase{ code: ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { let key = signer.keys.get(keyIndex: 0) ?? panic("unexpectedly nil") log(key) assert(!key.isRevoked) @@ -304,7 +302,7 @@ func TestRuntimeAuthAccountKeys(t *testing.T) { test := accountKeyTestCase{ code: ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { let key: AccountKey? = signer.keys.get(keyIndex: 5) assert(key == nil) } @@ -331,7 +329,7 @@ func TestRuntimeAuthAccountKeys(t *testing.T) { test := accountKeyTestCase{ code: ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(RevokeKey) &Account) { let key = signer.keys.revoke(keyIndex: 0) ?? panic("unexpectedly nil") assert(key.isRevoked) } @@ -360,7 +358,7 @@ func TestRuntimeAuthAccountKeys(t *testing.T) { test := accountKeyTestCase{ code: ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(RevokeKey) &Account) { let key: AccountKey? = signer.keys.revoke(keyIndex: 5) assert(key == nil) } @@ -377,7 +375,7 @@ func TestRuntimeAuthAccountKeys(t *testing.T) { assert.Nil(t, testEnv.storage.returnedKey) }) - t.Run("get key count", func(t *testing.T) { + t.Run("get key count after revocation", func(t *testing.T) { t.Parallel() nextTransactionLocation := newTransactionLocationGenerator() @@ -386,7 +384,7 @@ func TestRuntimeAuthAccountKeys(t *testing.T) { test := accountKeyTestCase{ code: ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(RevokeKey) &Account) { assert(signer.keys.count == 1) let key = signer.keys.revoke(keyIndex: 0) ?? panic("unexpectedly nil") @@ -409,7 +407,7 @@ func TestRuntimeAuthAccountKeys(t *testing.T) { assert.Equal(t, revokedAccountKeyA, testEnv.storage.returnedKey) }) - t.Run("test keys forEach", func(t *testing.T) { + t.Run("test keys forEach, after add and revoke", func(t *testing.T) { t.Parallel() nextTransactionLocation := newTransactionLocationGenerator() @@ -418,7 +416,7 @@ func TestRuntimeAuthAccountKeys(t *testing.T) { test := accountKeyTestCase{ code: ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Keys) &Account) { signer.keys.add( publicKey: PublicKey( publicKey: [1, 2, 3], @@ -475,8 +473,8 @@ func TestRuntimeAuthAccountKeysAdd(t *testing.T) { const code = ` transaction(publicKey: [UInt8]) { - prepare(signer: AuthAccount) { - let acct = AuthAccount(payer: signer) + prepare(signer: auth(BorrowValue) &Account) { + let acct = Account(payer: signer) acct.keys.add( publicKey: PublicKey( publicKey: publicKey, @@ -645,7 +643,7 @@ func TestRuntimePublicAccountKeys(t *testing.T) { code: ` access(all) fun main(): AccountKey? { let acc = getAccount(0x02) - var keys: PublicAccount.Keys = acc.keys + var keys: &Account.Keys = acc.keys return keys.get(keyIndex: 0) } `, @@ -899,7 +897,7 @@ func newBytesValue(bytes []byte) cadence.Array { } return cadence.NewArray(result). WithType(&cadence.VariableSizedArrayType{ - ElementType: cadence.UInt8Type{}, + ElementType: cadence.UInt8Type, }) } @@ -1035,7 +1033,7 @@ func addAuthAccountKey(t *testing.T, runtime Runtime, runtimeInterface *testRunt name: "Add key", code: ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(AddKey) &Account) { let key = PublicKey( publicKey: "010203".decodeHex(), signatureAlgorithm: SignatureAlgorithm.ECDSA_P256 @@ -1513,7 +1511,7 @@ func TestRuntimePublicKey(t *testing.T) { } -func TestAuthAccountContracts(t *testing.T) { +func TestRuntimeAuthAccountContracts(t *testing.T) { t.Parallel() @@ -1524,7 +1522,7 @@ func TestAuthAccountContracts(t *testing.T) { script := []byte(` transaction { - prepare(acc: AuthAccount) { + prepare(acc: &Account) { let deployedContract = acc.contracts.get(name: "foo") assert(deployedContract!.name == "foo") } @@ -1566,7 +1564,7 @@ func TestAuthAccountContracts(t *testing.T) { script := []byte(` transaction { - prepare(acc: AuthAccount) { + prepare(acc: &Account) { let deployedContract = acc.contracts.get(name: "foo") assert(deployedContract == nil) } @@ -1679,7 +1677,7 @@ func TestAuthAccountContracts(t *testing.T) { import HelloInterface from 0x42 transaction { - prepare(acc: AuthAccount) { + prepare(acc: &Account) { let hello = acc.contracts.borrow<&HelloInterface>(name: "Hello") assert(hello?.hello() == "Hello!") } @@ -1770,7 +1768,7 @@ func TestAuthAccountContracts(t *testing.T) { import HelloInterface from 0x42 transaction { - prepare(acc: AuthAccount) { + prepare(acc: &Account) { let hello = acc.contracts.borrow<&HelloInterface>(name: "Hello") assert(hello == nil) } @@ -1806,7 +1804,7 @@ func TestAuthAccountContracts(t *testing.T) { Script{ Source: []byte(` transaction { - prepare(acc: AuthAccount) { + prepare(acc: &Account) { let hello = acc.contracts.borrow<&AnyStruct>(name: "Hello") assert(hello == nil) } @@ -1828,7 +1826,7 @@ func TestAuthAccountContracts(t *testing.T) { script := []byte(` transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { let names = signer.contracts.names assert(names.isInstance(Type<[String]>())) @@ -1872,7 +1870,7 @@ func TestAuthAccountContracts(t *testing.T) { script := []byte(` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Mutate) &Account) { signer.contracts.names[0] = "baz" } } @@ -1898,7 +1896,10 @@ func TestAuthAccountContracts(t *testing.T) { Location: nextTransactionLocation(), }, ) - require.NoError(t, err) + + errs := checker.RequireCheckerErrors(t, err, 1) + + assert.IsType(t, &sema.UnauthorizedReferenceAssignmentError{}, errs[0]) }) t.Run("update names through reference", func(t *testing.T) { @@ -1908,8 +1909,8 @@ func TestAuthAccountContracts(t *testing.T) { script := []byte(` transaction { - prepare(signer: AuthAccount) { - var namesRef = &signer.contracts.names as auth(Mutate) &[String] + prepare(signer: auth(Mutate) &Account) { + let namesRef = signer.contracts.names namesRef[0] = "baz" assert(signer.contracts.names[0] == "foo") @@ -1937,11 +1938,14 @@ func TestAuthAccountContracts(t *testing.T) { Location: nextTransactionLocation(), }, ) - require.NoError(t, err) + + errs := checker.RequireCheckerErrors(t, err, 1) + + assert.IsType(t, &sema.UnauthorizedReferenceAssignmentError{}, errs[0]) }) } -func TestPublicAccountContracts(t *testing.T) { +func TestRuntimePublicAccountContracts(t *testing.T) { t.Parallel() @@ -1997,7 +2001,7 @@ func TestPublicAccountContracts(t *testing.T) { cadence.UInt8(2), }, }.WithType(&cadence.VariableSizedArrayType{ - ElementType: cadence.UInt8Type{}, + ElementType: cadence.UInt8Type, }), array.Values[1], ) @@ -2047,7 +2051,7 @@ func TestPublicAccountContracts(t *testing.T) { rt := newTestInterpreterRuntime() script := []byte(` - access(all) fun main(): [String] { + access(all) fun main(): &[String] { let acc = getAccount(0x02) return acc.contracts.names } @@ -2085,91 +2089,9 @@ func TestPublicAccountContracts(t *testing.T) { assert.Equal(t, cadence.String("foo"), array.Values[0]) assert.Equal(t, cadence.String("bar"), array.Values[1]) }) - - t.Run("update names", func(t *testing.T) { - t.Parallel() - - rt := newTestInterpreterRuntime() - - script := []byte(` - access(all) fun main(): [String] { - let acc = getAccount(0x02) - acc.contracts.names[0] = "baz" - return acc.contracts.names - } - `) - - runtimeInterface := &testRuntimeInterface{ - getSigningAccounts: func() ([]Address, error) { - return []Address{{42}}, nil - }, - getAccountContractNames: func(_ Address) ([]string, error) { - return []string{"foo", "bar"}, nil - }, - } - - result, err := rt.ExecuteScript( - Script{ - Source: script, - }, - Context{ - Interface: runtimeInterface, - Location: common.ScriptLocation{}, - }, - ) - require.NoError(t, err) - - require.IsType(t, cadence.Array{}, result) - array := result.(cadence.Array) - - require.Len(t, array.Values, 2) - assert.Equal(t, cadence.String("foo"), array.Values[0]) - assert.Equal(t, cadence.String("bar"), array.Values[1]) - }) - - t.Run("append names", func(t *testing.T) { - t.Parallel() - - rt := newTestInterpreterRuntime() - - script := []byte(` - access(all) fun main(): [String] { - let acc = getAccount(0x02) - acc.contracts.names.append("baz") - return acc.contracts.names - } - `) - - runtimeInterface := &testRuntimeInterface{ - getSigningAccounts: func() ([]Address, error) { - return []Address{{42}}, nil - }, - getAccountContractNames: func(_ Address) ([]string, error) { - return []string{"foo", "bar"}, nil - }, - } - - result, err := rt.ExecuteScript( - Script{ - Source: script, - }, - Context{ - Interface: runtimeInterface, - Location: common.ScriptLocation{}, - }, - ) - require.NoError(t, err) - - require.IsType(t, cadence.Array{}, result) - array := result.(cadence.Array) - - require.Len(t, array.Values, 2) - assert.Equal(t, cadence.String("foo"), array.Values[0]) - assert.Equal(t, cadence.String("bar"), array.Values[1]) - }) } -func TestGetAuthAccount(t *testing.T) { +func TestRuntimeGetAuthAccount(t *testing.T) { t.Parallel() @@ -2180,8 +2102,8 @@ func TestGetAuthAccount(t *testing.T) { script := []byte(` access(all) fun main(): UInt64 { - let acc = getAuthAccount(0x02) - return acc.storageUsed + let acc = getAccount(0x02) + return acc.storage.used } `) @@ -2212,7 +2134,7 @@ func TestGetAuthAccount(t *testing.T) { script := []byte(` access(all) fun main() { - let acc = getAuthAccount("") + let acc = getAuthAccount<&Account>("") } `) @@ -2240,7 +2162,7 @@ func TestGetAuthAccount(t *testing.T) { script := []byte(` access(all) fun main() { - let acc = getAuthAccount() + let acc = getAuthAccount<&Account>() } `) @@ -2268,7 +2190,7 @@ func TestGetAuthAccount(t *testing.T) { script := []byte(` access(all) fun main() { - let acc = getAuthAccount(0x1, 0x2) + let acc = getAuthAccount<&Account>(0x1, 0x2) } `) @@ -2296,8 +2218,8 @@ func TestGetAuthAccount(t *testing.T) { script := []byte(` transaction { prepare() { - let acc = getAuthAccount(0x02) - log(acc.storageUsed) + let acc = getAuthAccount<&Account>(0x02) + log(acc.storage.used) } } `) diff --git a/runtime/ast/transaction_declaration_test.go b/runtime/ast/transaction_declaration_test.go index 44495943a8..b2a35d225c 100644 --- a/runtime/ast/transaction_declaration_test.go +++ b/runtime/ast/transaction_declaration_test.go @@ -393,9 +393,11 @@ func TestTransactionDeclaration_String(t *testing.T) { Identifier: "signer", }, TypeAnnotation: &TypeAnnotation{ - Type: &NominalType{ - Identifier: Identifier{ - Identifier: "AuthAccount", + Type: &ReferenceType{ + Type: &NominalType{ + Identifier: Identifier{ + Identifier: "Account", + }, }, }, }, @@ -449,7 +451,7 @@ func TestTransactionDeclaration_String(t *testing.T) { access(all) let f: @F - prepare(signer: AuthAccount) {} + prepare(signer: &Account) {} pre { true: diff --git a/runtime/attachments_test.go b/runtime/attachments_test.go index de0ede93e7..4e09eba660 100644 --- a/runtime/attachments_test.go +++ b/runtime/attachments_test.go @@ -36,7 +36,7 @@ func newTestInterpreterRuntimeWithAttachments() testInterpreterRuntime { return rt } -func TestAccountAttachmentSaveAndLoad(t *testing.T) { +func TestRuntimeAccountAttachmentSaveAndLoad(t *testing.T) { t.Parallel() storage := newTestLedger(nil, nil) @@ -67,9 +67,9 @@ func TestAccountAttachmentSaveAndLoad(t *testing.T) { transaction1 := []byte(` import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Storage) &Account) { let r <- Test.makeRWithA() - signer.save(<-r, to: /storage/foo) + signer.storage.save(<-r, to: /storage/foo) } } `) @@ -77,8 +77,8 @@ func TestAccountAttachmentSaveAndLoad(t *testing.T) { transaction2 := []byte(` import Test from 0x1 transaction { - prepare(signer: AuthAccount) { - let r <- signer.load<@Test.R>(from: /storage/foo)! + prepare(signer: auth(Storage) &Account) { + let r <- signer.storage.load<@Test.R>(from: /storage/foo)! let i = r[Test.A]!.foo() destroy r log(i) @@ -147,7 +147,7 @@ func TestAccountAttachmentSaveAndLoad(t *testing.T) { require.Equal(t, []string{"3"}, logs) } -func TestAccountAttachmentExportFailure(t *testing.T) { +func TestRuntimeAccountAttachmentExportFailure(t *testing.T) { t.Parallel() storage := newTestLedger(nil, nil) @@ -169,7 +169,7 @@ func TestAccountAttachmentExportFailure(t *testing.T) { script := []byte(` import Test from 0x1 - access(all) fun main(): &Test.A? { + access(all) fun main(): &Test.A? { let r <- Test.makeRWithA() var a = r[Test.A] @@ -237,7 +237,7 @@ func TestAccountAttachmentExportFailure(t *testing.T) { require.ErrorAs(t, err, &interpreter.DestroyedResourceError{}) } -func TestAccountAttachmentExport(t *testing.T) { +func TestRuntimeAccountAttachmentExport(t *testing.T) { t.Parallel() @@ -260,11 +260,11 @@ func TestAccountAttachmentExport(t *testing.T) { script := []byte(` import Test from 0x1 - access(all) fun main(): &Test.A? { + access(all) fun main(): &Test.A? { let r <- Test.makeRWithA() - let authAccount = getAuthAccount(0x1) - authAccount.save(<-r, to: /storage/foo) - let ref = authAccount.borrow<&Test.R>(from: /storage/foo)! + let authAccount = getAuthAccount(0x1) + authAccount.storage.save(<-r, to: /storage/foo) + let ref = authAccount.storage.borrow<&Test.R>(from: /storage/foo)! let a = ref[Test.A] return a } @@ -322,7 +322,7 @@ func TestAccountAttachmentExport(t *testing.T) { require.Equal(t, "A.0000000000000001.Test.A()", v.(cadence.Optional).Value.String()) } -func TestAccountAttachedExport(t *testing.T) { +func TestRuntimeAccountAttachedExport(t *testing.T) { t.Parallel() @@ -345,7 +345,7 @@ func TestAccountAttachedExport(t *testing.T) { script := []byte(` import Test from 0x1 - access(all) fun main(): @Test.R { + access(all) fun main(): @Test.R { return <-Test.makeRWithA() } `) @@ -404,7 +404,7 @@ func TestAccountAttachedExport(t *testing.T) { require.Equal(t, "A.0000000000000001.Test.A()", v.(cadence.Resource).Fields[1].String()) } -func TestAccountAttachmentSaveAndBorrow(t *testing.T) { +func TestRuntimeAccountAttachmentSaveAndBorrow(t *testing.T) { t.Parallel() storage := newTestLedger(nil, nil) @@ -438,9 +438,9 @@ func TestAccountAttachmentSaveAndBorrow(t *testing.T) { transaction1 := []byte(` import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Storage) &Account) { let r <- Test.makeRWithA() - signer.save(<-r, to: /storage/foo) + signer.storage.save(<-r, to: /storage/foo) } } `) @@ -448,8 +448,8 @@ func TestAccountAttachmentSaveAndBorrow(t *testing.T) { transaction2 := []byte(` import Test from 0x1 transaction { - prepare(signer: AuthAccount) { - let r = signer.borrow<&{Test.I}>(from: /storage/foo)! + prepare(signer: auth(Storage) &Account) { + let r = signer.storage.borrow<&{Test.I}>(from: /storage/foo)! let a: &Test.A = r[Test.A]! let i = a.foo() log(i) @@ -518,7 +518,7 @@ func TestAccountAttachmentSaveAndBorrow(t *testing.T) { require.Equal(t, []string{"3"}, logs) } -func TestAccountAttachmentCapability(t *testing.T) { +func TestRuntimeAccountAttachmentCapability(t *testing.T) { t.Parallel() storage := newTestLedger(nil, nil) @@ -552,9 +552,9 @@ func TestAccountAttachmentCapability(t *testing.T) { transaction1 := []byte(` import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Storage, Capabilities, Inbox) &Account) { let r <- Test.makeRWithA() - signer.save(<-r, to: /storage/foo) + signer.storage.save(<-r, to: /storage/foo) let cap = signer.capabilities.storage.issue<&{Test.I}>(/storage/foo)! signer.inbox.publish(cap, name: "foo", recipient: 0x2) } @@ -564,7 +564,7 @@ func TestAccountAttachmentCapability(t *testing.T) { transaction2 := []byte(` import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Inbox) &Account) { let cap = signer.inbox.claim<&{Test.I}>("foo", provider: 0x1)! let ref = cap.borrow()! let i = ref[Test.A]!.foo() @@ -708,12 +708,12 @@ func TestRuntimeAttachmentStorage(t *testing.T) { access(all) fun main(): Int { - let authAccount = getAuthAccount(0x1) + let authAccount = getAuthAccount(0x1) let r <- create R() let r2 <- attach A() to <-r - authAccount.save(<-r2, to: /storage/foo) - let r3 <- authAccount.load<@R>(from: /storage/foo)! + authAccount.storage.save(<-r2, to: /storage/foo) + let r3 <- authAccount.storage.load<@R>(from: /storage/foo)! let i = r3[A]?.foo()! destroy r3 return i @@ -751,12 +751,12 @@ func TestRuntimeAttachmentStorage(t *testing.T) { access(all) fun main(): Int { - let authAccount = getAuthAccount(0x1) + let authAccount = getAuthAccount(0x1) let r <- create R() let r2 <- attach A() to <-r - authAccount.save(<-r2, to: /storage/foo) - let r3 = authAccount.borrow<&R>(from: /storage/foo)! + authAccount.storage.save(<-r2, to: /storage/foo) + let r3 = authAccount.storage.borrow<&R>(from: /storage/foo)! return r3[A]?.foo()! } ` @@ -793,12 +793,12 @@ func TestRuntimeAttachmentStorage(t *testing.T) { access(all) fun main(): Int { - let authAccount = getAuthAccount(0x1) + let authAccount = getAuthAccount(0x1) let pubAccount = getAccount(0x1) let r <- create R() let r2 <- attach A() to <-r - authAccount.save(<-r2, to: /storage/foo) + authAccount.storage.save(<-r2, to: /storage/foo) let cap = authAccount.capabilities.storage .issue<&R>(/storage/foo) authAccount.capabilities.publish(cap, at: /public/foo) @@ -844,12 +844,12 @@ func TestRuntimeAttachmentStorage(t *testing.T) { access(all) fun main(): Int { - let authAccount = getAuthAccount(0x1) + let authAccount = getAuthAccount(0x1) let pubAccount = getAccount(0x1) let r <- create R() let r2 <- attach A() to <-r - authAccount.save(<-r2, to: /storage/foo) + authAccount.storage.save(<-r2, to: /storage/foo) let cap = authAccount.capabilities.storage .issue<&{I}>(/storage/foo) authAccount.capabilities.publish(cap, at: /public/foo) diff --git a/runtime/capabilities_test.go b/runtime/capabilities_test.go index b955f2becc..66b62ad277 100644 --- a/runtime/capabilities_test.go +++ b/runtime/capabilities_test.go @@ -113,7 +113,7 @@ func TestRuntimeCapability_borrowAndCheck(t *testing.T) { access(all) fun setup() { let r <- create R() - self.account.save(<-r, to: /storage/r) + self.account.storage.save(<-r, to: /storage/r) let rCap = self.account.capabilities.storage.issue<&R>(/storage/r) self.account.capabilities.publish(rCap, at: /public/r) @@ -218,11 +218,11 @@ func TestRuntimeCapability_borrowAndCheck(t *testing.T) { fun testSwap(): Int { let ref = self.account.capabilities.get<&R>(/public/r)!.borrow()! - let r <- self.account.load<@R>(from: /storage/r) + let r <- self.account.storage.load<@R>(from: /storage/r) destroy r let r2 <- create R2() - self.account.save(<-r2, to: /storage/r) + self.account.storage.save(<-r2, to: /storage/r) return ref.foo } @@ -341,7 +341,7 @@ func TestRuntimeCapability_borrowAndCheck(t *testing.T) { access(all) fun setup() { let s = S() - self.account.save(s, to: /storage/s) + self.account.storage.save(s, to: /storage/s) let sCap = self.account.capabilities.storage.issue<&S>(/storage/s) self.account.capabilities.publish(sCap, at: /public/s) @@ -446,10 +446,10 @@ func TestRuntimeCapability_borrowAndCheck(t *testing.T) { fun testSwap(): Int { let ref = self.account.capabilities.get<&S>(/public/s)!.borrow()! - self.account.load(from: /storage/s) + self.account.storage.load(from: /storage/s) let s2 = S2() - self.account.save(s2, to: /storage/s) + self.account.storage.save(s2, to: /storage/s) return ref.foo } @@ -536,14 +536,14 @@ func TestRuntimeCapability_borrowAndCheck(t *testing.T) { entitlement X init() { - self.cap = self.account.capabilities.account.issue<&AuthAccount>() + self.cap = self.account.capabilities.account.issue<&Account>() } access(all) fun test() { assert( - self.cap.check<&AuthAccount>(), + self.cap.check<&Account>(), message: "check failed" ) @@ -552,7 +552,7 @@ func TestRuntimeCapability_borrowAndCheck(t *testing.T) { message: "invalid cap address" ) - let ref = self.cap.borrow<&AuthAccount>() + let ref = self.cap.borrow<&Account>() assert( ref != nil, message: "borrow failed" @@ -567,7 +567,7 @@ func TestRuntimeCapability_borrowAndCheck(t *testing.T) { access(all) fun testAuth() { assert( - !self.cap.check(), + !self.cap.check(), message: "invalid check" ) @@ -577,7 +577,7 @@ func TestRuntimeCapability_borrowAndCheck(t *testing.T) { ) assert( - self.cap.borrow() == nil, + self.cap.borrow() == nil, message: "invalid borrow" ) } diff --git a/runtime/capabilitycontrollers_test.go b/runtime/capabilitycontrollers_test.go index a0b3ada799..bf7234a1ce 100644 --- a/runtime/capabilitycontrollers_test.go +++ b/runtime/capabilitycontrollers_test.go @@ -64,14 +64,14 @@ func TestRuntimeCapabilityControllers(t *testing.T) { access(all) resource S {} access(all) fun createAndSaveR(id: Int, storagePath: StoragePath) { - self.account.save( + self.account.storage.save( <-create R(id: id), to: storagePath ) } access(all) fun createAndSaveS(storagePath: StoragePath) { - self.account.save( + self.account.storage.save( <-create S(), to: storagePath ) @@ -179,6 +179,9 @@ func TestRuntimeCapabilityControllers(t *testing.T) { return } + authAccountType := sema.FullyEntitledAccountReferenceType + publicAccountType := sema.AccountReferenceType + testAccount := func(accountType sema.Type, accountExpression string) { testName := fmt.Sprintf( @@ -199,7 +202,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { // Act let gotCap: Capability<&AnyStruct>? = %s.capabilities.get<&AnyStruct>(/public/x) @@ -227,7 +230,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r let publicPath = /public/r let expectedCapID: UInt64 = 1 @@ -262,18 +265,18 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let publicPath = /public/acct let expectedCapID: UInt64 = 1 // Arrange - let issuedCap: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() + let issuedCap: Capability<&Account> = + signer.capabilities.account.issue<&Account>() signer.capabilities.publish(issuedCap, at: publicPath) // Act - let gotCap: Capability<&AuthAccount> = - %s.capabilities.get<&AuthAccount>(publicPath)! + let gotCap: Capability<&Account> = + %s.capabilities.get<&Account>(publicPath)! // Assert assert(issuedCap.id == expectedCapID) @@ -302,7 +305,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r let publicPath = /public/r let expectedCapID: UInt64 = 1 @@ -340,19 +343,19 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let publicPath = /public/acct let expectedCapID: UInt64 = 1 // Arrange - let issuedCap: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() + let issuedCap: Capability<&Account> = + signer.capabilities.account.issue<&Account>() signer.capabilities.publish(issuedCap, at: publicPath) // Act - let gotCap: Capability<&AuthAccount> = - %s.capabilities.get<&AuthAccount>(publicPath)! - let ref: &AuthAccount = gotCap.borrow()! + let gotCap: Capability<&Account> = + %s.capabilities.get<&Account>(publicPath)! + let ref: &Account = gotCap.borrow()! // Assert assert(issuedCap.id == expectedCapID) @@ -382,7 +385,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r let publicPath = /public/r let expectedCapID: UInt64 = 1 @@ -419,13 +422,13 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let publicPath = /public/acct let expectedCapID: UInt64 = 1 // Arrange - let issuedCap: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() + let issuedCap: Capability<&Account> = + signer.capabilities.account.issue<&Account>() signer.capabilities.publish(issuedCap, at: publicPath) // Act @@ -458,7 +461,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r let publicPath = /public/r let expectedCapID: UInt64 = 1 @@ -493,13 +496,13 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let publicPath = /public/acct let expectedCapID: UInt64 = 1 // Arrange - let issuedCap: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() + let issuedCap: Capability<&Account> = + signer.capabilities.account.issue<&Account>() signer.capabilities.publish(issuedCap, at: publicPath) // Act @@ -531,7 +534,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r let publicPath = /public/r let expectedCapID: UInt64 = 1 @@ -567,19 +570,19 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let publicPath = /public/acct let expectedCapID: UInt64 = 1 // Arrange - let issuedCap: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() + let issuedCap: Capability<&Account> = + signer.capabilities.account.issue<&Account>() signer.capabilities.publish(issuedCap, at: publicPath) let unpublishedcap = signer.capabilities.unpublish(publicPath) // Act - let gotCap: Capability<&AuthAccount>? = - %s.capabilities.get<&AuthAccount>(publicPath) + let gotCap: Capability<&Account>? = + %s.capabilities.get<&Account>(publicPath) // Assert assert(issuedCap.id == expectedCapID) @@ -605,7 +608,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { // Act let ref: &AnyStruct? = %s.capabilities.borrow<&AnyStruct>(/public/x) @@ -633,7 +636,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r let publicPath = /public/r let expectedCapID: UInt64 = 1 @@ -667,18 +670,18 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let publicPath = /public/acct let expectedCapID: UInt64 = 1 // Arrange - let issuedCap: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() + let issuedCap: Capability<&Account> = + signer.capabilities.account.issue<&Account>() signer.capabilities.publish(issuedCap, at: publicPath) // Act - let ref: &AuthAccount = - %s.capabilities.borrow<&AuthAccount>(publicPath)! + let ref: &Account = + %s.capabilities.borrow<&Account>(publicPath)! // Assert assert(issuedCap.id == expectedCapID) @@ -706,7 +709,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r let publicPath = /public/r let expectedCapID: UInt64 = 1 @@ -740,21 +743,21 @@ func TestRuntimeCapabilityControllers(t *testing.T) { fmt.Sprintf( // language=cadence ` - import Test from 0x1 + import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let publicPath = /public/acct let expectedCapID: UInt64 = 1 // Arrange - let issuedCap: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() + let issuedCap: Capability<&Account> = + signer.capabilities.account.issue<&Account>() signer.capabilities.publish(issuedCap, at: publicPath) // Act - let ref: auth(Test.X) &AuthAccount? = - %s.capabilities.borrow(publicPath) + let ref: auth(Test.X) &Account? = + %s.capabilities.borrow(publicPath) // Assert assert(issuedCap.id == expectedCapID) @@ -782,7 +785,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r let publicPath = /public/r let expectedCapID: UInt64 = 1 @@ -817,13 +820,13 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let publicPath = /public/acct let expectedCapID: UInt64 = 1 // Arrange - let issuedCap: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() + let issuedCap: Capability<&Account> = + signer.capabilities.account.issue<&Account>() signer.capabilities.publish(issuedCap, at: publicPath) // Act @@ -855,7 +858,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r let publicPath = /public/r let expectedCapID: UInt64 = 1 @@ -891,19 +894,19 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let publicPath = /public/acct let expectedCapID: UInt64 = 1 // Arrange - let issuedCap: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() + let issuedCap: Capability<&Account> = + signer.capabilities.account.issue<&Account>() signer.capabilities.publish(issuedCap, at: publicPath) let unpublishedcap = signer.capabilities.unpublish(publicPath) // Act - let ref: &AuthAccount? = - %s.capabilities.borrow<&AuthAccount>(publicPath) + let ref: &Account? = + %s.capabilities.borrow<&Account>(publicPath) // Assert assert(issuedCap.id == expectedCapID) @@ -919,7 +922,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { }) }) - if accountType == sema.AuthAccountType { + if accountType == authAccountType { t.Run("publish, existing published", func(t *testing.T) { @@ -932,7 +935,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r let publicPath = /public/r let expectedCapID: UInt64 = 1 @@ -959,13 +962,13 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let publicPath = /public/acct let expectedCapID: UInt64 = 1 // Arrange - let issuedCap: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() + let issuedCap: Capability<&Account> = + signer.capabilities.account.issue<&Account>() signer.capabilities.publish(issuedCap, at: publicPath) // Act @@ -989,7 +992,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let publicPath = /public/r // Act @@ -1008,13 +1011,13 @@ func TestRuntimeCapabilityControllers(t *testing.T) { } for accountType, accountExpression := range map[sema.Type]string{ - sema.AuthAccountType: "signer", - sema.PublicAccountType: "getAccount(0x1)", + authAccountType: "signer", + publicAccountType: "getAccount(0x1)", } { testAccount(accountType, accountExpression) } - t.Run("AuthAccount.StorageCapabilities", func(t *testing.T) { + t.Run("Account.StorageCapabilities", func(t *testing.T) { t.Parallel() @@ -1028,7 +1031,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath1 = /storage/r let storagePath2 = /storage/r2 @@ -1062,7 +1065,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { // Act let controller1: &StorageCapabilityController? = signer.capabilities.storage.getController(byCapabilityID: 0) @@ -1087,10 +1090,10 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { // Arrange - let issuedCap: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() + let issuedCap: Capability<&Account> = + signer.capabilities.account.issue<&Account>() // Act let controller: &StorageCapabilityController? = @@ -1115,7 +1118,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath1 = /storage/r let storagePath2 = /storage/r2 @@ -1172,7 +1175,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath1 = /storage/r let storagePath2 = /storage/r2 @@ -1225,7 +1228,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r // Act @@ -1257,7 +1260,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath1 = /storage/r let storagePath2 = /storage/r2 @@ -1325,7 +1328,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r // Arrange @@ -1364,7 +1367,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r // Arrange @@ -1397,7 +1400,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r // Arrange @@ -1433,7 +1436,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r // Arrange @@ -1466,7 +1469,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r // Arrange @@ -1493,7 +1496,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { }) }) - t.Run("AuthAccount.AccountCapabilities", func(t *testing.T) { + t.Run("Account.AccountCapabilities", func(t *testing.T) { t.Parallel() @@ -1505,14 +1508,14 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { // Act - let issuedCap1: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() - let issuedCap2: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() - let issuedCap3: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() + let issuedCap1: Capability<&Account> = + signer.capabilities.account.issue<&Account>() + let issuedCap2: Capability<&Account> = + signer.capabilities.account.issue<&Account>() + let issuedCap3: Capability<&Account> = + signer.capabilities.account.issue<&Account>() // Assert assert(issuedCap1.id == 1) @@ -1533,7 +1536,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { // Act let controller1: &AccountCapabilityController? = signer.capabilities.account.getController(byCapabilityID: 0) @@ -1558,7 +1561,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { // Arrange let issuedCap: Capability<&AnyStruct> = signer.capabilities.storage.issue<&AnyStruct>(/storage/x) @@ -1584,14 +1587,14 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { // Arrange - let issuedCap1: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() - let issuedCap2: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() - let issuedCap3: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() + let issuedCap1: Capability<&Account> = + signer.capabilities.account.issue<&Account>() + let issuedCap2: Capability<&Account> = + signer.capabilities.account.issue<&Account>() + let issuedCap3: Capability<&Account> = + signer.capabilities.account.issue<&Account>() // Act let controller1: &AccountCapabilityController? = @@ -1603,13 +1606,13 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // Assert assert(controller1!.capabilityID == 1) - assert(controller1!.borrowType == Type<&AuthAccount>()) + assert(controller1!.borrowType == Type<&Account>()) assert(controller2!.capabilityID == 2) - assert(controller2!.borrowType == Type<&AuthAccount>()) + assert(controller2!.borrowType == Type<&Account>()) assert(controller3!.capabilityID == 3) - assert(controller3!.borrowType == Type<&AuthAccount>()) + assert(controller3!.borrowType == Type<&Account>()) } } `, @@ -1627,15 +1630,15 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { // Arrange - let issuedCap1: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() - let issuedCap2: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() - let issuedCap3: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() + let issuedCap1: Capability<&Account> = + signer.capabilities.account.issue<&Account>() + let issuedCap2: Capability<&Account> = + signer.capabilities.account.issue<&Account>() + let issuedCap3: Capability<&Account> = + signer.capabilities.account.issue<&Account>() // Act let controllers: [&AccountCapabilityController] = @@ -1671,7 +1674,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { // Act var called = false @@ -1701,14 +1704,14 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { // Arrange - let issuedCap1: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() - let issuedCap2: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() - let issuedCap3: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() + let issuedCap1: Capability<&Account> = + signer.capabilities.account.issue<&Account>() + let issuedCap2: Capability<&Account> = + signer.capabilities.account.issue<&Account>() + let issuedCap3: Capability<&Account> = + signer.capabilities.account.issue<&Account>() // Act let controllers: [&AccountCapabilityController] = [] @@ -1749,12 +1752,12 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { // Arrange - let issuedCap1: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() - let issuedCap2: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() + let issuedCap1: Capability<&Account> = + signer.capabilities.account.issue<&Account>() + let issuedCap2: Capability<&Account> = + signer.capabilities.account.issue<&Account>() // Act var stopped = false @@ -1783,15 +1786,15 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { // Arrange - signer.capabilities.account.issue<&AuthAccount>() + signer.capabilities.account.issue<&Account>() // Act signer.capabilities.account.forEachController( fun (controller: &AccountCapabilityController): Bool { - signer.capabilities.account.issue<&AuthAccount>() + signer.capabilities.account.issue<&Account>() return true } @@ -1814,15 +1817,15 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { // Arrange - signer.capabilities.account.issue<&AuthAccount>() + signer.capabilities.account.issue<&Account>() // Act signer.capabilities.account.forEachController( fun (controller: &AccountCapabilityController): Bool { - signer.capabilities.account.issue<&AuthAccount>() + signer.capabilities.account.issue<&Account>() return false } @@ -1842,9 +1845,9 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { // Arrange - signer.capabilities.account.issue<&AuthAccount>() + signer.capabilities.account.issue<&Account>() // Act signer.capabilities.account.forEachController( @@ -1873,9 +1876,9 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { // Arrange - signer.capabilities.account.issue<&AuthAccount>() + signer.capabilities.account.issue<&Account>() // Act signer.capabilities.account.forEachController( @@ -1907,7 +1910,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Storage, Capabilities) &Account) { let storagePath = /storage/r let resourceID = 42 @@ -1944,7 +1947,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r // Arrange @@ -1988,7 +1991,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath1 = /storage/r let storagePath2 = /storage/r2 @@ -2092,7 +2095,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath1 = /storage/r let storagePath2 = /storage/empty let resourceID = 42 @@ -2131,7 +2134,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath1 = /storage/r let storagePath2 = /storage/r2 let resourceID1 = 42 @@ -2173,7 +2176,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath1 = /storage/r let storagePath2 = /storage/s let resourceID = 42 @@ -2218,7 +2221,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r // Arrange @@ -2257,7 +2260,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r // Arrange @@ -2287,7 +2290,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r // Arrange @@ -2317,7 +2320,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r // Arrange @@ -2347,7 +2350,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r // Arrange @@ -2382,7 +2385,7 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { let storagePath = /storage/r let resourceID = 42 @@ -2425,11 +2428,11 @@ func TestRuntimeCapabilityControllers(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { // Arrange - let issuedCap: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() + let issuedCap: Capability<&Account> = + signer.capabilities.account.issue<&Account>() let controller1: &AccountCapabilityController = signer.capabilities.account.getController(byCapabilityID: issuedCap.id)! let controller2: &AccountCapabilityController = @@ -2440,8 +2443,8 @@ func TestRuntimeCapabilityControllers(t *testing.T) { let controller2Cap = controller2.capability // Assert - assert(controller1Cap.borrow<&AuthAccount>() != nil) - assert(controller2Cap.borrow<&AuthAccount>() != nil) + assert(controller1Cap.borrow<&Account>() != nil) + assert(controller2Cap.borrow<&Account>() != nil) } } `, @@ -2456,10 +2459,10 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { // Arrange - let issuedCap: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() + let issuedCap: Capability<&Account> = + signer.capabilities.account.issue<&Account>() let controller1: &AccountCapabilityController = signer.capabilities.account.getController(byCapabilityID: issuedCap.id)! let controller2: &AccountCapabilityController = @@ -2496,10 +2499,10 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { // Arrange - let issuedCap: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() + let issuedCap: Capability<&Account> = + signer.capabilities.account.issue<&Account>() let controller: &AccountCapabilityController? = signer.capabilities.account.getController(byCapabilityID: issuedCap.id) @@ -2531,10 +2534,10 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { // Arrange - let issuedCap: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() + let issuedCap: Capability<&Account> = + signer.capabilities.account.issue<&Account>() let controller: &AccountCapabilityController? = signer.capabilities.account.getController(byCapabilityID: issuedCap.id) @@ -2557,10 +2560,10 @@ func TestRuntimeCapabilityControllers(t *testing.T) { // language=cadence ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { // Arrange - let issuedCap: Capability<&AuthAccount> = - signer.capabilities.account.issue<&AuthAccount>() + let issuedCap: Capability<&Account> = + signer.capabilities.account.issue<&Account>() assert(issuedCap.check()) assert(issuedCap.borrow() != nil) @@ -2609,14 +2612,14 @@ func TestRuntimeCapabilityBorrowAsInheritedInterface(t *testing.T) { import Test from 0x01 transaction { - prepare(acct: AuthAccount) { - acct.save(<- Test.createVaultImpl(), to: /storage/r) + prepare(acct: auth(Storage, Capabilities) &Account) { + acct.storage.save(<-Test.createVaultImpl(), to: /storage/r) let cap = acct.capabilities.storage.issue<&{Test.Balance}>(/storage/r) acct.capabilities.publish(cap, at: /public/r) - let vaultRef = acct.capabilities.get<&{Test.Balance}>(/public/r)! - .borrow() ?? panic("Could not borrow Balance reference to the Vault") + let vaultRef = acct.capabilities.borrow<&{Test.Balance}>(/public/r) + ?? panic("Could not borrow Balance reference to the Vault") } } `) diff --git a/runtime/cmd/minifier/minifier_test.go b/runtime/cmd/minifier/minifier_test.go index c84fe6edee..a7fcbe924c 100644 --- a/runtime/cmd/minifier/minifier_test.go +++ b/runtime/cmd/minifier/minifier_test.go @@ -40,10 +40,10 @@ transaction(amount: UFix64, to: Address) { // The Vault resource that holds the tokens that are being transferred let sentVault: @FungibleToken.Vault - prepare(signer: AuthAccount) { + prepare(signer: &Account) { // Get a reference to the signer's stored vault - let vaultRef = signer.borrow<&ExampleToken.Vault>(from: /storage/exampleTokenVault) + let vaultRef = signer.storage.borrow<&ExampleToken.Vault>(from: /storage/exampleTokenVault) ?? panic("Could not borrow reference to the owner's Vault!") // Withdraw tokens from the signer's stored vault @@ -70,8 +70,8 @@ const expectedOutput = `import FungibleToken from 0xFUNGIBLETOKENADDRESS import ExampleToken from 0xTOKENADDRESS transaction(amount: UFix64, to: Address) { let sentVault: @FungibleToken.Vault -prepare(signer: AuthAccount) { -let vaultRef = signer.borrow<&ExampleToken.Vault>(from: /storage/exampleTokenVault) +prepare(signer: &Account) { +let vaultRef = signer.storage.borrow<&ExampleToken.Vault>(from: /storage/exampleTokenVault) ?? panic("Could not borrow reference to the owner's Vault!") self.sentVault <- vaultRef.withdraw(amount: amount) } diff --git a/runtime/common/memorykind.go b/runtime/common/memorykind.go index e6270a1f91..695e0d8c83 100644 --- a/runtime/common/memorykind.go +++ b/runtime/common/memorykind.go @@ -41,7 +41,6 @@ const ( MemoryKindPathValue MemoryKindCapabilityValue MemoryKindStorageReferenceValue - MemoryKindAccountReferenceValue MemoryKindEphemeralReferenceValue MemoryKindInterpretedFunctionValue MemoryKindHostFunctionValue diff --git a/runtime/common/memorykind_string.go b/runtime/common/memorykind_string.go index c85f747910..8ee42934db 100644 --- a/runtime/common/memorykind_string.go +++ b/runtime/common/memorykind_string.go @@ -22,193 +22,192 @@ func _() { _ = x[MemoryKindPathValue-11] _ = x[MemoryKindCapabilityValue-12] _ = x[MemoryKindStorageReferenceValue-13] - _ = x[MemoryKindAccountReferenceValue-14] - _ = x[MemoryKindEphemeralReferenceValue-15] - _ = x[MemoryKindInterpretedFunctionValue-16] - _ = x[MemoryKindHostFunctionValue-17] - _ = x[MemoryKindBoundFunctionValue-18] - _ = x[MemoryKindBigInt-19] - _ = x[MemoryKindSimpleCompositeValue-20] - _ = x[MemoryKindPublishedValue-21] - _ = x[MemoryKindStorageCapabilityControllerValue-22] - _ = x[MemoryKindAccountCapabilityControllerValue-23] - _ = x[MemoryKindAtreeArrayDataSlab-24] - _ = x[MemoryKindAtreeArrayMetaDataSlab-25] - _ = x[MemoryKindAtreeArrayElementOverhead-26] - _ = x[MemoryKindAtreeMapDataSlab-27] - _ = x[MemoryKindAtreeMapMetaDataSlab-28] - _ = x[MemoryKindAtreeMapElementOverhead-29] - _ = x[MemoryKindAtreeMapPreAllocatedElement-30] - _ = x[MemoryKindAtreeEncodedSlab-31] - _ = x[MemoryKindPrimitiveStaticType-32] - _ = x[MemoryKindCompositeStaticType-33] - _ = x[MemoryKindInterfaceStaticType-34] - _ = x[MemoryKindVariableSizedStaticType-35] - _ = x[MemoryKindConstantSizedStaticType-36] - _ = x[MemoryKindDictionaryStaticType-37] - _ = x[MemoryKindOptionalStaticType-38] - _ = x[MemoryKindIntersectionStaticType-39] - _ = x[MemoryKindEntitlementSetStaticAccess-40] - _ = x[MemoryKindEntitlementMapStaticAccess-41] - _ = x[MemoryKindReferenceStaticType-42] - _ = x[MemoryKindCapabilityStaticType-43] - _ = x[MemoryKindFunctionStaticType-44] - _ = x[MemoryKindCadenceVoidValue-45] - _ = x[MemoryKindCadenceOptionalValue-46] - _ = x[MemoryKindCadenceBoolValue-47] - _ = x[MemoryKindCadenceStringValue-48] - _ = x[MemoryKindCadenceCharacterValue-49] - _ = x[MemoryKindCadenceAddressValue-50] - _ = x[MemoryKindCadenceIntValue-51] - _ = x[MemoryKindCadenceNumberValue-52] - _ = x[MemoryKindCadenceArrayValueBase-53] - _ = x[MemoryKindCadenceArrayValueLength-54] - _ = x[MemoryKindCadenceDictionaryValue-55] - _ = x[MemoryKindCadenceKeyValuePair-56] - _ = x[MemoryKindCadenceStructValueBase-57] - _ = x[MemoryKindCadenceStructValueSize-58] - _ = x[MemoryKindCadenceResourceValueBase-59] - _ = x[MemoryKindCadenceAttachmentValueBase-60] - _ = x[MemoryKindCadenceResourceValueSize-61] - _ = x[MemoryKindCadenceAttachmentValueSize-62] - _ = x[MemoryKindCadenceEventValueBase-63] - _ = x[MemoryKindCadenceEventValueSize-64] - _ = x[MemoryKindCadenceContractValueBase-65] - _ = x[MemoryKindCadenceContractValueSize-66] - _ = x[MemoryKindCadenceEnumValueBase-67] - _ = x[MemoryKindCadenceEnumValueSize-68] - _ = x[MemoryKindCadencePathValue-69] - _ = x[MemoryKindCadenceTypeValue-70] - _ = x[MemoryKindCadenceCapabilityValue-71] - _ = x[MemoryKindCadenceFunctionValue-72] - _ = x[MemoryKindCadenceOptionalType-73] - _ = x[MemoryKindCadenceVariableSizedArrayType-74] - _ = x[MemoryKindCadenceConstantSizedArrayType-75] - _ = x[MemoryKindCadenceDictionaryType-76] - _ = x[MemoryKindCadenceField-77] - _ = x[MemoryKindCadenceParameter-78] - _ = x[MemoryKindCadenceTypeParameter-79] - _ = x[MemoryKindCadenceStructType-80] - _ = x[MemoryKindCadenceResourceType-81] - _ = x[MemoryKindCadenceAttachmentType-82] - _ = x[MemoryKindCadenceEventType-83] - _ = x[MemoryKindCadenceContractType-84] - _ = x[MemoryKindCadenceStructInterfaceType-85] - _ = x[MemoryKindCadenceResourceInterfaceType-86] - _ = x[MemoryKindCadenceContractInterfaceType-87] - _ = x[MemoryKindCadenceFunctionType-88] - _ = x[MemoryKindCadenceEntitlementSetAccess-89] - _ = x[MemoryKindCadenceEntitlementMapAccess-90] - _ = x[MemoryKindCadenceReferenceType-91] - _ = x[MemoryKindCadenceIntersectionType-92] - _ = x[MemoryKindCadenceCapabilityType-93] - _ = x[MemoryKindCadenceEnumType-94] - _ = x[MemoryKindRawString-95] - _ = x[MemoryKindAddressLocation-96] - _ = x[MemoryKindBytes-97] - _ = x[MemoryKindVariable-98] - _ = x[MemoryKindCompositeTypeInfo-99] - _ = x[MemoryKindCompositeField-100] - _ = x[MemoryKindInvocation-101] - _ = x[MemoryKindStorageMap-102] - _ = x[MemoryKindStorageKey-103] - _ = x[MemoryKindTypeToken-104] - _ = x[MemoryKindErrorToken-105] - _ = x[MemoryKindSpaceToken-106] - _ = x[MemoryKindProgram-107] - _ = x[MemoryKindIdentifier-108] - _ = x[MemoryKindArgument-109] - _ = x[MemoryKindBlock-110] - _ = x[MemoryKindFunctionBlock-111] - _ = x[MemoryKindParameter-112] - _ = x[MemoryKindParameterList-113] - _ = x[MemoryKindTypeParameter-114] - _ = x[MemoryKindTypeParameterList-115] - _ = x[MemoryKindTransfer-116] - _ = x[MemoryKindMembers-117] - _ = x[MemoryKindTypeAnnotation-118] - _ = x[MemoryKindDictionaryEntry-119] - _ = x[MemoryKindFunctionDeclaration-120] - _ = x[MemoryKindCompositeDeclaration-121] - _ = x[MemoryKindAttachmentDeclaration-122] - _ = x[MemoryKindInterfaceDeclaration-123] - _ = x[MemoryKindEntitlementDeclaration-124] - _ = x[MemoryKindEntitlementMappingElement-125] - _ = x[MemoryKindEntitlementMappingDeclaration-126] - _ = x[MemoryKindEnumCaseDeclaration-127] - _ = x[MemoryKindFieldDeclaration-128] - _ = x[MemoryKindTransactionDeclaration-129] - _ = x[MemoryKindImportDeclaration-130] - _ = x[MemoryKindVariableDeclaration-131] - _ = x[MemoryKindSpecialFunctionDeclaration-132] - _ = x[MemoryKindPragmaDeclaration-133] - _ = x[MemoryKindAssignmentStatement-134] - _ = x[MemoryKindBreakStatement-135] - _ = x[MemoryKindContinueStatement-136] - _ = x[MemoryKindEmitStatement-137] - _ = x[MemoryKindExpressionStatement-138] - _ = x[MemoryKindForStatement-139] - _ = x[MemoryKindIfStatement-140] - _ = x[MemoryKindReturnStatement-141] - _ = x[MemoryKindSwapStatement-142] - _ = x[MemoryKindSwitchStatement-143] - _ = x[MemoryKindWhileStatement-144] - _ = x[MemoryKindRemoveStatement-145] - _ = x[MemoryKindBooleanExpression-146] - _ = x[MemoryKindVoidExpression-147] - _ = x[MemoryKindNilExpression-148] - _ = x[MemoryKindStringExpression-149] - _ = x[MemoryKindIntegerExpression-150] - _ = x[MemoryKindFixedPointExpression-151] - _ = x[MemoryKindArrayExpression-152] - _ = x[MemoryKindDictionaryExpression-153] - _ = x[MemoryKindIdentifierExpression-154] - _ = x[MemoryKindInvocationExpression-155] - _ = x[MemoryKindMemberExpression-156] - _ = x[MemoryKindIndexExpression-157] - _ = x[MemoryKindConditionalExpression-158] - _ = x[MemoryKindUnaryExpression-159] - _ = x[MemoryKindBinaryExpression-160] - _ = x[MemoryKindFunctionExpression-161] - _ = x[MemoryKindCastingExpression-162] - _ = x[MemoryKindCreateExpression-163] - _ = x[MemoryKindDestroyExpression-164] - _ = x[MemoryKindReferenceExpression-165] - _ = x[MemoryKindForceExpression-166] - _ = x[MemoryKindPathExpression-167] - _ = x[MemoryKindAttachExpression-168] - _ = x[MemoryKindConstantSizedType-169] - _ = x[MemoryKindDictionaryType-170] - _ = x[MemoryKindFunctionType-171] - _ = x[MemoryKindInstantiationType-172] - _ = x[MemoryKindNominalType-173] - _ = x[MemoryKindOptionalType-174] - _ = x[MemoryKindReferenceType-175] - _ = x[MemoryKindIntersectionType-176] - _ = x[MemoryKindVariableSizedType-177] - _ = x[MemoryKindPosition-178] - _ = x[MemoryKindRange-179] - _ = x[MemoryKindElaboration-180] - _ = x[MemoryKindActivation-181] - _ = x[MemoryKindActivationEntries-182] - _ = x[MemoryKindVariableSizedSemaType-183] - _ = x[MemoryKindConstantSizedSemaType-184] - _ = x[MemoryKindDictionarySemaType-185] - _ = x[MemoryKindOptionalSemaType-186] - _ = x[MemoryKindIntersectionSemaType-187] - _ = x[MemoryKindReferenceSemaType-188] - _ = x[MemoryKindEntitlementSemaType-189] - _ = x[MemoryKindEntitlementMapSemaType-190] - _ = x[MemoryKindCapabilitySemaType-191] - _ = x[MemoryKindOrderedMap-192] - _ = x[MemoryKindOrderedMapEntryList-193] - _ = x[MemoryKindOrderedMapEntry-194] - _ = x[MemoryKindLast-195] + _ = x[MemoryKindEphemeralReferenceValue-14] + _ = x[MemoryKindInterpretedFunctionValue-15] + _ = x[MemoryKindHostFunctionValue-16] + _ = x[MemoryKindBoundFunctionValue-17] + _ = x[MemoryKindBigInt-18] + _ = x[MemoryKindSimpleCompositeValue-19] + _ = x[MemoryKindPublishedValue-20] + _ = x[MemoryKindStorageCapabilityControllerValue-21] + _ = x[MemoryKindAccountCapabilityControllerValue-22] + _ = x[MemoryKindAtreeArrayDataSlab-23] + _ = x[MemoryKindAtreeArrayMetaDataSlab-24] + _ = x[MemoryKindAtreeArrayElementOverhead-25] + _ = x[MemoryKindAtreeMapDataSlab-26] + _ = x[MemoryKindAtreeMapMetaDataSlab-27] + _ = x[MemoryKindAtreeMapElementOverhead-28] + _ = x[MemoryKindAtreeMapPreAllocatedElement-29] + _ = x[MemoryKindAtreeEncodedSlab-30] + _ = x[MemoryKindPrimitiveStaticType-31] + _ = x[MemoryKindCompositeStaticType-32] + _ = x[MemoryKindInterfaceStaticType-33] + _ = x[MemoryKindVariableSizedStaticType-34] + _ = x[MemoryKindConstantSizedStaticType-35] + _ = x[MemoryKindDictionaryStaticType-36] + _ = x[MemoryKindOptionalStaticType-37] + _ = x[MemoryKindIntersectionStaticType-38] + _ = x[MemoryKindEntitlementSetStaticAccess-39] + _ = x[MemoryKindEntitlementMapStaticAccess-40] + _ = x[MemoryKindReferenceStaticType-41] + _ = x[MemoryKindCapabilityStaticType-42] + _ = x[MemoryKindFunctionStaticType-43] + _ = x[MemoryKindCadenceVoidValue-44] + _ = x[MemoryKindCadenceOptionalValue-45] + _ = x[MemoryKindCadenceBoolValue-46] + _ = x[MemoryKindCadenceStringValue-47] + _ = x[MemoryKindCadenceCharacterValue-48] + _ = x[MemoryKindCadenceAddressValue-49] + _ = x[MemoryKindCadenceIntValue-50] + _ = x[MemoryKindCadenceNumberValue-51] + _ = x[MemoryKindCadenceArrayValueBase-52] + _ = x[MemoryKindCadenceArrayValueLength-53] + _ = x[MemoryKindCadenceDictionaryValue-54] + _ = x[MemoryKindCadenceKeyValuePair-55] + _ = x[MemoryKindCadenceStructValueBase-56] + _ = x[MemoryKindCadenceStructValueSize-57] + _ = x[MemoryKindCadenceResourceValueBase-58] + _ = x[MemoryKindCadenceAttachmentValueBase-59] + _ = x[MemoryKindCadenceResourceValueSize-60] + _ = x[MemoryKindCadenceAttachmentValueSize-61] + _ = x[MemoryKindCadenceEventValueBase-62] + _ = x[MemoryKindCadenceEventValueSize-63] + _ = x[MemoryKindCadenceContractValueBase-64] + _ = x[MemoryKindCadenceContractValueSize-65] + _ = x[MemoryKindCadenceEnumValueBase-66] + _ = x[MemoryKindCadenceEnumValueSize-67] + _ = x[MemoryKindCadencePathValue-68] + _ = x[MemoryKindCadenceTypeValue-69] + _ = x[MemoryKindCadenceCapabilityValue-70] + _ = x[MemoryKindCadenceFunctionValue-71] + _ = x[MemoryKindCadenceOptionalType-72] + _ = x[MemoryKindCadenceVariableSizedArrayType-73] + _ = x[MemoryKindCadenceConstantSizedArrayType-74] + _ = x[MemoryKindCadenceDictionaryType-75] + _ = x[MemoryKindCadenceField-76] + _ = x[MemoryKindCadenceParameter-77] + _ = x[MemoryKindCadenceTypeParameter-78] + _ = x[MemoryKindCadenceStructType-79] + _ = x[MemoryKindCadenceResourceType-80] + _ = x[MemoryKindCadenceAttachmentType-81] + _ = x[MemoryKindCadenceEventType-82] + _ = x[MemoryKindCadenceContractType-83] + _ = x[MemoryKindCadenceStructInterfaceType-84] + _ = x[MemoryKindCadenceResourceInterfaceType-85] + _ = x[MemoryKindCadenceContractInterfaceType-86] + _ = x[MemoryKindCadenceFunctionType-87] + _ = x[MemoryKindCadenceEntitlementSetAccess-88] + _ = x[MemoryKindCadenceEntitlementMapAccess-89] + _ = x[MemoryKindCadenceReferenceType-90] + _ = x[MemoryKindCadenceIntersectionType-91] + _ = x[MemoryKindCadenceCapabilityType-92] + _ = x[MemoryKindCadenceEnumType-93] + _ = x[MemoryKindRawString-94] + _ = x[MemoryKindAddressLocation-95] + _ = x[MemoryKindBytes-96] + _ = x[MemoryKindVariable-97] + _ = x[MemoryKindCompositeTypeInfo-98] + _ = x[MemoryKindCompositeField-99] + _ = x[MemoryKindInvocation-100] + _ = x[MemoryKindStorageMap-101] + _ = x[MemoryKindStorageKey-102] + _ = x[MemoryKindTypeToken-103] + _ = x[MemoryKindErrorToken-104] + _ = x[MemoryKindSpaceToken-105] + _ = x[MemoryKindProgram-106] + _ = x[MemoryKindIdentifier-107] + _ = x[MemoryKindArgument-108] + _ = x[MemoryKindBlock-109] + _ = x[MemoryKindFunctionBlock-110] + _ = x[MemoryKindParameter-111] + _ = x[MemoryKindParameterList-112] + _ = x[MemoryKindTypeParameter-113] + _ = x[MemoryKindTypeParameterList-114] + _ = x[MemoryKindTransfer-115] + _ = x[MemoryKindMembers-116] + _ = x[MemoryKindTypeAnnotation-117] + _ = x[MemoryKindDictionaryEntry-118] + _ = x[MemoryKindFunctionDeclaration-119] + _ = x[MemoryKindCompositeDeclaration-120] + _ = x[MemoryKindAttachmentDeclaration-121] + _ = x[MemoryKindInterfaceDeclaration-122] + _ = x[MemoryKindEntitlementDeclaration-123] + _ = x[MemoryKindEntitlementMappingElement-124] + _ = x[MemoryKindEntitlementMappingDeclaration-125] + _ = x[MemoryKindEnumCaseDeclaration-126] + _ = x[MemoryKindFieldDeclaration-127] + _ = x[MemoryKindTransactionDeclaration-128] + _ = x[MemoryKindImportDeclaration-129] + _ = x[MemoryKindVariableDeclaration-130] + _ = x[MemoryKindSpecialFunctionDeclaration-131] + _ = x[MemoryKindPragmaDeclaration-132] + _ = x[MemoryKindAssignmentStatement-133] + _ = x[MemoryKindBreakStatement-134] + _ = x[MemoryKindContinueStatement-135] + _ = x[MemoryKindEmitStatement-136] + _ = x[MemoryKindExpressionStatement-137] + _ = x[MemoryKindForStatement-138] + _ = x[MemoryKindIfStatement-139] + _ = x[MemoryKindReturnStatement-140] + _ = x[MemoryKindSwapStatement-141] + _ = x[MemoryKindSwitchStatement-142] + _ = x[MemoryKindWhileStatement-143] + _ = x[MemoryKindRemoveStatement-144] + _ = x[MemoryKindBooleanExpression-145] + _ = x[MemoryKindVoidExpression-146] + _ = x[MemoryKindNilExpression-147] + _ = x[MemoryKindStringExpression-148] + _ = x[MemoryKindIntegerExpression-149] + _ = x[MemoryKindFixedPointExpression-150] + _ = x[MemoryKindArrayExpression-151] + _ = x[MemoryKindDictionaryExpression-152] + _ = x[MemoryKindIdentifierExpression-153] + _ = x[MemoryKindInvocationExpression-154] + _ = x[MemoryKindMemberExpression-155] + _ = x[MemoryKindIndexExpression-156] + _ = x[MemoryKindConditionalExpression-157] + _ = x[MemoryKindUnaryExpression-158] + _ = x[MemoryKindBinaryExpression-159] + _ = x[MemoryKindFunctionExpression-160] + _ = x[MemoryKindCastingExpression-161] + _ = x[MemoryKindCreateExpression-162] + _ = x[MemoryKindDestroyExpression-163] + _ = x[MemoryKindReferenceExpression-164] + _ = x[MemoryKindForceExpression-165] + _ = x[MemoryKindPathExpression-166] + _ = x[MemoryKindAttachExpression-167] + _ = x[MemoryKindConstantSizedType-168] + _ = x[MemoryKindDictionaryType-169] + _ = x[MemoryKindFunctionType-170] + _ = x[MemoryKindInstantiationType-171] + _ = x[MemoryKindNominalType-172] + _ = x[MemoryKindOptionalType-173] + _ = x[MemoryKindReferenceType-174] + _ = x[MemoryKindIntersectionType-175] + _ = x[MemoryKindVariableSizedType-176] + _ = x[MemoryKindPosition-177] + _ = x[MemoryKindRange-178] + _ = x[MemoryKindElaboration-179] + _ = x[MemoryKindActivation-180] + _ = x[MemoryKindActivationEntries-181] + _ = x[MemoryKindVariableSizedSemaType-182] + _ = x[MemoryKindConstantSizedSemaType-183] + _ = x[MemoryKindDictionarySemaType-184] + _ = x[MemoryKindOptionalSemaType-185] + _ = x[MemoryKindIntersectionSemaType-186] + _ = x[MemoryKindReferenceSemaType-187] + _ = x[MemoryKindEntitlementSemaType-188] + _ = x[MemoryKindEntitlementMapSemaType-189] + _ = x[MemoryKindCapabilitySemaType-190] + _ = x[MemoryKindOrderedMap-191] + _ = x[MemoryKindOrderedMapEntryList-192] + _ = x[MemoryKindOrderedMapEntry-193] + _ = x[MemoryKindLast-194] } -const _MemoryKind_name = "UnknownAddressValueStringValueCharacterValueNumberValueArrayValueBaseDictionaryValueBaseCompositeValueBaseSimpleCompositeValueBaseOptionalValueTypeValuePathValueCapabilityValueStorageReferenceValueAccountReferenceValueEphemeralReferenceValueInterpretedFunctionValueHostFunctionValueBoundFunctionValueBigIntSimpleCompositeValuePublishedValueStorageCapabilityControllerValueAccountCapabilityControllerValueAtreeArrayDataSlabAtreeArrayMetaDataSlabAtreeArrayElementOverheadAtreeMapDataSlabAtreeMapMetaDataSlabAtreeMapElementOverheadAtreeMapPreAllocatedElementAtreeEncodedSlabPrimitiveStaticTypeCompositeStaticTypeInterfaceStaticTypeVariableSizedStaticTypeConstantSizedStaticTypeDictionaryStaticTypeOptionalStaticTypeIntersectionStaticTypeEntitlementSetStaticAccessEntitlementMapStaticAccessReferenceStaticTypeCapabilityStaticTypeFunctionStaticTypeCadenceVoidValueCadenceOptionalValueCadenceBoolValueCadenceStringValueCadenceCharacterValueCadenceAddressValueCadenceIntValueCadenceNumberValueCadenceArrayValueBaseCadenceArrayValueLengthCadenceDictionaryValueCadenceKeyValuePairCadenceStructValueBaseCadenceStructValueSizeCadenceResourceValueBaseCadenceAttachmentValueBaseCadenceResourceValueSizeCadenceAttachmentValueSizeCadenceEventValueBaseCadenceEventValueSizeCadenceContractValueBaseCadenceContractValueSizeCadenceEnumValueBaseCadenceEnumValueSizeCadencePathValueCadenceTypeValueCadenceCapabilityValueCadenceFunctionValueCadenceOptionalTypeCadenceVariableSizedArrayTypeCadenceConstantSizedArrayTypeCadenceDictionaryTypeCadenceFieldCadenceParameterCadenceTypeParameterCadenceStructTypeCadenceResourceTypeCadenceAttachmentTypeCadenceEventTypeCadenceContractTypeCadenceStructInterfaceTypeCadenceResourceInterfaceTypeCadenceContractInterfaceTypeCadenceFunctionTypeCadenceEntitlementSetAccessCadenceEntitlementMapAccessCadenceReferenceTypeCadenceIntersectionTypeCadenceCapabilityTypeCadenceEnumTypeRawStringAddressLocationBytesVariableCompositeTypeInfoCompositeFieldInvocationStorageMapStorageKeyTypeTokenErrorTokenSpaceTokenProgramIdentifierArgumentBlockFunctionBlockParameterParameterListTypeParameterTypeParameterListTransferMembersTypeAnnotationDictionaryEntryFunctionDeclarationCompositeDeclarationAttachmentDeclarationInterfaceDeclarationEntitlementDeclarationEntitlementMappingElementEntitlementMappingDeclarationEnumCaseDeclarationFieldDeclarationTransactionDeclarationImportDeclarationVariableDeclarationSpecialFunctionDeclarationPragmaDeclarationAssignmentStatementBreakStatementContinueStatementEmitStatementExpressionStatementForStatementIfStatementReturnStatementSwapStatementSwitchStatementWhileStatementRemoveStatementBooleanExpressionVoidExpressionNilExpressionStringExpressionIntegerExpressionFixedPointExpressionArrayExpressionDictionaryExpressionIdentifierExpressionInvocationExpressionMemberExpressionIndexExpressionConditionalExpressionUnaryExpressionBinaryExpressionFunctionExpressionCastingExpressionCreateExpressionDestroyExpressionReferenceExpressionForceExpressionPathExpressionAttachExpressionConstantSizedTypeDictionaryTypeFunctionTypeInstantiationTypeNominalTypeOptionalTypeReferenceTypeIntersectionTypeVariableSizedTypePositionRangeElaborationActivationActivationEntriesVariableSizedSemaTypeConstantSizedSemaTypeDictionarySemaTypeOptionalSemaTypeIntersectionSemaTypeReferenceSemaTypeEntitlementSemaTypeEntitlementMapSemaTypeCapabilitySemaTypeOrderedMapOrderedMapEntryListOrderedMapEntryLast" +const _MemoryKind_name = "UnknownAddressValueStringValueCharacterValueNumberValueArrayValueBaseDictionaryValueBaseCompositeValueBaseSimpleCompositeValueBaseOptionalValueTypeValuePathValueCapabilityValueStorageReferenceValueEphemeralReferenceValueInterpretedFunctionValueHostFunctionValueBoundFunctionValueBigIntSimpleCompositeValuePublishedValueStorageCapabilityControllerValueAccountCapabilityControllerValueAtreeArrayDataSlabAtreeArrayMetaDataSlabAtreeArrayElementOverheadAtreeMapDataSlabAtreeMapMetaDataSlabAtreeMapElementOverheadAtreeMapPreAllocatedElementAtreeEncodedSlabPrimitiveStaticTypeCompositeStaticTypeInterfaceStaticTypeVariableSizedStaticTypeConstantSizedStaticTypeDictionaryStaticTypeOptionalStaticTypeIntersectionStaticTypeEntitlementSetStaticAccessEntitlementMapStaticAccessReferenceStaticTypeCapabilityStaticTypeFunctionStaticTypeCadenceVoidValueCadenceOptionalValueCadenceBoolValueCadenceStringValueCadenceCharacterValueCadenceAddressValueCadenceIntValueCadenceNumberValueCadenceArrayValueBaseCadenceArrayValueLengthCadenceDictionaryValueCadenceKeyValuePairCadenceStructValueBaseCadenceStructValueSizeCadenceResourceValueBaseCadenceAttachmentValueBaseCadenceResourceValueSizeCadenceAttachmentValueSizeCadenceEventValueBaseCadenceEventValueSizeCadenceContractValueBaseCadenceContractValueSizeCadenceEnumValueBaseCadenceEnumValueSizeCadencePathValueCadenceTypeValueCadenceCapabilityValueCadenceFunctionValueCadenceOptionalTypeCadenceVariableSizedArrayTypeCadenceConstantSizedArrayTypeCadenceDictionaryTypeCadenceFieldCadenceParameterCadenceTypeParameterCadenceStructTypeCadenceResourceTypeCadenceAttachmentTypeCadenceEventTypeCadenceContractTypeCadenceStructInterfaceTypeCadenceResourceInterfaceTypeCadenceContractInterfaceTypeCadenceFunctionTypeCadenceEntitlementSetAccessCadenceEntitlementMapAccessCadenceReferenceTypeCadenceIntersectionTypeCadenceCapabilityTypeCadenceEnumTypeRawStringAddressLocationBytesVariableCompositeTypeInfoCompositeFieldInvocationStorageMapStorageKeyTypeTokenErrorTokenSpaceTokenProgramIdentifierArgumentBlockFunctionBlockParameterParameterListTypeParameterTypeParameterListTransferMembersTypeAnnotationDictionaryEntryFunctionDeclarationCompositeDeclarationAttachmentDeclarationInterfaceDeclarationEntitlementDeclarationEntitlementMappingElementEntitlementMappingDeclarationEnumCaseDeclarationFieldDeclarationTransactionDeclarationImportDeclarationVariableDeclarationSpecialFunctionDeclarationPragmaDeclarationAssignmentStatementBreakStatementContinueStatementEmitStatementExpressionStatementForStatementIfStatementReturnStatementSwapStatementSwitchStatementWhileStatementRemoveStatementBooleanExpressionVoidExpressionNilExpressionStringExpressionIntegerExpressionFixedPointExpressionArrayExpressionDictionaryExpressionIdentifierExpressionInvocationExpressionMemberExpressionIndexExpressionConditionalExpressionUnaryExpressionBinaryExpressionFunctionExpressionCastingExpressionCreateExpressionDestroyExpressionReferenceExpressionForceExpressionPathExpressionAttachExpressionConstantSizedTypeDictionaryTypeFunctionTypeInstantiationTypeNominalTypeOptionalTypeReferenceTypeIntersectionTypeVariableSizedTypePositionRangeElaborationActivationActivationEntriesVariableSizedSemaTypeConstantSizedSemaTypeDictionarySemaTypeOptionalSemaTypeIntersectionSemaTypeReferenceSemaTypeEntitlementSemaTypeEntitlementMapSemaTypeCapabilitySemaTypeOrderedMapOrderedMapEntryListOrderedMapEntryLast" -var _MemoryKind_index = [...]uint16{0, 7, 19, 30, 44, 55, 69, 88, 106, 130, 143, 152, 161, 176, 197, 218, 241, 265, 282, 300, 306, 326, 340, 372, 404, 422, 444, 469, 485, 505, 528, 555, 571, 590, 609, 628, 651, 674, 694, 712, 734, 760, 786, 805, 825, 843, 859, 879, 895, 913, 934, 953, 968, 986, 1007, 1030, 1052, 1071, 1093, 1115, 1139, 1165, 1189, 1215, 1236, 1257, 1281, 1305, 1325, 1345, 1361, 1377, 1399, 1419, 1438, 1467, 1496, 1517, 1529, 1545, 1565, 1582, 1601, 1622, 1638, 1657, 1683, 1711, 1739, 1758, 1785, 1812, 1832, 1855, 1876, 1891, 1900, 1915, 1920, 1928, 1945, 1959, 1969, 1979, 1989, 1998, 2008, 2018, 2025, 2035, 2043, 2048, 2061, 2070, 2083, 2096, 2113, 2121, 2128, 2142, 2157, 2176, 2196, 2217, 2237, 2259, 2284, 2313, 2332, 2348, 2370, 2387, 2406, 2432, 2449, 2468, 2482, 2499, 2512, 2531, 2543, 2554, 2569, 2582, 2597, 2611, 2626, 2643, 2657, 2670, 2686, 2703, 2723, 2738, 2758, 2778, 2798, 2814, 2829, 2850, 2865, 2881, 2899, 2916, 2932, 2949, 2968, 2983, 2997, 3013, 3030, 3044, 3056, 3073, 3084, 3096, 3109, 3125, 3142, 3150, 3155, 3166, 3176, 3193, 3214, 3235, 3253, 3269, 3289, 3306, 3325, 3347, 3365, 3375, 3394, 3409, 3413} +var _MemoryKind_index = [...]uint16{0, 7, 19, 30, 44, 55, 69, 88, 106, 130, 143, 152, 161, 176, 197, 220, 244, 261, 279, 285, 305, 319, 351, 383, 401, 423, 448, 464, 484, 507, 534, 550, 569, 588, 607, 630, 653, 673, 691, 713, 739, 765, 784, 804, 822, 838, 858, 874, 892, 913, 932, 947, 965, 986, 1009, 1031, 1050, 1072, 1094, 1118, 1144, 1168, 1194, 1215, 1236, 1260, 1284, 1304, 1324, 1340, 1356, 1378, 1398, 1417, 1446, 1475, 1496, 1508, 1524, 1544, 1561, 1580, 1601, 1617, 1636, 1662, 1690, 1718, 1737, 1764, 1791, 1811, 1834, 1855, 1870, 1879, 1894, 1899, 1907, 1924, 1938, 1948, 1958, 1968, 1977, 1987, 1997, 2004, 2014, 2022, 2027, 2040, 2049, 2062, 2075, 2092, 2100, 2107, 2121, 2136, 2155, 2175, 2196, 2216, 2238, 2263, 2292, 2311, 2327, 2349, 2366, 2385, 2411, 2428, 2447, 2461, 2478, 2491, 2510, 2522, 2533, 2548, 2561, 2576, 2590, 2605, 2622, 2636, 2649, 2665, 2682, 2702, 2717, 2737, 2757, 2777, 2793, 2808, 2829, 2844, 2860, 2878, 2895, 2911, 2928, 2947, 2962, 2976, 2992, 3009, 3023, 3035, 3052, 3063, 3075, 3088, 3104, 3121, 3129, 3134, 3145, 3155, 3172, 3193, 3214, 3232, 3248, 3268, 3285, 3304, 3326, 3344, 3354, 3373, 3388, 3392} func (i MemoryKind) String() string { if i >= MemoryKind(len(_MemoryKind_index)-1) { diff --git a/runtime/common/metering.go b/runtime/common/metering.go index a1abb8aee1..3083320fcd 100644 --- a/runtime/common/metering.go +++ b/runtime/common/metering.go @@ -149,7 +149,6 @@ var ( CapabilityValueMemoryUsage = NewConstantMemoryUsage(MemoryKindCapabilityValue) EphemeralReferenceValueMemoryUsage = NewConstantMemoryUsage(MemoryKindEphemeralReferenceValue) StorageReferenceValueMemoryUsage = NewConstantMemoryUsage(MemoryKindStorageReferenceValue) - AccountReferenceValueMemoryUsage = NewConstantMemoryUsage(MemoryKindAccountReferenceValue) PathValueMemoryUsage = NewConstantMemoryUsage(MemoryKindPathValue) OptionalValueMemoryUsage = NewConstantMemoryUsage(MemoryKindOptionalValue) TypeValueMemoryUsage = NewConstantMemoryUsage(MemoryKindTypeValue) @@ -239,21 +238,17 @@ var ( TypeValueStringMemoryUsage = NewRawStringMemoryUsage(len("Type<>()")) NilValueStringMemoryUsage = NewRawStringMemoryUsage(len("nil")) StorageReferenceValueStringMemoryUsage = NewRawStringMemoryUsage(len("StorageReference()")) - AccountReferenceValueStringMemoryUsage = NewRawStringMemoryUsage(len("AccountReference()")) SeenReferenceStringMemoryUsage = NewRawStringMemoryUsage(3) // len(ellipsis) AddressValueStringMemoryUsage = NewRawStringMemoryUsage(AddressLength*2 + 2) // len(bytes-to-hex + prefix) HostFunctionValueStringMemoryUsage = NewRawStringMemoryUsage(len("Function(...)")) - AuthAccountValueStringMemoryUsage = NewRawStringMemoryUsage(len("AuthAccount()")) - PublicAccountValueStringMemoryUsage = NewRawStringMemoryUsage(len("PublicAccount()")) - AuthAccountContractsStringMemoryUsage = NewRawStringMemoryUsage(len("AuthAccount.Contracts()")) - PublicAccountContractsStringMemoryUsage = NewRawStringMemoryUsage(len("PublicAccount.Contracts()")) - AuthAccountKeysStringMemoryUsage = NewRawStringMemoryUsage(len("AuthAccount.Keys()")) - PublicAccountKeysStringMemoryUsage = NewRawStringMemoryUsage(len("PublicAccount.Keys()")) - AuthAccountStorageCapabilitiesStringMemoryUsage = NewRawStringMemoryUsage(len("AuthAccount.StorageCapabilities()")) - AuthAccountAccountCapabilitiesStringMemoryUsage = NewRawStringMemoryUsage(len("AuthAccount.AccountCapabilities()")) - AuthAccountCapabilitiesStringMemoryUsage = NewRawStringMemoryUsage(len("AuthAccount.Capabilities()")) - PublicAccountCapabilitiesStringMemoryUsage = NewRawStringMemoryUsage(len("PublicAccount.Capabilities()")) - AuthAccountInboxStringMemoryUsage = NewRawStringMemoryUsage(len("AuthAccount.Inbox()")) + AccountValueStringMemoryUsage = NewRawStringMemoryUsage(len("Account()")) + AccountContractsStringMemoryUsage = NewRawStringMemoryUsage(len("Account.Contracts()")) + AccountKeysStringMemoryUsage = NewRawStringMemoryUsage(len("Account.Keys()")) + AccountStorageCapabilitiesStringMemoryUsage = NewRawStringMemoryUsage(len("Account.StorageCapabilities()")) + AccountAccountCapabilitiesStringMemoryUsage = NewRawStringMemoryUsage(len("Account.AccountCapabilities()")) + AccountCapabilitiesStringMemoryUsage = NewRawStringMemoryUsage(len("Account.Capabilities()")) + AccountInboxStringMemoryUsage = NewRawStringMemoryUsage(len("Account.Inbox()")) + AccountStorageStringMemoryUsage = NewRawStringMemoryUsage(len("Account.Storage()")) CapabilityValueStringMemoryUsage = NewRawStringMemoryUsage(len("Capability<>(address: , id: )")) StorageCapabilityControllerValueStringMemoryUsage = NewRawStringMemoryUsage(len("StorageCapabilityController(borrowType: , capabilityID: , target: )")) AccountCapabilityControllerValueStringMemoryUsage = NewRawStringMemoryUsage(len("AccountCapabilityController(borrowType: , capabilityID: )")) @@ -265,8 +260,6 @@ var ( VariableSizedStaticTypeStringMemoryUsage = NewRawStringMemoryUsage(2) // [] DictionaryStaticTypeStringMemoryUsage = NewRawStringMemoryUsage(4) // {: } OptionalStaticTypeStringMemoryUsage = NewRawStringMemoryUsage(1) // ? - AuthReferenceStaticTypeStringMemoryUsage = NewRawStringMemoryUsage(5) // auth& - ReferenceStaticTypeStringMemoryUsage = NewRawStringMemoryUsage(1) // & CapabilityStaticTypeStringMemoryUsage = NewRawStringMemoryUsage(12) // Capability<> ) diff --git a/runtime/contract_function_executor.go b/runtime/contract_function_executor.go index c60d4d30ac..1703d518f6 100644 --- a/runtime/contract_function_executor.go +++ b/runtime/contract_function_executor.go @@ -158,15 +158,17 @@ func (executor *interpreterContractFunctionExecutor) execute() (val cadence.Valu interpreterArguments := make([]interpreter.Value, len(executor.arguments)) + locationRange := interpreter.LocationRange{ + Location: location, + HasPosition: ast.EmptyRange, + } + for i, argumentType := range executor.argumentTypes { interpreterArguments[i], err = executor.convertArgument( inter, executor.arguments[i], argumentType, - interpreter.LocationRange{ - Location: location, - HasPosition: ast.EmptyRange, - }, + locationRange, ) if err != nil { return nil, newError(err, location, codesAndPrograms) @@ -237,19 +239,32 @@ func (executor *interpreterContractFunctionExecutor) convertArgument( ) (interpreter.Value, error) { environment := executor.environment - switch argumentType { - case sema.AuthAccountType: - // convert addresses to auth accounts so there is no need to construct an auth account value for the caller - if addressValue, ok := argument.(cadence.Address); ok { - address := interpreter.NewAddressValue(inter, common.Address(addressValue)) - return environment.NewAuthAccountValue(address), nil - } + // Convert `Address` arguments to account reference values (`&Account`) + // if it is the expected argument type, + // so there is no need for the caller to construct the value + + if addressValue, ok := argument.(cadence.Address); ok { + + if referenceType, ok := argumentType.(*sema.ReferenceType); ok && + referenceType.Type == sema.AccountType { - case sema.PublicAccountType: - // convert addresses to public accounts so there is no need to construct a public account value for the caller - if addressValue, ok := argument.(cadence.Address); ok { address := interpreter.NewAddressValue(inter, common.Address(addressValue)) - return environment.NewPublicAccountValue(address), nil + + accountValue := environment.NewAccountValue(address) + + authorization := interpreter.ConvertSemaAccessToStaticAuthorization( + inter, + referenceType.Authorization, + ) + + accountReferenceValue := interpreter.NewEphemeralReferenceValue( + inter, + authorization, + accountValue, + sema.AccountType, + ) + + return accountReferenceValue, nil } } diff --git a/runtime/contract_test.go b/runtime/contract_test.go index 9280789c04..2bdf7a1d8d 100644 --- a/runtime/contract_test.go +++ b/runtime/contract_test.go @@ -62,7 +62,7 @@ func TestRuntimeContract(t *testing.T) { fmt.Sprintf( ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(AddContract) &Account) { let contract1 = signer.contracts.get(name: %[1]q) log(contract1?.name) log(contract1?.code) @@ -89,13 +89,13 @@ func TestRuntimeContract(t *testing.T) { fmt.Sprintf( ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(UpdateContract) &Account) { let contract1 = signer.contracts.get(name: %[1]q) log(contract1?.name) log(contract1?.code) - let contract2 = signer.contracts.update__experimental(name: %[1]q, code: "%[2]s".decodeHex()) + let contract2 = signer.contracts.update(name: %[1]q, code: "%[2]s".decodeHex()) log(contract2.name) log(contract2.code) @@ -114,7 +114,7 @@ func TestRuntimeContract(t *testing.T) { fmt.Sprintf( ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(RemoveContract) &Account) { let contract1 = signer.contracts.get(name: %[1]q) log(contract1?.name) log(contract1?.code) @@ -136,7 +136,7 @@ func TestRuntimeContract(t *testing.T) { fmt.Sprintf( ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Contracts) &Account) { let contract1 = signer.contracts.get(name: %[1]q) log(contract1?.name) log(contract1?.code) @@ -639,7 +639,7 @@ func TestRuntimeImportMultipleContracts(t *testing.T) { fmt.Sprintf( ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Contracts) &Account) { signer.contracts.add(name: %[1]q, code: "%[2]s".decodeHex()) } } @@ -708,7 +708,7 @@ func TestRuntimeImportMultipleContracts(t *testing.T) { import A from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { log(A.a()) } } @@ -733,7 +733,7 @@ func TestRuntimeImportMultipleContracts(t *testing.T) { import B from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { log(B.b()) } } @@ -758,7 +758,7 @@ func TestRuntimeImportMultipleContracts(t *testing.T) { import C from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { log(C.c()) } } @@ -779,7 +779,7 @@ func TestRuntimeImportMultipleContracts(t *testing.T) { }) } -func TestContractInterfaceEventEmission(t *testing.T) { +func TestRuntimeContractInterfaceEventEmission(t *testing.T) { t.Parallel() storage := newTestLedger(nil, nil) @@ -788,10 +788,10 @@ func TestContractInterfaceEventEmission(t *testing.T) { deployInterfaceTx := DeploymentTransaction("TestInterface", []byte(` access(all) contract interface TestInterface { - access(all) event Foo(x: Int) + access(all) event Foo(x: Int) access(all) fun foo() { - emit Foo(x: 3) + emit Foo(x: 3) } } `)) @@ -799,10 +799,10 @@ func TestContractInterfaceEventEmission(t *testing.T) { deployTx := DeploymentTransaction("TestContract", []byte(` import TestInterface from 0x1 access(all) contract TestContract: TestInterface { - access(all) event Foo(x: String, y: Int) + access(all) event Foo(x: String, y: Int) access(all) fun bar() { - emit Foo(x: "", y: 2) + emit Foo(x: "", y: 2) } } `)) @@ -810,7 +810,7 @@ func TestContractInterfaceEventEmission(t *testing.T) { transaction1 := []byte(` import TestContract from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { TestContract.foo() TestContract.bar() } @@ -892,7 +892,7 @@ func TestContractInterfaceEventEmission(t *testing.T) { require.Equal(t, concreteEvent.Fields[1], cadence.NewInt(2)) } -func TestContractInterfaceConditionEventEmission(t *testing.T) { +func TestRuntimeContractInterfaceConditionEventEmission(t *testing.T) { t.Parallel() storage := newTestLedger(nil, nil) @@ -900,12 +900,15 @@ func TestContractInterfaceConditionEventEmission(t *testing.T) { accountCodes := map[Location][]byte{} deployInterfaceTx := DeploymentTransaction("TestInterface", []byte(` - access(all) contract interface TestInterface { - access(all) event Foo(x: Int) + access(all) + contract interface TestInterface { + + access(all) + event Foo(x: Int) access(all) fun bar() { post { - emit Foo(x: 3) + emit Foo(x: 3) } } } @@ -913,19 +916,25 @@ func TestContractInterfaceConditionEventEmission(t *testing.T) { deployTx := DeploymentTransaction("TestContract", []byte(` import TestInterface from 0x1 - access(all) contract TestContract: TestInterface { - access(all) event Foo(x: String, y: Int) - access(all) fun bar() { - emit Foo(x: "", y: 2) + access(all) + contract TestContract: TestInterface { + + access(all) + event Foo(x: String, y: Int) + + access(all) + fun bar() { + emit Foo(x: "", y: 2) } } `)) transaction1 := []byte(` import TestContract from 0x1 + transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { TestContract.bar() } } diff --git a/runtime/contract_update_test.go b/runtime/contract_update_test.go index 9ac36a3258..d1845ee24a 100644 --- a/runtime/contract_update_test.go +++ b/runtime/contract_update_test.go @@ -30,7 +30,7 @@ import ( "github.com/onflow/cadence/runtime/tests/utils" ) -func TestContractUpdateWithDependencies(t *testing.T) { +func TestRuntimeContractUpdateWithDependencies(t *testing.T) { t.Parallel() runtime := newTestInterpreterRuntime() @@ -212,7 +212,7 @@ func TestContractUpdateWithDependencies(t *testing.T) { require.NoError(t, err) } -func TestContractUpdateWithPrecedingIdentifiers(t *testing.T) { +func TestRuntimeContractUpdateWithPrecedingIdentifiers(t *testing.T) { t.Parallel() runtime := newTestInterpreterRuntime() diff --git a/runtime/contract_update_validation_test.go b/runtime/contract_update_validation_test.go index 70a1fc485a..a514d36169 100644 --- a/runtime/contract_update_validation_test.go +++ b/runtime/contract_update_validation_test.go @@ -38,7 +38,7 @@ func newContractDeployTransaction(function, name, code string) string { return fmt.Sprintf( ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Contracts) &Account) { signer.contracts.%s(name: "%s", code: "%s".decodeHex()) } } @@ -51,7 +51,7 @@ func newContractDeployTransaction(function, name, code string) string { func newContractAddTransaction(name string, code string) string { return newContractDeployTransaction( - sema.AuthAccountContractsTypeAddFunctionName, + sema.Account_ContractsTypeAddFunctionName, name, code, ) @@ -59,7 +59,7 @@ func newContractAddTransaction(name string, code string) string { func newContractUpdateTransaction(name string, code string) string { return newContractDeployTransaction( - sema.AuthAccountContractsTypeUpdate__experimentalFunctionName, + sema.Account_ContractsTypeUpdateFunctionName, name, code, ) @@ -69,12 +69,12 @@ func newContractRemovalTransaction(contractName string) string { return fmt.Sprintf( ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(RemoveContract) &Account) { signer.contracts.%s(name: "%s") } } `, - sema.AuthAccountContractsTypeRemoveFunctionName, + sema.Account_ContractsTypeRemoveFunctionName, contractName, ) } @@ -2468,7 +2468,7 @@ func TestRuntimeContractUpdateProgramCaching(t *testing.T) { import %s from %s transaction { - prepare(signer: AuthAccount) {} + prepare(signer: &Account) {} } `, name, diff --git a/runtime/convertTypes.go b/runtime/convertTypes.go index 2045db7d40..073da0843f 100644 --- a/runtime/convertTypes.go +++ b/runtime/convertTypes.go @@ -49,139 +49,212 @@ func ExportMeteredType( } result := func() cadence.Type { - switch t := t.(type) { - case *sema.OptionalType: - return exportOptionalType(gauge, t, results) - case *sema.VariableSizedType: - return exportVariableSizedType(gauge, t, results) - case *sema.ConstantSizedType: - return exportConstantSizedType(gauge, t, results) - case *sema.CompositeType: - return exportCompositeType(gauge, t, results) - case *sema.InterfaceType: - return exportInterfaceType(gauge, t, results) - case *sema.DictionaryType: - return exportDictionaryType(gauge, t, results) - case *sema.FunctionType: - return exportFunctionType(gauge, t, results) - case *sema.AddressType: - return cadence.TheAddressType - case *sema.ReferenceType: - return exportReferenceType(gauge, t, results) - case *sema.IntersectionType: - return exportIntersectionType(gauge, t, results) - case *sema.CapabilityType: - return exportCapabilityType(gauge, t, results) - } - switch t { case sema.NumberType: - return cadence.TheNumberType + return cadence.NumberType case sema.SignedNumberType: - return cadence.TheSignedNumberType + return cadence.SignedNumberType case sema.IntegerType: - return cadence.TheIntegerType + return cadence.IntegerType case sema.SignedIntegerType: - return cadence.TheSignedIntegerType + return cadence.SignedIntegerType case sema.FixedPointType: - return cadence.TheFixedPointType + return cadence.FixedPointType case sema.SignedFixedPointType: - return cadence.TheSignedFixedPointType + return cadence.SignedFixedPointType case sema.IntType: - return cadence.TheIntType + return cadence.IntType case sema.Int8Type: - return cadence.TheInt8Type + return cadence.Int8Type case sema.Int16Type: - return cadence.TheInt16Type + return cadence.Int16Type case sema.Int32Type: - return cadence.TheInt32Type + return cadence.Int32Type case sema.Int64Type: - return cadence.TheInt64Type + return cadence.Int64Type case sema.Int128Type: - return cadence.TheInt128Type + return cadence.Int128Type case sema.Int256Type: - return cadence.TheInt256Type + return cadence.Int256Type case sema.UIntType: - return cadence.TheUIntType + return cadence.UIntType case sema.UInt8Type: - return cadence.TheUInt8Type + return cadence.UInt8Type case sema.UInt16Type: - return cadence.TheUInt16Type + return cadence.UInt16Type case sema.UInt32Type: - return cadence.TheUInt32Type + return cadence.UInt32Type case sema.UInt64Type: - return cadence.TheUInt64Type + return cadence.UInt64Type case sema.UInt128Type: - return cadence.TheUInt128Type + return cadence.UInt128Type case sema.UInt256Type: - return cadence.TheUInt256Type + return cadence.UInt256Type case sema.Word8Type: - return cadence.TheWord8Type + return cadence.Word8Type case sema.Word16Type: - return cadence.TheWord16Type + return cadence.Word16Type case sema.Word32Type: - return cadence.TheWord32Type + return cadence.Word32Type case sema.Word64Type: - return cadence.TheWord64Type + return cadence.Word64Type case sema.Word128Type: - return cadence.TheWord128Type + return cadence.Word128Type case sema.Word256Type: - return cadence.TheWord256Type + return cadence.Word256Type case sema.Fix64Type: - return cadence.TheFix64Type + return cadence.Fix64Type case sema.UFix64Type: - return cadence.TheUFix64Type + return cadence.UFix64Type case sema.PathType: - return cadence.ThePathType + return cadence.PathType case sema.StoragePathType: - return cadence.TheStoragePathType + return cadence.StoragePathType case sema.PrivatePathType: - return cadence.ThePrivatePathType + return cadence.PrivatePathType case sema.PublicPathType: - return cadence.ThePublicPathType + return cadence.PublicPathType case sema.CapabilityPathType: - return cadence.TheCapabilityPathType + return cadence.CapabilityPathType case sema.NeverType: - return cadence.TheNeverType + return cadence.NeverType case sema.VoidType: - return cadence.TheVoidType + return cadence.VoidType case sema.InvalidType: return nil case sema.MetaType: - return cadence.TheMetaType + return cadence.MetaType case sema.BoolType: - return cadence.TheBoolType + return cadence.BoolType case sema.CharacterType: - return cadence.TheCharacterType + return cadence.CharacterType case sema.AnyType: - return cadence.TheAnyType + return cadence.AnyType case sema.AnyStructType: - return cadence.TheAnyStructType + return cadence.AnyStructType case sema.AnyResourceType: - return cadence.TheAnyResourceType + return cadence.AnyResourceType + case sema.AnyStructAttachmentType: + return cadence.AnyStructAttachmentType + case sema.AnyResourceAttachmentType: + return cadence.AnyResourceAttachmentType case sema.BlockType: - return cadence.TheBlockType + return cadence.BlockType case sema.StringType: - return cadence.TheStringType - case sema.AccountKeyType: - return cadence.TheAccountKeyType - case sema.PublicAccountContractsType: - return cadence.ThePublicAccountContractsType - case sema.AuthAccountContractsType: - return cadence.TheAuthAccountContractsType - case sema.PublicAccountKeysType: - return cadence.ThePublicAccountKeysType - case sema.AuthAccountKeysType: - return cadence.TheAuthAccountKeysType - case sema.PublicAccountType: - return cadence.ThePublicAccountType - case sema.AuthAccountType: - return cadence.TheAuthAccountType + return cadence.StringType + case sema.StorageCapabilityControllerType: + return cadence.StorageCapabilityControllerType + case sema.AccountCapabilityControllerType: + return cadence.AccountCapabilityControllerType + case sema.Account_StorageType: + return cadence.Account_StorageType + case sema.Account_ContractsType: + return cadence.Account_ContractsType + case sema.Account_KeysType: + return cadence.Account_KeysType + case sema.Account_InboxType: + return cadence.Account_InboxType + case sema.Account_CapabilitiesType: + return cadence.Account_CapabilitiesType + case sema.Account_StorageCapabilitiesType: + return cadence.Account_StorageCapabilitiesType + case sema.Account_AccountCapabilitiesType: + return cadence.Account_AccountCapabilitiesType + case sema.AccountType: + return cadence.AccountType case sema.DeployedContractType: - return cadence.TheDeployedContractType + return cadence.DeployedContractType + + case sema.MutateType: + return cadence.MutateType + case sema.InsertType: + return cadence.InsertType + case sema.RemoveType: + return cadence.RemoveType + + case sema.StorageType: + return cadence.StorageType + case sema.SaveValueType: + return cadence.SaveValueType + case sema.LoadValueType: + return cadence.LoadValueType + case sema.BorrowValueType: + return cadence.BorrowValueType + case sema.ContractsType: + return cadence.ContractsType + case sema.AddContractType: + return cadence.AddContractType + case sema.UpdateContractType: + return cadence.UpdateContractType + case sema.RemoveContractType: + return cadence.RemoveContractType + case sema.KeysType: + return cadence.KeysType + case sema.AddKeyType: + return cadence.AddKeyType + case sema.RevokeKeyType: + return cadence.RevokeKeyType + case sema.InboxType: + return cadence.InboxType + case sema.PublishInboxCapabilityType: + return cadence.PublishInboxCapabilityType + case sema.UnpublishInboxCapabilityType: + return cadence.UnpublishInboxCapabilityType + case sema.ClaimInboxCapabilityType: + return cadence.ClaimInboxCapabilityType + case sema.CapabilitiesType: + return cadence.CapabilitiesType + case sema.StorageCapabilitiesType: + return cadence.StorageCapabilitiesType + case sema.AccountCapabilitiesType: + return cadence.AccountCapabilitiesType + case sema.PublishCapabilityType: + return cadence.PublishCapabilityType + case sema.UnpublishCapabilityType: + return cadence.UnpublishCapabilityType + case sema.GetStorageCapabilityControllerType: + return cadence.GetStorageCapabilityControllerType + case sema.IssueStorageCapabilityControllerType: + return cadence.IssueStorageCapabilityControllerType + case sema.GetAccountCapabilityControllerType: + return cadence.GetAccountCapabilityControllerType + case sema.IssueAccountCapabilityControllerType: + return cadence.IssueAccountCapabilityControllerType + + case sema.CapabilitiesMappingType: + return cadence.CapabilitiesMappingType + case sema.AccountMappingType: + return cadence.AccountMappingType + case sema.IdentityType: + return cadence.IdentityType + } + + switch t := t.(type) { + case *sema.OptionalType: + return exportOptionalType(gauge, t, results) + case *sema.VariableSizedType: + return exportVariableSizedType(gauge, t, results) + case *sema.ConstantSizedType: + return exportConstantSizedType(gauge, t, results) + case *sema.CompositeType: + return exportCompositeType(gauge, t, results) + case *sema.InterfaceType: + return exportInterfaceType(gauge, t, results) + case *sema.DictionaryType: + return exportDictionaryType(gauge, t, results) + case *sema.FunctionType: + return exportFunctionType(gauge, t, results) + case *sema.AddressType: + return cadence.AddressType + case *sema.ReferenceType: + return exportReferenceType(gauge, t, results) + case *sema.IntersectionType: + return exportIntersectionType(gauge, t, results) + case *sema.CapabilityType: + return exportCapabilityType(gauge, t, results) } - panic(fmt.Sprintf("cannot export type of type %T", t)) + panic(fmt.Sprintf("cannot export type %s", t)) }() results[typeID] = result @@ -475,7 +548,7 @@ func exportAuthorization( if access.Equal(sema.UnauthorizedAccess) { return cadence.UnauthorizedAccess } - case sema.EntitlementMapAccess: + case *sema.EntitlementMapAccess: common.UseMemory(gauge, common.NewConstantMemoryUsage(common.MemoryKindCadenceEntitlementMapAccess)) return cadence.EntitlementMapAuthorization{ TypeID: access.Type.ID(), @@ -581,114 +654,63 @@ func importAuthorization(memoryGauge common.MemoryGauge, auth cadence.Authorizat func ImportType(memoryGauge common.MemoryGauge, t cadence.Type) interpreter.StaticType { switch t := t.(type) { - case cadence.AnyType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeAny) - case cadence.AnyStructType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeAnyStruct) - case cadence.AnyResourceType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeAnyResource) + case cadence.PrimitiveType: + return interpreter.NewPrimitiveStaticType( + memoryGauge, + interpreter.PrimitiveStaticType(t), + ) + case *cadence.OptionalType: - return interpreter.NewOptionalStaticType(memoryGauge, ImportType(memoryGauge, t.Type)) - case cadence.MetaType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeMetaType) - case cadence.VoidType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeVoid) - case cadence.NeverType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeNever) - case cadence.BoolType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeBool) - case cadence.StringType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeString) - case cadence.CharacterType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeCharacter) - case cadence.AddressType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeAddress) - case cadence.NumberType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeNumber) - case cadence.SignedNumberType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeSignedNumber) - case cadence.IntegerType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeInteger) - case cadence.SignedIntegerType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeSignedInteger) - case cadence.FixedPointType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeFixedPoint) - case cadence.SignedFixedPointType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeSignedFixedPoint) - case cadence.IntType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeInt) - case cadence.Int8Type: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeInt8) - case cadence.Int16Type: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeInt16) - case cadence.Int32Type: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeInt32) - case cadence.Int64Type: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeInt64) - case cadence.Int128Type: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeInt128) - case cadence.Int256Type: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeInt256) - case cadence.UIntType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeUInt) - case cadence.UInt8Type: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeUInt8) - case cadence.UInt16Type: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeUInt16) - case cadence.UInt32Type: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeUInt32) - case cadence.UInt64Type: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeUInt64) - case cadence.UInt128Type: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeUInt128) - case cadence.UInt256Type: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeUInt256) - case cadence.Word8Type: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeWord8) - case cadence.Word16Type: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeWord16) - case cadence.Word32Type: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeWord32) - case cadence.Word64Type: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeWord64) - case cadence.Word128Type: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeWord128) - case cadence.Word256Type: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeWord256) - case cadence.Fix64Type: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeFix64) - case cadence.UFix64Type: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeUFix64) + return interpreter.NewOptionalStaticType( + memoryGauge, + ImportType(memoryGauge, t.Type), + ) + case *cadence.VariableSizedArrayType: - return interpreter.NewVariableSizedStaticType(memoryGauge, ImportType(memoryGauge, t.ElementType)) + return interpreter.NewVariableSizedStaticType( + memoryGauge, + ImportType(memoryGauge, t.ElementType), + ) + case *cadence.ConstantSizedArrayType: return interpreter.NewConstantSizedStaticType( memoryGauge, ImportType(memoryGauge, t.ElementType), int64(t.Size), ) + case *cadence.DictionaryType: return interpreter.NewDictionaryStaticType( memoryGauge, ImportType(memoryGauge, t.KeyType), ImportType(memoryGauge, t.ElementType), ) + case *cadence.StructType, *cadence.ResourceType, *cadence.EventType, *cadence.ContractType, *cadence.EnumType: - return importCompositeType(memoryGauge, t.(cadence.CompositeType)) + return importCompositeType( + memoryGauge, + t.(cadence.CompositeType), + ) + case *cadence.StructInterfaceType, *cadence.ResourceInterfaceType, *cadence.ContractInterfaceType: - return importInterfaceType(memoryGauge, t.(cadence.InterfaceType)) + return importInterfaceType( + memoryGauge, + t.(cadence.InterfaceType), + ) + case *cadence.ReferenceType: return interpreter.NewReferenceStaticType( memoryGauge, importAuthorization(memoryGauge, t.Authorization), ImportType(memoryGauge, t.Type), ) + case *cadence.IntersectionType: types := make([]interpreter.InterfaceStaticType, 0, len(t.Types)) for _, typ := range t.Types { @@ -702,34 +724,17 @@ func ImportType(memoryGauge common.MemoryGauge, t cadence.Type) interpreter.Stat memoryGauge, types, ) - case cadence.BlockType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeBlock) - case cadence.CapabilityPathType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeCapabilityPath) - case cadence.StoragePathType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeStoragePath) - case cadence.PublicPathType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypePublicPath) - case cadence.PrivatePathType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypePrivatePath) + case *cadence.CapabilityType: - return interpreter.NewCapabilityStaticType(memoryGauge, ImportType(memoryGauge, t.BorrowType)) - case cadence.AccountKeyType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeAccountKey) - case cadence.AuthAccountContractsType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeAuthAccountContracts) - case cadence.AuthAccountKeysType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeAuthAccountKeys) - case cadence.AuthAccountType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeAuthAccount) - case cadence.PublicAccountContractsType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypePublicAccountContracts) - case cadence.PublicAccountKeysType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypePublicAccountKeys) - case cadence.PublicAccountType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypePublicAccount) - case cadence.DeployedContractType: - return interpreter.NewPrimitiveStaticType(memoryGauge, interpreter.PrimitiveStaticTypeDeployedContract) + if t.BorrowType == nil { + return interpreter.PrimitiveStaticTypeCapability + } + + return interpreter.NewCapabilityStaticType( + memoryGauge, + ImportType(memoryGauge, t.BorrowType), + ) + default: panic(fmt.Sprintf("cannot import type of type %T", t)) } diff --git a/runtime/convertTypes_test.go b/runtime/convertTypes_test.go index e27b4c65a2..8bfbd98323 100644 --- a/runtime/convertTypes_test.go +++ b/runtime/convertTypes_test.go @@ -30,7 +30,7 @@ import ( "github.com/onflow/cadence/runtime/tests/utils" ) -func TestExportRecursiveType(t *testing.T) { +func TestRuntimeExportRecursiveType(t *testing.T) { t.Parallel() @@ -77,7 +77,7 @@ func BenchmarkExportType(b *testing.B) { ty := sema.StringType exportedType := ExportType(ty, map[sema.TypeID]cadence.Type{}) - assert.Equal(b, cadence.NewStringType(), exportedType) + assert.Equal(b, cadence.StringType, exportedType) b.ResetTimer() b.ReportAllocs() diff --git a/runtime/convertValues.go b/runtime/convertValues.go index c6aeb7faf6..522ff25b13 100644 --- a/runtime/convertValues.go +++ b/runtime/convertValues.go @@ -453,69 +453,62 @@ func exportCompositeValue( structure, err := cadence.NewMeteredStruct( inter, len(fieldNames), - func() ([]cadence.Value, error) { - return makeFields() - }, + makeFields, ) if err != nil { return nil, err } return structure.WithType(t.(*cadence.StructType)), nil + case common.CompositeKindResource: resource, err := cadence.NewMeteredResource( inter, len(fieldNames), - func() ([]cadence.Value, error) { - return makeFields() - }, + makeFields, ) if err != nil { return nil, err } return resource.WithType(t.(*cadence.ResourceType)), nil + case common.CompositeKindAttachment: attachment, err := cadence.NewMeteredAttachment( inter, len(fieldNames), - func() ([]cadence.Value, error) { - return makeFields() - }, + makeFields, ) if err != nil { return nil, err } return attachment.WithType(t.(*cadence.AttachmentType)), nil + case common.CompositeKindEvent: event, err := cadence.NewMeteredEvent( inter, len(fieldNames), - func() ([]cadence.Value, error) { - return makeFields() - }, + makeFields, ) if err != nil { return nil, err } return event.WithType(t.(*cadence.EventType)), nil + case common.CompositeKindContract: contract, err := cadence.NewMeteredContract( inter, len(fieldNames), - func() ([]cadence.Value, error) { - return makeFields() - }, + makeFields, ) if err != nil { return nil, err } return contract.WithType(t.(*cadence.ContractType)), nil + case common.CompositeKindEnum: enum, err := cadence.NewMeteredEnum( inter, len(fieldNames), - func() ([]cadence.Value, error) { - return makeFields() - }, + makeFields, ) if err != nil { return nil, err diff --git a/runtime/convertValues_test.go b/runtime/convertValues_test.go index 218c44ad4f..b2bdbc8512 100644 --- a/runtime/convertValues_test.go +++ b/runtime/convertValues_test.go @@ -38,7 +38,7 @@ import ( . "github.com/onflow/cadence/runtime/tests/utils" ) -func TestExportValue(t *testing.T) { +func TestRuntimeExportValue(t *testing.T) { t.Parallel() @@ -84,11 +84,11 @@ func TestExportValue(t *testing.T) { newSignatureAlgorithmType := func() *cadence.EnumType { return &cadence.EnumType{ QualifiedIdentifier: "SignatureAlgorithm", - RawType: cadence.UInt8Type{}, + RawType: cadence.UInt8Type, Fields: []cadence.Field{ { Identifier: "rawValue", - Type: cadence.UInt8Type{}, + Type: cadence.UInt8Type, }, }, } @@ -101,7 +101,7 @@ func TestExportValue(t *testing.T) { { Identifier: "publicKey", Type: &cadence.VariableSizedArrayType{ - ElementType: cadence.UInt8Type{}, + ElementType: cadence.UInt8Type, }, }, { @@ -115,11 +115,11 @@ func TestExportValue(t *testing.T) { newHashAlgorithmType := func() *cadence.EnumType { return &cadence.EnumType{ QualifiedIdentifier: "HashAlgorithm", - RawType: cadence.UInt8Type{}, + RawType: cadence.UInt8Type, Fields: []cadence.Field{ { Identifier: "rawValue", - Type: cadence.UInt8Type{}, + Type: cadence.UInt8Type, }, }, } @@ -139,7 +139,7 @@ func TestExportValue(t *testing.T) { sema.FunctionPurityImpure, nil, nil, - cadence.VoidType{}, + cadence.VoidType, ) for _, tt := range []exportTest{ @@ -196,7 +196,7 @@ func TestExportValue(t *testing.T) { }, expected: cadence.NewArray([]cadence.Value{}). WithType(&cadence.VariableSizedArrayType{ - ElementType: cadence.AnyStructType{}, + ElementType: cadence.AnyStructType, }), }, { @@ -217,7 +217,7 @@ func TestExportValue(t *testing.T) { cadence.NewInt(42), cadence.String("foo"), }).WithType(&cadence.VariableSizedArrayType{ - ElementType: cadence.AnyStructType{}, + ElementType: cadence.AnyStructType, }), }, { @@ -234,8 +234,8 @@ func TestExportValue(t *testing.T) { }, expected: cadence.NewDictionary([]cadence.KeyValuePair{}). WithType(&cadence.DictionaryType{ - KeyType: cadence.StringType{}, - ElementType: cadence.AnyStructType{}, + KeyType: cadence.StringType, + ElementType: cadence.AnyStructType, }), }, { @@ -265,8 +265,8 @@ func TestExportValue(t *testing.T) { }, }). WithType(&cadence.DictionaryType{ - KeyType: cadence.StringType{}, - ElementType: cadence.AnyStructType{}, + KeyType: cadence.StringType, + ElementType: cadence.AnyStructType, }), }, { @@ -460,7 +460,7 @@ func TestExportValue(t *testing.T) { Fields: []cadence.Field{ { Identifier: "keyIndex", - Type: cadence.IntType{}, + Type: cadence.IntType, }, { Identifier: "publicKey", @@ -472,11 +472,11 @@ func TestExportValue(t *testing.T) { }, { Identifier: "weight", - Type: cadence.UFix64Type{}, + Type: cadence.UFix64Type, }, { Identifier: "isRevoked", - Type: cadence.BoolType{}, + Type: cadence.BoolType, }, }, }, @@ -490,7 +490,7 @@ func TestExportValue(t *testing.T) { cadence.NewUInt8(2), cadence.NewUInt8(3), }).WithType(&cadence.VariableSizedArrayType{ - ElementType: cadence.UInt8Type{}, + ElementType: cadence.UInt8Type, }), cadence.Enum{ EnumType: signatureAlgorithmType, @@ -556,7 +556,7 @@ func TestExportValue(t *testing.T) { } -func TestImportValue(t *testing.T) { +func TestRuntimeImportValue(t *testing.T) { t.Parallel() @@ -849,7 +849,7 @@ func TestImportValue(t *testing.T) { value: cadence.NewCapability( 4, cadence.Address{0x1}, - cadence.IntType{}, + cadence.IntType, ), expected: nil, }, @@ -860,7 +860,7 @@ func TestImportValue(t *testing.T) { }, { label: "Type()", - value: cadence.NewTypeValue(cadence.IntType{}), + value: cadence.NewTypeValue(cadence.IntType), expected: interpreter.TypeValue{Type: interpreter.PrimitiveStaticTypeInt}, }, } { @@ -876,7 +876,7 @@ func assertUserError(t *testing.T, err error) { ) } -func TestImportRuntimeType(t *testing.T) { +func TestRuntimeImportRuntimeType(t *testing.T) { t.Parallel() type importTest struct { @@ -897,263 +897,296 @@ func TestImportRuntimeType(t *testing.T) { for _, tt := range []importTest{ { label: "Any", - actual: cadence.AnyType{}, + actual: cadence.AnyType, expected: interpreter.PrimitiveStaticTypeAny, }, { label: "AnyStruct", - actual: cadence.AnyStructType{}, + actual: cadence.AnyStructType, expected: interpreter.PrimitiveStaticTypeAnyStruct, }, { label: "AnyResource", - actual: cadence.AnyResourceType{}, + actual: cadence.AnyResourceType, expected: interpreter.PrimitiveStaticTypeAnyResource, }, { label: "MetaType", - actual: cadence.MetaType{}, + actual: cadence.MetaType, expected: interpreter.PrimitiveStaticTypeMetaType, }, { label: "Void", - actual: cadence.VoidType{}, + actual: cadence.VoidType, expected: interpreter.PrimitiveStaticTypeVoid, }, { label: "Never", - actual: cadence.NeverType{}, + actual: cadence.NeverType, expected: interpreter.PrimitiveStaticTypeNever, }, { label: "Bool", - actual: cadence.BoolType{}, + actual: cadence.BoolType, expected: interpreter.PrimitiveStaticTypeBool, }, { label: "String", - actual: cadence.StringType{}, + actual: cadence.StringType, expected: interpreter.PrimitiveStaticTypeString, }, { label: "Character", - actual: cadence.CharacterType{}, + actual: cadence.CharacterType, expected: interpreter.PrimitiveStaticTypeCharacter, }, { label: "Address", - actual: cadence.AddressType{}, + actual: cadence.AddressType, expected: interpreter.PrimitiveStaticTypeAddress, }, { label: "Number", - actual: cadence.NumberType{}, + actual: cadence.NumberType, expected: interpreter.PrimitiveStaticTypeNumber, }, { label: "SignedNumber", - actual: cadence.SignedNumberType{}, + actual: cadence.SignedNumberType, expected: interpreter.PrimitiveStaticTypeSignedNumber, }, { label: "Integer", - actual: cadence.IntegerType{}, + actual: cadence.IntegerType, expected: interpreter.PrimitiveStaticTypeInteger, }, { label: "SignedInteger", - actual: cadence.SignedIntegerType{}, + actual: cadence.SignedIntegerType, expected: interpreter.PrimitiveStaticTypeSignedInteger, }, { label: "FixedPoint", - actual: cadence.FixedPointType{}, + actual: cadence.FixedPointType, expected: interpreter.PrimitiveStaticTypeFixedPoint, }, { label: "SignedFixedPoint", - actual: cadence.SignedFixedPointType{}, + actual: cadence.SignedFixedPointType, expected: interpreter.PrimitiveStaticTypeSignedFixedPoint, }, { label: "Int", - actual: cadence.IntType{}, + actual: cadence.IntType, expected: interpreter.PrimitiveStaticTypeInt, }, { label: "Int8", - actual: cadence.Int8Type{}, + actual: cadence.Int8Type, expected: interpreter.PrimitiveStaticTypeInt8, }, { label: "Int16", - actual: cadence.Int16Type{}, + actual: cadence.Int16Type, expected: interpreter.PrimitiveStaticTypeInt16, }, { label: "Int32", - actual: cadence.Int32Type{}, + actual: cadence.Int32Type, expected: interpreter.PrimitiveStaticTypeInt32, }, { label: "Int64", - actual: cadence.Int64Type{}, + actual: cadence.Int64Type, expected: interpreter.PrimitiveStaticTypeInt64, }, { label: "Int128", - actual: cadence.Int128Type{}, + actual: cadence.Int128Type, expected: interpreter.PrimitiveStaticTypeInt128, }, { label: "Int256", - actual: cadence.Int256Type{}, + actual: cadence.Int256Type, expected: interpreter.PrimitiveStaticTypeInt256, }, { label: "UInt", - actual: cadence.UIntType{}, + actual: cadence.UIntType, expected: interpreter.PrimitiveStaticTypeUInt, }, { label: "UInt8", - actual: cadence.UInt8Type{}, + actual: cadence.UInt8Type, expected: interpreter.PrimitiveStaticTypeUInt8, }, { label: "UInt16", - actual: cadence.UInt16Type{}, + actual: cadence.UInt16Type, expected: interpreter.PrimitiveStaticTypeUInt16, }, { label: "UInt32", - actual: cadence.UInt32Type{}, + actual: cadence.UInt32Type, expected: interpreter.PrimitiveStaticTypeUInt32, }, { label: "UInt64", - actual: cadence.UInt64Type{}, + actual: cadence.UInt64Type, expected: interpreter.PrimitiveStaticTypeUInt64, }, { label: "UInt128", - actual: cadence.UInt128Type{}, + actual: cadence.UInt128Type, expected: interpreter.PrimitiveStaticTypeUInt128, }, { label: "UInt256", - actual: cadence.UInt256Type{}, + actual: cadence.UInt256Type, expected: interpreter.PrimitiveStaticTypeUInt256, }, { label: "Word8", - actual: cadence.Word8Type{}, + actual: cadence.Word8Type, expected: interpreter.PrimitiveStaticTypeWord8, }, { label: "Word16", - actual: cadence.Word16Type{}, + actual: cadence.Word16Type, expected: interpreter.PrimitiveStaticTypeWord16, }, { label: "Word32", - actual: cadence.Word32Type{}, + actual: cadence.Word32Type, expected: interpreter.PrimitiveStaticTypeWord32, }, { label: "Word64", - actual: cadence.Word64Type{}, + actual: cadence.Word64Type, expected: interpreter.PrimitiveStaticTypeWord64, }, { label: "Word128", - actual: cadence.Word128Type{}, + actual: cadence.Word128Type, expected: interpreter.PrimitiveStaticTypeWord128, }, { label: "Word256", - actual: cadence.Word256Type{}, + actual: cadence.Word256Type, expected: interpreter.PrimitiveStaticTypeWord256, }, { label: "Fix64", - actual: cadence.Fix64Type{}, + actual: cadence.Fix64Type, expected: interpreter.PrimitiveStaticTypeFix64, }, { label: "UFix64", - actual: cadence.UFix64Type{}, + actual: cadence.UFix64Type, expected: interpreter.PrimitiveStaticTypeUFix64, }, { label: "Block", - actual: cadence.BlockType{}, + actual: cadence.BlockType, expected: interpreter.PrimitiveStaticTypeBlock, }, { label: "CapabilityPath", - actual: cadence.CapabilityPathType{}, + actual: cadence.CapabilityPathType, expected: interpreter.PrimitiveStaticTypeCapabilityPath, }, { label: "StoragePath", - actual: cadence.StoragePathType{}, + actual: cadence.StoragePathType, expected: interpreter.PrimitiveStaticTypeStoragePath, }, { label: "PublicPath", - actual: cadence.PublicPathType{}, + actual: cadence.PublicPathType, expected: interpreter.PrimitiveStaticTypePublicPath, }, { label: "PrivatePath", - actual: cadence.PrivatePathType{}, + actual: cadence.PrivatePathType, expected: interpreter.PrimitiveStaticTypePrivatePath, }, { - label: "AuthAccount", - actual: cadence.AuthAccountType{}, - expected: interpreter.PrimitiveStaticTypeAuthAccount, - }, - { - label: "PublicAccount", - actual: cadence.PublicAccountType{}, - expected: interpreter.PrimitiveStaticTypePublicAccount, + label: "Account", + actual: cadence.AccountType, + expected: interpreter.PrimitiveStaticTypeAccount, }, { label: "DeployedContract", - actual: cadence.DeployedContractType{}, + actual: cadence.DeployedContractType, expected: interpreter.PrimitiveStaticTypeDeployedContract, }, { - label: "AuthAccount.Keys", - actual: cadence.AuthAccountKeysType{}, - expected: interpreter.PrimitiveStaticTypeAuthAccountKeys, + label: "Account.Storage", + actual: cadence.Account_StorageType, + expected: interpreter.PrimitiveStaticTypeAccount_Storage, + }, + { + label: "Account.Keys", + actual: cadence.Account_KeysType, + expected: interpreter.PrimitiveStaticTypeAccount_Keys, + }, + { + label: "Account.Contracts", + actual: cadence.Account_ContractsType, + expected: interpreter.PrimitiveStaticTypeAccount_Contracts, + }, + { + label: "Account.Inbox", + actual: cadence.Account_InboxType, + expected: interpreter.PrimitiveStaticTypeAccount_Inbox, }, { - label: "PublicAccount.Keys", - actual: cadence.PublicAccountKeysType{}, - expected: interpreter.PrimitiveStaticTypePublicAccountKeys, + label: "Account.Capabilities", + actual: cadence.Account_CapabilitiesType, + expected: interpreter.PrimitiveStaticTypeAccount_Capabilities, + }, + { + label: "Account.StorageCapabilities", + actual: cadence.Account_StorageCapabilitiesType, + expected: interpreter.PrimitiveStaticTypeAccount_StorageCapabilities, + }, + { + label: "Account.AccountCapabilities", + actual: cadence.Account_AccountCapabilitiesType, + expected: interpreter.PrimitiveStaticTypeAccount_AccountCapabilities, + }, + { + label: "AccountKey", + actual: &cadence.StructType{ + QualifiedIdentifier: "AccountKey", + }, + expected: interpreter.NewCompositeStaticTypeComputeTypeID(nil, nil, "AccountKey"), }, { - label: "AuthAccount.Contracts", - actual: cadence.AuthAccountContractsType{}, - expected: interpreter.PrimitiveStaticTypeAuthAccountContracts, + label: "PublicKey", + actual: &cadence.StructType{ + QualifiedIdentifier: "PublicKey", + }, + expected: interpreter.NewCompositeStaticTypeComputeTypeID(nil, nil, "PublicKey"), }, { - label: "PublicAccount.Contracts", - actual: cadence.PublicAccountContractsType{}, - expected: interpreter.PrimitiveStaticTypePublicAccountContracts, + label: "HashAlgorithm", + actual: &cadence.StructType{ + QualifiedIdentifier: "HashAlgorithm", + }, + expected: interpreter.NewCompositeStaticTypeComputeTypeID(nil, nil, "HashAlgorithm"), }, { - label: "AccountKey", - actual: cadence.AccountKeyType{}, - expected: interpreter.PrimitiveStaticTypeAccountKey, + label: "SignatureAlgorithm", + actual: &cadence.StructType{ + QualifiedIdentifier: "SignatureAlgorithm", + }, + expected: interpreter.NewCompositeStaticTypeComputeTypeID(nil, nil, "SignatureAlgorithm"), }, { label: "Optional", actual: &cadence.OptionalType{ - Type: cadence.IntType{}, + Type: cadence.IntType, }, expected: interpreter.OptionalStaticType{ Type: interpreter.PrimitiveStaticTypeInt, @@ -1162,7 +1195,7 @@ func TestImportRuntimeType(t *testing.T) { { label: "VariableSizedArray", actual: &cadence.VariableSizedArrayType{ - ElementType: cadence.IntType{}, + ElementType: cadence.IntType, }, expected: interpreter.VariableSizedStaticType{ Type: interpreter.PrimitiveStaticTypeInt, @@ -1171,7 +1204,7 @@ func TestImportRuntimeType(t *testing.T) { { label: "ConstantSizedArray", actual: &cadence.ConstantSizedArrayType{ - ElementType: cadence.IntType{}, + ElementType: cadence.IntType, Size: 3, }, expected: interpreter.ConstantSizedStaticType{ @@ -1182,8 +1215,8 @@ func TestImportRuntimeType(t *testing.T) { { label: "Dictionary", actual: &cadence.DictionaryType{ - ElementType: cadence.IntType{}, - KeyType: cadence.StringType{}, + ElementType: cadence.IntType, + KeyType: cadence.StringType, }, expected: interpreter.DictionaryStaticType{ KeyType: interpreter.PrimitiveStaticTypeString, @@ -1194,7 +1227,7 @@ func TestImportRuntimeType(t *testing.T) { label: "Unauthorized Reference", actual: &cadence.ReferenceType{ Authorization: cadence.UnauthorizedAccess, - Type: cadence.IntType{}, + Type: cadence.IntType, }, expected: interpreter.ReferenceStaticType{ Authorization: interpreter.UnauthorizedAccess, @@ -1208,7 +1241,7 @@ func TestImportRuntimeType(t *testing.T) { Kind: cadence.Conjunction, Entitlements: []common.TypeID{"E", "F"}, }, - Type: cadence.IntType{}, + Type: cadence.IntType, }, expected: interpreter.ReferenceStaticType{ Authorization: interpreter.NewEntitlementSetAuthorization( @@ -1228,7 +1261,7 @@ func TestImportRuntimeType(t *testing.T) { Kind: cadence.Disjunction, Entitlements: []common.TypeID{"E", "F"}, }, - Type: cadence.IntType{}, + Type: cadence.IntType, }, expected: interpreter.ReferenceStaticType{ Authorization: interpreter.NewEntitlementSetAuthorization( @@ -1245,7 +1278,7 @@ func TestImportRuntimeType(t *testing.T) { Authorization: cadence.EntitlementMapAuthorization{ TypeID: "M", }, - Type: cadence.IntType{}, + Type: cadence.IntType, }, expected: interpreter.ReferenceStaticType{ Authorization: interpreter.EntitlementMapAuthorization{ @@ -1257,7 +1290,7 @@ func TestImportRuntimeType(t *testing.T) { { label: "Capability", actual: &cadence.CapabilityType{ - BorrowType: cadence.IntType{}, + BorrowType: cadence.IntType, }, expected: interpreter.CapabilityStaticType{ BorrowType: interpreter.PrimitiveStaticTypeInt, @@ -1348,7 +1381,7 @@ func TestImportRuntimeType(t *testing.T) { } } -func TestExportIntegerValuesFromScript(t *testing.T) { +func TestRuntimeExportIntegerValuesFromScript(t *testing.T) { t.Parallel() @@ -1378,7 +1411,7 @@ func TestExportIntegerValuesFromScript(t *testing.T) { } } -func TestExportFixedPointValuesFromScript(t *testing.T) { +func TestRuntimeExportFixedPointValuesFromScript(t *testing.T) { t.Parallel() @@ -1417,7 +1450,7 @@ func TestExportFixedPointValuesFromScript(t *testing.T) { } } -func TestExportAddressValue(t *testing.T) { +func TestRuntimeExportAddressValue(t *testing.T) { t.Parallel() @@ -1435,7 +1468,7 @@ func TestExportAddressValue(t *testing.T) { assert.Equal(t, expected, actual) } -func TestExportStructValue(t *testing.T) { +func TestRuntimeExportStructValue(t *testing.T) { t.Parallel() @@ -1469,7 +1502,7 @@ func TestExportStructValue(t *testing.T) { assert.Equal(t, expected, actual) } -func TestExportResourceValue(t *testing.T) { +func TestRuntimeExportResourceValue(t *testing.T) { t.Parallel() @@ -1498,7 +1531,7 @@ func TestExportResourceValue(t *testing.T) { assert.Equal(t, expected, actual) } -func TestExportResourceArrayValue(t *testing.T) { +func TestRuntimeExportResourceArrayValue(t *testing.T) { t.Parallel() @@ -1539,11 +1572,11 @@ func TestExportResourceArrayValue(t *testing.T) { Fields: []cadence.Field{ { Identifier: "uuid", - Type: cadence.UInt64Type{}, + Type: cadence.UInt64Type, }, { Identifier: "bar", - Type: cadence.IntType{}, + Type: cadence.IntType, }, }, }, @@ -1553,7 +1586,7 @@ func TestExportResourceArrayValue(t *testing.T) { assert.Equal(t, expected, actual) } -func TestExportResourceDictionaryValue(t *testing.T) { +func TestRuntimeExportResourceDictionaryValue(t *testing.T) { t.Parallel() @@ -1597,18 +1630,18 @@ func TestExportResourceDictionaryValue(t *testing.T) { }).WithType(fooResourceType), }, }).WithType(&cadence.DictionaryType{ - KeyType: cadence.StringType{}, + KeyType: cadence.StringType, ElementType: &cadence.ResourceType{ Location: common.ScriptLocation{}, QualifiedIdentifier: "Foo", Fields: []cadence.Field{ { Identifier: "uuid", - Type: cadence.UInt64Type{}, + Type: cadence.UInt64Type, }, { Identifier: "bar", - Type: cadence.IntType{}, + Type: cadence.IntType, }, }, }, @@ -1618,7 +1651,7 @@ func TestExportResourceDictionaryValue(t *testing.T) { assert.Equal(t, expected, actual) } -func TestExportNestedResourceValueFromScript(t *testing.T) { +func TestRuntimeExportNestedResourceValueFromScript(t *testing.T) { t.Parallel() @@ -1628,11 +1661,11 @@ func TestExportNestedResourceValueFromScript(t *testing.T) { Fields: []cadence.Field{ { Identifier: "uuid", - Type: cadence.UInt64Type{}, + Type: cadence.UInt64Type, }, { Identifier: "x", - Type: cadence.IntType{}, + Type: cadence.IntType, }, }, } @@ -1643,7 +1676,7 @@ func TestExportNestedResourceValueFromScript(t *testing.T) { Fields: []cadence.Field{ { Identifier: "uuid", - Type: cadence.UInt64Type{}, + Type: cadence.UInt64Type, }, { Identifier: "bar", @@ -1694,29 +1727,71 @@ func TestExportNestedResourceValueFromScript(t *testing.T) { assert.Equal(t, expected, actual) } -func TestExportEventValue(t *testing.T) { +func TestRuntimeExportEventValue(t *testing.T) { t.Parallel() - script := ` - access(all) event Foo(bar: Int) + t.Run("primitive", func(t *testing.T) { + t.Parallel() - access(all) fun main() { - emit Foo(bar: 42) - } - ` + script := ` + access(all) + event Foo(bar: Int) - fooEventType := &cadence.EventType{ - Location: common.ScriptLocation{}, - QualifiedIdentifier: "Foo", - Fields: fooFields, - } + access(all) + fun main() { + emit Foo(bar: 42) + } + ` + + fooEventType := &cadence.EventType{ + Location: common.ScriptLocation{}, + QualifiedIdentifier: "Foo", + Fields: fooFields, + } - actual := exportEventFromScript(t, script) - expected := cadence.NewEvent([]cadence.Value{cadence.NewInt(42)}). - WithType(fooEventType) + actual := exportEventFromScript(t, script) + expected := cadence.NewEvent([]cadence.Value{ + cadence.NewInt(42), + }).WithType(fooEventType) - assert.Equal(t, expected, actual) + assert.Equal(t, expected, actual) + }) + + t.Run("reference", func(t *testing.T) { + t.Parallel() + + script := ` + access(all) + event Foo(bar: &Int) + + access(all) + fun main() { + emit Foo(bar: &42) + } + ` + + fooEventType := &cadence.EventType{ + Location: common.ScriptLocation{}, + QualifiedIdentifier: "Foo", + Fields: []cadence.Field{ + { + Identifier: "bar", + Type: cadence.NewReferenceType( + cadence.UnauthorizedAccess, + cadence.IntType, + ), + }, + }, + } + + actual := exportEventFromScript(t, script) + expected := cadence.NewEvent([]cadence.Value{ + cadence.NewInt(42), + }).WithType(fooEventType) + + assert.Equal(t, expected, actual) + }) } func exportEventFromScript(t *testing.T, script string) cadence.Event { @@ -1767,7 +1842,7 @@ func exportValueFromScript(t *testing.T, script string) cadence.Value { return value } -func TestExportReferenceValue(t *testing.T) { +func TestRuntimeExportReferenceValue(t *testing.T) { t.Parallel() @@ -1805,13 +1880,13 @@ func TestExportReferenceValue(t *testing.T) { nil, }).WithType(&cadence.VariableSizedArrayType{ ElementType: &cadence.ReferenceType{ - Type: cadence.AnyStructType{}, + Type: cadence.AnyStructType, Authorization: cadence.UnauthorizedAccess, }, }), }).WithType(&cadence.VariableSizedArrayType{ ElementType: &cadence.ReferenceType{ - Type: cadence.AnyStructType{}, + Type: cadence.AnyStructType, Authorization: cadence.UnauthorizedAccess, }, }) @@ -1829,8 +1904,8 @@ func TestExportReferenceValue(t *testing.T) { transaction := ` transaction { - prepare(signer: AuthAccount) { - signer.save(1, to: /storage/test) + prepare(signer: auth(Storage, Capabilities) &Account) { + signer.storage.save(1, to: /storage/test) let cap = signer.capabilities.storage.issue<&Int>(/storage/test) signer.capabilities.publish(cap, at: /public/test) @@ -1891,11 +1966,11 @@ func TestExportReferenceValue(t *testing.T) { script := ` access(all) fun main(): &AnyStruct { - var acct = getAuthAccount(0x01) + var acct = getAuthAccount(0x01) var v:[AnyStruct] = [] - acct.save(v, to: /storage/x) + acct.storage.save(v, to: /storage/x) - var ref = acct.borrow(from: /storage/x)! + var ref = acct.storage.borrow(from: /storage/x)! ref.append(ref) return ref } @@ -1926,12 +2001,12 @@ func TestExportReferenceValue(t *testing.T) { script := ` access(all) fun main(): &AnyStruct { - var acct = getAuthAccount(0x01) - var v:[AnyStruct] = [] - acct.save(v, to: /storage/x) + let acct = getAuthAccount(0x01) + let v: [AnyStruct] = [] + acct.storage.save(v, to: /storage/x) - var ref1 = acct.borrow(from: /storage/x)! - var ref2 = acct.borrow<&[AnyStruct]>(from: /storage/x)! + let ref1 = acct.storage.borrow(from: /storage/x)! + let ref2 = acct.storage.borrow<&[AnyStruct]>(from: /storage/x)! ref1.append(ref2) return ref1 @@ -1958,7 +2033,7 @@ func TestExportReferenceValue(t *testing.T) { }) } -func TestExportTypeValue(t *testing.T) { +func TestRuntimeExportTypeValue(t *testing.T) { t.Parallel() @@ -1974,7 +2049,7 @@ func TestExportTypeValue(t *testing.T) { actual := exportValueFromScript(t, script) expected := cadence.TypeValue{ - StaticType: cadence.IntType{}, + StaticType: cadence.IntType, } assert.Equal(t, expected, actual) @@ -2100,7 +2175,7 @@ func TestExportTypeValue(t *testing.T) { } -func TestExportCapabilityValue(t *testing.T) { +func TestRuntimeExportCapabilityValue(t *testing.T) { t.Parallel() @@ -2123,7 +2198,7 @@ func TestExportCapabilityValue(t *testing.T) { expected := cadence.NewCapability( 3, cadence.Address{0x1}, - cadence.IntType{}, + cadence.IntType, ) assert.Equal(t, expected, actual) @@ -2182,7 +2257,7 @@ func TestExportCapabilityValue(t *testing.T) { }) } -func TestExportCompositeValueWithFunctionValueField(t *testing.T) { +func TestRuntimeExportCompositeValueWithFunctionValueField(t *testing.T) { t.Parallel() @@ -2208,12 +2283,12 @@ func TestExportCompositeValueWithFunctionValueField(t *testing.T) { Fields: []cadence.Field{ { Identifier: "answer", - Type: cadence.IntType{}, + Type: cadence.IntType, }, { Identifier: "f", Type: &cadence.FunctionType{ - ReturnType: cadence.VoidType{}, + ReturnType: cadence.VoidType, }, }, }, @@ -2228,7 +2303,7 @@ func TestExportCompositeValueWithFunctionValueField(t *testing.T) { cadence.NewInt(42), cadence.Function{ FunctionType: &cadence.FunctionType{ - ReturnType: cadence.VoidType{}, + ReturnType: cadence.VoidType, }, }, }).WithType(fooStructType), @@ -2240,7 +2315,7 @@ func TestExportCompositeValueWithFunctionValueField(t *testing.T) { //go:embed test-export-json-deterministic.txt var exportJsonDeterministicExpected string -func TestExportJsonDeterministic(t *testing.T) { +func TestRuntimeExportJsonDeterministic(t *testing.T) { t.Parallel() // exported order of field in a dictionary depends on the execution , @@ -2293,17 +2368,17 @@ func TestExportJsonDeterministic(t *testing.T) { var fooFields = []cadence.Field{ { Identifier: "bar", - Type: cadence.IntType{}, + Type: cadence.IntType, }, } var fooResourceFields = []cadence.Field{ { Identifier: "uuid", - Type: cadence.UInt64Type{}, + Type: cadence.UInt64Type, }, { Identifier: "bar", - Type: cadence.IntType{}, + Type: cadence.IntType, }, } @@ -2327,10 +2402,10 @@ func TestRuntimeEnumValue(t *testing.T) { Fields: []cadence.Field{ { Identifier: sema.EnumRawValueFieldName, - Type: cadence.IntType{}, + Type: cadence.IntType, }, }, - RawType: cadence.IntType{}, + RawType: cadence.IntType, }, Fields: []cadence.Value{ cadence.NewInt(3), @@ -2471,7 +2546,7 @@ func TestRuntimeArgumentPassing(t *testing.T) { typeSignature: "[String]", exportedValue: cadence.NewArray([]cadence.Value{}). WithType(&cadence.VariableSizedArrayType{ - ElementType: cadence.StringType{}, + ElementType: cadence.StringType, }), }, { @@ -2481,7 +2556,7 @@ func TestRuntimeArgumentPassing(t *testing.T) { cadence.String("foo"), cadence.String("bar"), }).WithType(&cadence.VariableSizedArrayType{ - ElementType: cadence.StringType{}, + ElementType: cadence.StringType, }), }, { @@ -2493,8 +2568,8 @@ func TestRuntimeArgumentPassing(t *testing.T) { Value: cadence.String("bar"), }, }).WithType(&cadence.DictionaryType{ - KeyType: cadence.StringType{}, - ElementType: cadence.StringType{}, + KeyType: cadence.StringType, + ElementType: cadence.StringType, }), }, { @@ -2697,52 +2772,52 @@ func TestRuntimeComplexStructArgumentPassing(t *testing.T) { { Identifier: "a", Type: &cadence.OptionalType{ - Type: cadence.StringType{}, + Type: cadence.StringType, }, }, { Identifier: "b", Type: &cadence.DictionaryType{ - KeyType: cadence.StringType{}, - ElementType: cadence.StringType{}, + KeyType: cadence.StringType, + ElementType: cadence.StringType, }, }, { Identifier: "c", Type: &cadence.VariableSizedArrayType{ - ElementType: cadence.StringType{}, + ElementType: cadence.StringType, }, }, { Identifier: "d", Type: &cadence.ConstantSizedArrayType{ - ElementType: cadence.StringType{}, + ElementType: cadence.StringType, Size: 2, }, }, { Identifier: "e", - Type: cadence.AddressType{}, + Type: cadence.AddressType, }, { Identifier: "f", - Type: cadence.BoolType{}, + Type: cadence.BoolType, }, { Identifier: "g", - Type: cadence.StoragePathType{}, + Type: cadence.StoragePathType, }, { Identifier: "h", - Type: cadence.PublicPathType{}, + Type: cadence.PublicPathType, }, { Identifier: "i", - Type: cadence.PrivatePathType{}, + Type: cadence.PrivatePathType, }, { Identifier: "j", - Type: cadence.AnyStructType{}, + Type: cadence.AnyStructType, }, }, }, @@ -2757,20 +2832,20 @@ func TestRuntimeComplexStructArgumentPassing(t *testing.T) { Value: cadence.String("Doe"), }, }).WithType(&cadence.DictionaryType{ - KeyType: cadence.StringType{}, - ElementType: cadence.StringType{}, + KeyType: cadence.StringType, + ElementType: cadence.StringType, }), cadence.NewArray([]cadence.Value{ cadence.String("foo"), cadence.String("bar"), }).WithType(&cadence.VariableSizedArrayType{ - ElementType: cadence.StringType{}, + ElementType: cadence.StringType, }), cadence.NewArray([]cadence.Value{ cadence.String("foo"), cadence.String("bar"), }).WithType(&cadence.ConstantSizedArrayType{ - ElementType: cadence.StringType{}, + ElementType: cadence.StringType, Size: 2, }), cadence.NewAddress([8]byte{0, 0, 0, 0, 0, 1, 0, 2}), @@ -2852,32 +2927,32 @@ func TestRuntimeComplexStructWithAnyStructFields(t *testing.T) { { Identifier: "a", Type: &cadence.OptionalType{ - Type: cadence.AnyStructType{}, + Type: cadence.AnyStructType, }, }, { Identifier: "b", Type: &cadence.DictionaryType{ - KeyType: cadence.StringType{}, - ElementType: cadence.AnyStructType{}, + KeyType: cadence.StringType, + ElementType: cadence.AnyStructType, }, }, { Identifier: "c", Type: &cadence.VariableSizedArrayType{ - ElementType: cadence.AnyStructType{}, + ElementType: cadence.AnyStructType, }, }, { Identifier: "d", Type: &cadence.ConstantSizedArrayType{ - ElementType: cadence.AnyStructType{}, + ElementType: cadence.AnyStructType, Size: 2, }, }, { Identifier: "e", - Type: cadence.AnyStructType{}, + Type: cadence.AnyStructType, }, }, }, @@ -2890,20 +2965,20 @@ func TestRuntimeComplexStructWithAnyStructFields(t *testing.T) { Value: cadence.String("Doe"), }, }).WithType(&cadence.DictionaryType{ - KeyType: cadence.StringType{}, - ElementType: cadence.AnyStructType{}, + KeyType: cadence.StringType, + ElementType: cadence.AnyStructType, }), cadence.NewArray([]cadence.Value{ cadence.String("foo"), cadence.String("bar"), }).WithType(&cadence.VariableSizedArrayType{ - ElementType: cadence.AnyStructType{}, + ElementType: cadence.AnyStructType, }), cadence.NewArray([]cadence.Value{ cadence.String("foo"), cadence.String("bar"), }).WithType(&cadence.ConstantSizedArrayType{ - ElementType: cadence.AnyStructType{}, + ElementType: cadence.AnyStructType, Size: 2, }), cadence.Path{ @@ -2963,7 +3038,7 @@ func TestRuntimeMalformedArgumentPassing(t *testing.T) { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.IntType{}, + Type: cadence.IntType, }, }, } @@ -2988,7 +3063,7 @@ func TestRuntimeMalformedArgumentPassing(t *testing.T) { Fields: []cadence.Field{ { Identifier: "nonExisting", - Type: cadence.StringType{}, + Type: cadence.StringType, }, }, }, @@ -3031,7 +3106,7 @@ func TestRuntimeMalformedArgumentPassing(t *testing.T) { { Identifier: "a", Type: &cadence.DictionaryType{ - KeyType: cadence.StringType{}, + KeyType: cadence.StringType, ElementType: newMalformedStructType1(), }, }, @@ -3281,7 +3356,7 @@ func TestRuntimeImportExportArrayValue(t *testing.T) { assert.Equal(t, cadence.NewArray([]cadence.Value{}). WithType(&cadence.VariableSizedArrayType{ - ElementType: cadence.AnyStructType{}, + ElementType: cadence.AnyStructType, }), actual, ) @@ -3349,7 +3424,7 @@ func TestRuntimeImportExportArrayValue(t *testing.T) { cadence.NewInt(42), cadence.String("foo"), }).WithType(&cadence.VariableSizedArrayType{ - ElementType: cadence.AnyStructType{}, + ElementType: cadence.AnyStructType, }), actual, ) @@ -3486,8 +3561,8 @@ func TestRuntimeImportExportDictionaryValue(t *testing.T) { assert.Equal(t, cadence.NewDictionary([]cadence.KeyValuePair{}). WithType(&cadence.DictionaryType{ - KeyType: cadence.StringType{}, - ElementType: cadence.IntType{}, + KeyType: cadence.StringType, + ElementType: cadence.IntType, }), actual, ) @@ -3564,8 +3639,8 @@ func TestRuntimeImportExportDictionaryValue(t *testing.T) { Value: cadence.NewInt(1), }, }).WithType(&cadence.DictionaryType{ - KeyType: cadence.StringType{}, - ElementType: cadence.IntType{}, + KeyType: cadence.StringType, + ElementType: cadence.IntType, }), actual, ) @@ -3726,7 +3801,7 @@ func TestRuntimeImportExportDictionaryValue(t *testing.T) { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.AnyStructType{}, + Type: cadence.AnyStructType, }, }, }, @@ -3844,7 +3919,7 @@ func TestRuntimeStringValueImport(t *testing.T) { }) } -func TestTypeValueImport(t *testing.T) { +func TestRuntimeTypeValueImport(t *testing.T) { t.Parallel() @@ -3852,7 +3927,7 @@ func TestTypeValueImport(t *testing.T) { t.Parallel() - typeValue := cadence.NewTypeValue(cadence.IntType{}) + typeValue := cadence.NewTypeValue(cadence.IntType) script := ` access(all) fun main(s: Type) { @@ -3942,7 +4017,7 @@ func TestTypeValueImport(t *testing.T) { }) } -func TestCapabilityValueImport(t *testing.T) { +func TestRuntimeCapabilityValueImport(t *testing.T) { t.Parallel() @@ -3953,7 +4028,7 @@ func TestCapabilityValueImport(t *testing.T) { capabilityValue := cadence.NewCapability( 42, cadence.Address{0x1}, - &cadence.ReferenceType{Type: cadence.IntType{}}, + &cadence.ReferenceType{Type: cadence.IntType}, ) script := ` @@ -3997,7 +4072,7 @@ func TestCapabilityValueImport(t *testing.T) { capabilityValue := cadence.NewCapability( 3, cadence.Address{0x1}, - cadence.IntType{}, + cadence.IntType, ) script := ` @@ -4737,7 +4812,7 @@ func TestRuntimeImportExportComplex(t *testing.T) { } externalArrayType := &cadence.VariableSizedArrayType{ - ElementType: cadence.AnyStructType{}, + ElementType: cadence.AnyStructType, } internalArrayValue := interpreter.NewArrayValue( @@ -4753,7 +4828,7 @@ func TestRuntimeImportExportComplex(t *testing.T) { cadence.NewInt(42), cadence.String("foo"), }).WithType(&cadence.VariableSizedArrayType{ - ElementType: cadence.AnyStructType{}, + ElementType: cadence.AnyStructType, }) // Dictionary @@ -4769,7 +4844,7 @@ func TestRuntimeImportExportComplex(t *testing.T) { } externalDictionaryType := &cadence.DictionaryType{ - KeyType: cadence.StringType{}, + KeyType: cadence.StringType, ElementType: externalArrayType, } @@ -4786,9 +4861,9 @@ func TestRuntimeImportExportComplex(t *testing.T) { Value: externalArrayValue, }, }).WithType(&cadence.DictionaryType{ - KeyType: cadence.StringType{}, + KeyType: cadence.StringType, ElementType: &cadence.VariableSizedArrayType{ - ElementType: cadence.AnyStructType{}, + ElementType: cadence.AnyStructType, }, }) @@ -4929,7 +5004,7 @@ func TestRuntimeStaticTypeAvailability(t *testing.T) { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.AnyStructType{}, + Type: cadence.AnyStructType, }, }, }, @@ -4967,7 +5042,7 @@ func TestRuntimeStaticTypeAvailability(t *testing.T) { Fields: []cadence.Field{ { Identifier: "a", - Type: cadence.AnyStructType{}, + Type: cadence.AnyStructType, }, }, }, @@ -5008,7 +5083,7 @@ func newUnmeteredInMemoryStorage() interpreter.Storage { return interpreter.NewInMemoryStorage(nil) } -func TestNestedStructArgPassing(t *testing.T) { +func TestRuntimeNestedStructArgPassing(t *testing.T) { t.Parallel() t.Run("valid", func(t *testing.T) { @@ -5152,7 +5227,7 @@ func TestNestedStructArgPassing(t *testing.T) { }) } -func TestDestroyedResourceReferenceExport(t *testing.T) { +func TestRuntimeDestroyedResourceReferenceExport(t *testing.T) { t.Parallel() rt := newTestInterpreterRuntimeWithAttachments() diff --git a/runtime/coverage_test.go b/runtime/coverage_test.go index c28c55574d..8f3acc5094 100644 --- a/runtime/coverage_test.go +++ b/runtime/coverage_test.go @@ -32,7 +32,7 @@ import ( "github.com/onflow/cadence/runtime/stdlib" ) -func TestNewLocationCoverage(t *testing.T) { +func TestRuntimeNewLocationCoverage(t *testing.T) { t.Parallel() @@ -58,7 +58,7 @@ func TestNewLocationCoverage(t *testing.T) { assert.Equal(t, 0, locationCoverage.CoveredLines()) } -func TestLocationCoverageAddLineHit(t *testing.T) { +func TestRuntimeLocationCoverageAddLineHit(t *testing.T) { t.Parallel() @@ -88,7 +88,7 @@ func TestLocationCoverageAddLineHit(t *testing.T) { assert.Equal(t, "66.7%", locationCoverage.Percentage()) } -func TestLocationCoverageCoveredLines(t *testing.T) { +func TestRuntimeLocationCoverageCoveredLines(t *testing.T) { t.Parallel() @@ -104,7 +104,7 @@ func TestLocationCoverageCoveredLines(t *testing.T) { assert.Equal(t, 4, locationCoverage.CoveredLines()) } -func TestLocationCoverageMissedLines(t *testing.T) { +func TestRuntimeLocationCoverageMissedLines(t *testing.T) { t.Parallel() @@ -124,7 +124,7 @@ func TestLocationCoverageMissedLines(t *testing.T) { ) } -func TestLocationCoveragePercentage(t *testing.T) { +func TestRuntimeLocationCoveragePercentage(t *testing.T) { t.Parallel() @@ -141,7 +141,7 @@ func TestLocationCoveragePercentage(t *testing.T) { assert.Equal(t, "100.0%", locationCoverage.Percentage()) } -func TestNewCoverageReport(t *testing.T) { +func TestRuntimeNewCoverageReport(t *testing.T) { t.Parallel() @@ -152,7 +152,7 @@ func TestNewCoverageReport(t *testing.T) { assert.Equal(t, 0, len(coverageReport.ExcludedLocations)) } -func TestCoverageReportExcludeLocation(t *testing.T) { +func TestRuntimeCoverageReportExcludeLocation(t *testing.T) { t.Parallel() @@ -167,7 +167,7 @@ func TestCoverageReportExcludeLocation(t *testing.T) { assert.Equal(t, true, coverageReport.IsLocationExcluded(location)) } -func TestCoverageReportInspectProgram(t *testing.T) { +func TestRuntimeCoverageReportInspectProgram(t *testing.T) { t.Parallel() @@ -194,7 +194,7 @@ func TestCoverageReportInspectProgram(t *testing.T) { assert.Equal(t, true, coverageReport.IsLocationInspected(location)) } -func TestCoverageReportInspectProgramForExcludedLocation(t *testing.T) { +func TestRuntimeCoverageReportInspectProgramForExcludedLocation(t *testing.T) { t.Parallel() @@ -222,13 +222,13 @@ func TestCoverageReportInspectProgramForExcludedLocation(t *testing.T) { assert.Equal(t, false, coverageReport.IsLocationInspected(location)) } -func TestCoverageReportInspectProgramWithLocationFilter(t *testing.T) { +func TestRuntimeCoverageReportInspectProgramWithLocationFilter(t *testing.T) { t.Parallel() transaction := []byte(` transaction(amount: UFix64) { - prepare(account: AuthAccount) { + prepare(account: &Account) { assert(account.balance >= amount) } } @@ -253,7 +253,7 @@ func TestCoverageReportInspectProgramWithLocationFilter(t *testing.T) { assert.Equal(t, false, coverageReport.IsLocationInspected(location)) } -func TestCoverageReportAddLineHit(t *testing.T) { +func TestRuntimeCoverageReportAddLineHit(t *testing.T) { t.Parallel() @@ -296,7 +296,7 @@ func TestCoverageReportAddLineHit(t *testing.T) { assert.Equal(t, 2, locationCoverage.CoveredLines()) } -func TestCoverageReportWithFlowLocation(t *testing.T) { +func TestRuntimeCoverageReportWithFlowLocation(t *testing.T) { t.Parallel() @@ -342,7 +342,7 @@ func TestCoverageReportWithFlowLocation(t *testing.T) { require.JSONEq(t, expected, string(actual)) } -func TestCoverageReportWithREPLLocation(t *testing.T) { +func TestRuntimeCoverageReportWithREPLLocation(t *testing.T) { t.Parallel() @@ -388,7 +388,7 @@ func TestCoverageReportWithREPLLocation(t *testing.T) { require.JSONEq(t, expected, string(actual)) } -func TestCoverageReportWithScriptLocation(t *testing.T) { +func TestRuntimeCoverageReportWithScriptLocation(t *testing.T) { t.Parallel() @@ -434,7 +434,7 @@ func TestCoverageReportWithScriptLocation(t *testing.T) { require.JSONEq(t, expected, string(actual)) } -func TestCoverageReportWithStringLocation(t *testing.T) { +func TestRuntimeCoverageReportWithStringLocation(t *testing.T) { t.Parallel() @@ -480,7 +480,7 @@ func TestCoverageReportWithStringLocation(t *testing.T) { require.JSONEq(t, expected, string(actual)) } -func TestCoverageReportWithIdentifierLocation(t *testing.T) { +func TestRuntimeCoverageReportWithIdentifierLocation(t *testing.T) { t.Parallel() @@ -526,7 +526,7 @@ func TestCoverageReportWithIdentifierLocation(t *testing.T) { require.JSONEq(t, expected, string(actual)) } -func TestCoverageReportWithTransactionLocation(t *testing.T) { +func TestRuntimeCoverageReportWithTransactionLocation(t *testing.T) { t.Parallel() @@ -572,7 +572,7 @@ func TestCoverageReportWithTransactionLocation(t *testing.T) { require.JSONEq(t, expected, string(actual)) } -func TestCoverageReportWithAddressLocation(t *testing.T) { +func TestRuntimeCoverageReportWithAddressLocation(t *testing.T) { t.Parallel() @@ -621,7 +621,7 @@ func TestCoverageReportWithAddressLocation(t *testing.T) { require.JSONEq(t, expected, string(actual)) } -func TestCoverageReportReset(t *testing.T) { +func TestRuntimeCoverageReportReset(t *testing.T) { t.Parallel() @@ -664,7 +664,7 @@ func TestCoverageReportReset(t *testing.T) { assert.Equal(t, true, coverageReport.IsLocationExcluded(excludedLocation)) } -func TestCoverageReportAddLineHitForExcludedLocation(t *testing.T) { +func TestRuntimeCoverageReportAddLineHitForExcludedLocation(t *testing.T) { t.Parallel() @@ -681,7 +681,7 @@ func TestCoverageReportAddLineHitForExcludedLocation(t *testing.T) { assert.Equal(t, false, coverageReport.IsLocationInspected(location)) } -func TestCoverageReportAddLineHitWithLocationFilter(t *testing.T) { +func TestRuntimeCoverageReportAddLineHitWithLocationFilter(t *testing.T) { t.Parallel() @@ -702,7 +702,7 @@ func TestCoverageReportAddLineHitWithLocationFilter(t *testing.T) { assert.Equal(t, false, coverageReport.IsLocationInspected(location)) } -func TestCoverageReportAddLineHitForNonInspectedProgram(t *testing.T) { +func TestRuntimeCoverageReportAddLineHitForNonInspectedProgram(t *testing.T) { t.Parallel() @@ -718,7 +718,7 @@ func TestCoverageReportAddLineHitForNonInspectedProgram(t *testing.T) { assert.Equal(t, false, coverageReport.IsLocationInspected(location)) } -func TestCoverageReportPercentage(t *testing.T) { +func TestRuntimeCoverageReportPercentage(t *testing.T) { t.Parallel() @@ -768,7 +768,7 @@ func TestCoverageReportPercentage(t *testing.T) { assert.Equal(t, "50.0%", coverageReport.Percentage()) } -func TestCoverageReportString(t *testing.T) { +func TestRuntimeCoverageReportString(t *testing.T) { t.Parallel() @@ -823,7 +823,7 @@ func TestCoverageReportString(t *testing.T) { ) } -func TestCoverageReportDiff(t *testing.T) { +func TestRuntimeCoverageReportDiff(t *testing.T) { t.Parallel() @@ -888,7 +888,7 @@ func TestCoverageReportDiff(t *testing.T) { require.JSONEq(t, expected, string(actual)) } -func TestCoverageReportMerge(t *testing.T) { +func TestRuntimeCoverageReportMerge(t *testing.T) { t.Parallel() @@ -1014,7 +1014,7 @@ func TestCoverageReportMerge(t *testing.T) { require.JSONEq(t, expected, string(actual)) } -func TestCoverageReportUnmarshalJSON(t *testing.T) { +func TestRuntimeCoverageReportUnmarshalJSON(t *testing.T) { t.Parallel() @@ -1129,7 +1129,7 @@ func TestCoverageReportUnmarshalJSON(t *testing.T) { ) } -func TestCoverageReportUnmarshalJSONWithFormatError(t *testing.T) { +func TestRuntimeCoverageReportUnmarshalJSONWithFormatError(t *testing.T) { t.Parallel() @@ -1140,7 +1140,7 @@ func TestCoverageReportUnmarshalJSONWithFormatError(t *testing.T) { require.Error(t, err) } -func TestCoverageReportUnmarshalJSONWithDecodeLocationError(t *testing.T) { +func TestRuntimeCoverageReportUnmarshalJSONWithDecodeLocationError(t *testing.T) { t.Parallel() @@ -1169,7 +1169,7 @@ func TestCoverageReportUnmarshalJSONWithDecodeLocationError(t *testing.T) { require.ErrorContains(t, err, "invalid Location ID: X.Factorial") } -func TestCoverageReportUnmarshalJSONWithDecodeExcludedLocationError(t *testing.T) { +func TestRuntimeCoverageReportUnmarshalJSONWithDecodeExcludedLocationError(t *testing.T) { t.Parallel() @@ -1726,7 +1726,7 @@ func TestRuntimeCoverageWithNoStatements(t *testing.T) { require.JSONEq(t, expected, string(actual)) } -func TestCoverageReportLCOVFormat(t *testing.T) { +func TestRuntimeCoverageReportLCOVFormat(t *testing.T) { t.Parallel() diff --git a/runtime/crypto_test.go b/runtime/crypto_test.go index 82b42ce50c..74ef69f200 100644 --- a/runtime/crypto_test.go +++ b/runtime/crypto_test.go @@ -356,11 +356,11 @@ func TestRuntimeSignatureAlgorithmImport(t *testing.T) { cadence.UInt8(algo.RawValue()), }).WithType(&cadence.EnumType{ QualifiedIdentifier: "SignatureAlgorithm", - RawType: cadence.UInt8Type{}, + RawType: cadence.UInt8Type, Fields: []cadence.Field{ { Identifier: "rawValue", - Type: cadence.UInt8Type{}, + Type: cadence.UInt8Type, }, }, }), @@ -438,11 +438,11 @@ func TestRuntimeHashAlgorithmImport(t *testing.T) { cadence.UInt8(algo.RawValue()), }).WithType(&cadence.EnumType{ QualifiedIdentifier: "HashAlgorithm", - RawType: cadence.UInt8Type{}, + RawType: cadence.UInt8Type, Fields: []cadence.Field{ { Identifier: "rawValue", - Type: cadence.UInt8Type{}, + Type: cadence.UInt8Type, }, }, }), @@ -475,7 +475,7 @@ func TestRuntimeHashAlgorithmImport(t *testing.T) { } } -func TestBLSVerifyPoP(t *testing.T) { +func TestRuntimeBLSVerifyPoP(t *testing.T) { t.Parallel() @@ -534,7 +534,7 @@ func TestBLSVerifyPoP(t *testing.T) { assert.True(t, called) } -func TestBLSAggregateSignatures(t *testing.T) { +func TestRuntimeBLSAggregateSignatures(t *testing.T) { t.Parallel() @@ -591,7 +591,7 @@ func TestBLSAggregateSignatures(t *testing.T) { cadence.UInt8(4), cadence.UInt8(5), }).WithType(&cadence.VariableSizedArrayType{ - ElementType: cadence.UInt8Type{}, + ElementType: cadence.UInt8Type, }), result, ) @@ -599,7 +599,7 @@ func TestBLSAggregateSignatures(t *testing.T) { assert.True(t, called) } -func TestBLSAggregatePublicKeys(t *testing.T) { +func TestRuntimeBLSAggregatePublicKeys(t *testing.T) { t.Parallel() @@ -666,7 +666,7 @@ func TestBLSAggregatePublicKeys(t *testing.T) { cadence.UInt8(1), cadence.UInt8(2), }).WithType(&cadence.VariableSizedArrayType{ - ElementType: cadence.UInt8Type{}, + ElementType: cadence.UInt8Type, }), result.(cadence.Optional).Value.(cadence.Struct).Fields[0], ) @@ -693,7 +693,7 @@ func getCadenceValueArrayFromHexStr(t *testing.T, inp string) cadence.Value { // and should not be used as a sample code for Merkle Proof Verification, // for proper verification you need extra steps such as checking if the leaf content matches // what you're expecting and etc... -func TestTraversingMerkleProof(t *testing.T) { +func TestRuntimeTraversingMerkleProof(t *testing.T) { t.Parallel() @@ -703,8 +703,8 @@ func TestTraversingMerkleProof(t *testing.T) { access(all) fun main(rootHash: [UInt8], address: [UInt8], accountProof: [[UInt8]]){ let path = HashAlgorithm.KECCAK_256.hash(address) - - var nibbles: [UInt8] = [] + + var nibbles: [UInt8] = [] for b in path { nibbles.append(b >> 4) @@ -712,11 +712,11 @@ func TestTraversingMerkleProof(t *testing.T) { } var nibbleIndex = 0 - var expectedNodeHash = rootHash + var expectedNodeHash = rootHash for encodedNode in accountProof { log(nibbleIndex) - let nodeHash = HashAlgorithm.KECCAK_256.hash(encodedNode) + let nodeHash = HashAlgorithm.KECCAK_256.hash(encodedNode) // verify that expected node hash (from a higher level or given root hash) // matches the hash of this level diff --git a/runtime/debugger_test.go b/runtime/debugger_test.go index 4e914a8c89..cd20eae937 100644 --- a/runtime/debugger_test.go +++ b/runtime/debugger_test.go @@ -74,7 +74,7 @@ func TestRuntimeDebugger(t *testing.T) { Script{ Source: []byte(` transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { let answer = 42 log("Hello, World!") } @@ -164,7 +164,7 @@ func TestRuntimeDebuggerBreakpoints(t *testing.T) { Script{ Source: []byte(` transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { let answer = 42 log("Hello, World!") } diff --git a/runtime/deployedcontract_test.go b/runtime/deployedcontract_test.go index 49166bd53c..6b4c0c7cdc 100644 --- a/runtime/deployedcontract_test.go +++ b/runtime/deployedcontract_test.go @@ -28,7 +28,7 @@ import ( "github.com/onflow/cadence/runtime/tests/utils" ) -func TestDeployedContracts(t *testing.T) { +func TestRuntimeDeployedContracts(t *testing.T) { t.Parallel() contractCode := ` @@ -44,11 +44,11 @@ func TestDeployedContracts(t *testing.T) { script := ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { let deployedContract = signer.contracts.get(name: "Test") assert(deployedContract!.name == "Test") - let expected: {String: Void} = + let expected: {String: Void} = { "A.2a00000000000000.Test.A": () , "A.2a00000000000000.Test.B": () , "A.2a00000000000000.Test.C": () diff --git a/runtime/deployment_test.go b/runtime/deployment_test.go index 8e9202905a..48e7e7ba12 100644 --- a/runtime/deployment_test.go +++ b/runtime/deployment_test.go @@ -151,7 +151,7 @@ func TestRuntimeTransactionWithContractDeployment(t *testing.T) { ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(AddContract) &Account) { signer.contracts.add(name: "Test", code: %s%s) } } diff --git a/runtime/entitlements_test.go b/runtime/entitlements_test.go index f869a4f776..de0b5878ac 100644 --- a/runtime/entitlements_test.go +++ b/runtime/entitlements_test.go @@ -48,8 +48,8 @@ func TestRuntimeAccountEntitlementSaveAndLoadSuccess(t *testing.T) { transaction1 := []byte(` import Test from 0x1 transaction { - prepare(signer: AuthAccount) { - signer.save(3, to: /storage/foo) + prepare(signer: auth(Storage, Capabilities) &Account) { + signer.storage.save(3, to: /storage/foo) let cap = signer.capabilities.storage.issue(/storage/foo) signer.capabilities.publish(cap, at: /public/foo) } @@ -59,7 +59,7 @@ func TestRuntimeAccountEntitlementSaveAndLoadSuccess(t *testing.T) { transaction2 := []byte(` import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { let ref = signer.capabilities.borrow(/public/foo)! let downcastRef = ref as! auth(Test.X, Test.Y) &Int } @@ -140,8 +140,8 @@ func TestRuntimeAccountEntitlementSaveAndLoadFail(t *testing.T) { transaction1 := []byte(` import Test from 0x1 transaction { - prepare(signer: AuthAccount) { - signer.save(3, to: /storage/foo) + prepare(signer: auth(Storage, Capabilities) &Account) { + signer.storage.save(3, to: /storage/foo) let cap = signer.capabilities.storage.issue(/storage/foo) signer.capabilities.publish(cap, at: /public/foo) } @@ -151,7 +151,7 @@ func TestRuntimeAccountEntitlementSaveAndLoadFail(t *testing.T) { transaction2 := []byte(` import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { let ref = signer.capabilities.borrow(/public/foo)! let downcastRef = ref as! auth(Test.X, Test.Y) &Int } @@ -245,10 +245,11 @@ func TestRuntimeAccountEntitlementAttachmentMap(t *testing.T) { transaction1 := []byte(` import Test from 0x1 + transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Storage, Capabilities) &Account) { let r <- Test.createRWithA() - signer.save(<-r, to: /storage/foo) + signer.storage.save(<-r, to: /storage/foo) let cap = signer.capabilities.storage.issue(/storage/foo) signer.capabilities.publish(cap, at: /public/foo) } @@ -257,8 +258,9 @@ func TestRuntimeAccountEntitlementAttachmentMap(t *testing.T) { transaction2 := []byte(` import Test from 0x1 + transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { let ref = signer.capabilities.borrow(/public/foo)! ref[Test.A]!.foo() } @@ -345,9 +347,9 @@ func TestRuntimeAccountExportEntitledRef(t *testing.T) { import Test from 0x1 access(all) fun main(): &Test.R { let r <- Test.createR() - let authAccount = getAuthAccount(0x1) - authAccount.save(<-r, to: /storage/foo) - let ref = authAccount.borrow(from: /storage/foo)! + let authAccount = getAuthAccount(0x1) + authAccount.storage.save(<-r, to: /storage/foo) + let ref = authAccount.storage.borrow(from: /storage/foo)! return ref } `) @@ -525,9 +527,9 @@ func TestRuntimeAccountEntitlementCapabilityCasting(t *testing.T) { transaction1 := []byte(` import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Storage, Capabilities) &Account) { let r <- Test.createR() - signer.save(<-r, to: /storage/foo) + signer.storage.save(<-r, to: /storage/foo) let cap = signer.capabilities.storage.issue(/storage/foo) signer.capabilities.publish(cap, at: /public/foo) } @@ -537,7 +539,7 @@ func TestRuntimeAccountEntitlementCapabilityCasting(t *testing.T) { transaction2 := []byte(` import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { let capX = signer.capabilities.get(/public/foo)! let upCap = capX as Capability<&Test.R> let downCap = upCap as! Capability @@ -624,15 +626,18 @@ func TestRuntimeAccountEntitlementCapabilityDictionary(t *testing.T) { transaction1 := []byte(` import Test from 0x1 + transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Storage, Capabilities) &Account) { let r <- Test.createR() - signer.save(<-r, to: /storage/foo) + signer.storage.save(<-r, to: /storage/foo) + let capFoo = signer.capabilities.storage.issue(/storage/foo) signer.capabilities.publish(capFoo, at: /public/foo) let r2 <- Test.createR() - signer.save(<-r2, to: /storage/bar) + signer.storage.save(<-r2, to: /storage/bar) + let capBar = signer.capabilities.storage.issue(/storage/bar) signer.capabilities.publish(capBar, at: /public/bar) } @@ -642,7 +647,7 @@ func TestRuntimeAccountEntitlementCapabilityDictionary(t *testing.T) { transaction2 := []byte(` import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { let capX = signer.capabilities.get(/public/foo)! let capY = signer.capabilities.get(/public/bar)! @@ -736,15 +741,18 @@ func TestRuntimeAccountEntitlementGenericCapabilityDictionary(t *testing.T) { transaction1 := []byte(` import Test from 0x1 + transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Storage, Capabilities) &Account) { let r <- Test.createR() - signer.save(<-r, to: /storage/foo) + signer.storage.save(<-r, to: /storage/foo) + let capFoo = signer.capabilities.storage.issue(/storage/foo) signer.capabilities.publish(capFoo, at: /public/foo) let r2 <- Test.createR() - signer.save(<-r2, to: /storage/bar) + signer.storage.save(<-r2, to: /storage/bar) + let capBar = signer.capabilities.storage.issue(/storage/bar) signer.capabilities.publish(capBar, at: /public/bar) } @@ -754,7 +762,7 @@ func TestRuntimeAccountEntitlementGenericCapabilityDictionary(t *testing.T) { transaction2 := []byte(` import Test from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { let capX = signer.capabilities.get(/public/foo)! let capY = signer.capabilities.get(/public/bar)! @@ -883,10 +891,10 @@ func TestRuntimeCapabilityEntitlements(t *testing.T) { access(all) fun main() { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) let r <- create R() - account.save(<-r, to: /storage/foo) + account.storage.save(<-r, to: /storage/foo) let issuedCap = account.capabilities.storage.issue(/storage/foo) account.capabilities.publish(issuedCap, at: /public/foo) @@ -912,10 +920,10 @@ func TestRuntimeCapabilityEntitlements(t *testing.T) { access(all) fun main() { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) let r <- create R() - account.save(<-r, to: /storage/foo) + account.storage.save(<-r, to: /storage/foo) let issuedCap = account.capabilities.storage.issue(/storage/foo) account.capabilities.publish(issuedCap, at: /public/foo) @@ -944,10 +952,10 @@ func TestRuntimeCapabilityEntitlements(t *testing.T) { access(all) fun main() { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) let r <- create R() - account.save(<-r, to: /storage/foo) + account.storage.save(<-r, to: /storage/foo) let issuedCap = account.capabilities.storage.issue(/storage/foo) account.capabilities.publish(issuedCap, at: /public/foo) @@ -973,10 +981,10 @@ func TestRuntimeCapabilityEntitlements(t *testing.T) { access(all) fun main() { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) let s = S() - account.save(s, to: /storage/foo) + account.storage.save(s, to: /storage/foo) let issuedCap = account.capabilities.storage.issue(/storage/foo) account.capabilities.publish(issuedCap, at: /public/foo) @@ -1002,10 +1010,10 @@ func TestRuntimeCapabilityEntitlements(t *testing.T) { access(all) fun main() { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) let s = S() - account.save(s, to: /storage/foo) + account.storage.save(s, to: /storage/foo) let issuedCap = account.capabilities.storage.issue<&S>(/storage/foo) account.capabilities.publish(issuedCap, at: /public/foo) @@ -1035,10 +1043,10 @@ func TestRuntimeCapabilityEntitlements(t *testing.T) { access(all) fun main() { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) let r <- create R() - account.save(<-r, to: /storage/foo) + account.storage.save(<-r, to: /storage/foo) let issuedCap = account.capabilities.storage.issue(/storage/foo) account.capabilities.publish(issuedCap, at: /public/foo) @@ -1064,10 +1072,10 @@ func TestRuntimeCapabilityEntitlements(t *testing.T) { access(all) fun main() { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) let r <- create R() - account.save(<-r, to: /storage/foo) + account.storage.save(<-r, to: /storage/foo) let issuedCap = account.capabilities.storage.issue(/storage/foo) account.capabilities.publish(issuedCap, at: /public/foo) @@ -1093,10 +1101,10 @@ func TestRuntimeCapabilityEntitlements(t *testing.T) { access(all) fun main() { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) let r <- create R() - account.save(<-r, to: /storage/foo) + account.storage.save(<-r, to: /storage/foo) let issuedCap = account.capabilities.storage.issue(/storage/foo) account.capabilities.publish(issuedCap, at: /public/foo) diff --git a/runtime/environment.go b/runtime/environment.go index 5e307e4aa5..d32ca5ec58 100644 --- a/runtime/environment.go +++ b/runtime/environment.go @@ -63,8 +63,7 @@ type Environment interface { error, ) CommitStorage(inter *interpreter.Interpreter) error - NewAuthAccountValue(address interpreter.AddressValue) interpreter.Value - NewPublicAccountValue(address interpreter.AddressValue) interpreter.Value + NewAccountValue(address interpreter.AddressValue) interpreter.Value } // interpreterEnvironmentReconfigured is the portion of interpreterEnvironment @@ -93,10 +92,9 @@ var _ stdlib.Logger = &interpreterEnvironment{} var _ stdlib.UnsafeRandomGenerator = &interpreterEnvironment{} var _ stdlib.BlockAtHeightProvider = &interpreterEnvironment{} var _ stdlib.CurrentBlockProvider = &interpreterEnvironment{} -var _ stdlib.PublicAccountHandler = &interpreterEnvironment{} +var _ stdlib.AccountHandler = &interpreterEnvironment{} var _ stdlib.AccountCreator = &interpreterEnvironment{} var _ stdlib.EventEmitter = &interpreterEnvironment{} -var _ stdlib.AuthAccountHandler = &interpreterEnvironment{} var _ stdlib.PublicKeyValidator = &interpreterEnvironment{} var _ stdlib.PublicKeySignatureVerifier = &interpreterEnvironment{} var _ stdlib.BLSPoPVerifier = &interpreterEnvironment{} @@ -131,8 +129,7 @@ func (e *interpreterEnvironment) newInterpreterConfig() *interpreter.Config { UUIDHandler: e.newUUIDHandler(), ContractValueHandler: e.newContractValueHandler(), ImportLocationHandler: e.newImportLocationHandler(), - PublicAccountHandler: e.newPublicAccountHandler(), - AuthAccountHandler: e.newAuthAccountHandler(), + AccountHandler: e.NewAccountValue, OnRecordTrace: e.newOnRecordTraceHandler(), OnResourceOwnerChange: e.newResourceOwnerChangedHandler(), CompositeTypeHandler: e.newCompositeTypeHandler(), @@ -200,14 +197,6 @@ func (e *interpreterEnvironment) Declare(valueDeclaration stdlib.StandardLibrary interpreter.Declare(e.baseActivation, valueDeclaration) } -func (e *interpreterEnvironment) NewAuthAccountValue(address interpreter.AddressValue) interpreter.Value { - return stdlib.NewAuthAccountValue(e, e, address) -} - -func (e *interpreterEnvironment) NewPublicAccountValue(address interpreter.AddressValue) interpreter.Value { - return stdlib.NewPublicAccountValue(e, e, address) -} - func (e *interpreterEnvironment) MeterMemory(usage common.MemoryUsage) error { return e.runtimeInterface.MeterMemory(usage) } @@ -650,16 +639,8 @@ func (e *interpreterEnvironment) newOnRecordTraceHandler() interpreter.OnRecordT } } -func (e *interpreterEnvironment) newPublicAccountHandler() interpreter.PublicAccountHandlerFunc { - return func(address interpreter.AddressValue) interpreter.Value { - return stdlib.NewPublicAccountValue(e, e, address) - } -} - -func (e *interpreterEnvironment) newAuthAccountHandler() interpreter.AuthAccountHandlerFunc { - return func(address interpreter.AddressValue) interpreter.Value { - return stdlib.NewAuthAccountValue(e, e, address) - } +func (e *interpreterEnvironment) NewAccountValue(address interpreter.AddressValue) interpreter.Value { + return stdlib.NewAccountValue(e, e, address) } func (e *interpreterEnvironment) ValidatePublicKey(publicKey *stdlib.PublicKey) error { @@ -809,10 +790,11 @@ func (e *interpreterEnvironment) newInjectedCompositeFieldsHandler() interpreter ) return map[string]interpreter.Value{ - sema.ContractAccountFieldName: stdlib.NewAuthAccountValue( + sema.ContractAccountFieldName: stdlib.NewAccountReferenceValue( inter, e, addressValue, + interpreter.FullyEntitledAccountAccess, ), } } diff --git a/runtime/error_test.go b/runtime/error_test.go index afd62ba5df..0db3b0cf57 100644 --- a/runtime/error_test.go +++ b/runtime/error_test.go @@ -192,13 +192,13 @@ func TestRuntimeError(t *testing.T) { panic("42") } } - + access(all) fun createResource(): @Resource{ return <- create Resource( s: "argument" ) } - + access(all) fun main() { destroy createResource() } @@ -492,8 +492,8 @@ func TestRuntimeDefaultFunctionConflictPrintingError(t *testing.T) { return []byte(fmt.Sprintf( ` transaction { - prepare(signer: AuthAccount) { - let acct = AuthAccount(payer: signer) + prepare(signer: auth(BorrowValue) &Account) { + let acct = Account(payer: signer) acct.contracts.add(name: "%s", code: "%s".decodeHex()) } } @@ -513,7 +513,7 @@ func TestRuntimeDefaultFunctionConflictPrintingError(t *testing.T) { } access(all) resource interface B { - access(all) fun foo() + access(all) fun foo() } } ` @@ -619,8 +619,8 @@ func TestRuntimeMultipleInterfaceDefaultImplementationsError(t *testing.T) { return []byte(fmt.Sprintf( ` transaction { - prepare(signer: AuthAccount) { - let acct = AuthAccount(payer: signer) + prepare(signer: auth(BorrowValue) &Account) { + let acct = Account(payer: signer) acct.contracts.add(name: "%s", code: "%s".decodeHex()) } } diff --git a/runtime/ft_test.go b/runtime/ft_test.go index 61c9d6d146..a8ffbde2c2 100644 --- a/runtime/ft_test.go +++ b/runtime/ft_test.go @@ -360,13 +360,13 @@ access(all) contract FlowToken: FungibleToken { } } - init(adminAccount: AuthAccount) { + init(adminAccount: auth(Storage, Capabilities) &Account) { self.totalSupply = 0.0 // Create the Vault with the total supply of tokens and save it in storage // let vault <- create Vault(balance: self.totalSupply) - adminAccount.save(<-vault, to: /storage/flowTokenVault) + adminAccount.storage.save(<-vault, to: /storage/flowTokenVault) // Create a public capability to the stored Vault that only exposes // the 'deposit' method through the 'Receiver' interface @@ -383,7 +383,7 @@ access(all) contract FlowToken: FungibleToken { adminAccount.capabilities.publish(balanceCap, at: /public/flowTokenBalance) let admin <- create Administrator() - adminAccount.save(<-admin, to: /storage/flowTokenAdmin) + adminAccount.storage.save(<-admin, to: /storage/flowTokenAdmin) // Emit an event that shows that the contract was initialized emit TokensInitialized(initialSupply: self.totalSupply) @@ -397,11 +397,11 @@ import FlowToken from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { - if signer.borrow<&FlowToken.Vault>(from: /storage/flowTokenVault) == nil { + if signer.storage.borrow<&FlowToken.Vault>(from: /storage/flowTokenVault) == nil { // Create a new flowToken Vault and put it in storage - signer.save(<-FlowToken.createEmptyVault(), to: /storage/flowTokenVault) + signer.storage.save(<-FlowToken.createEmptyVault(), to: /storage/flowTokenVault) // Create a public capability to the Vault that only exposes // the deposit function through the Receiver interface @@ -429,7 +429,7 @@ transaction(recipient: Address, amount: UFix64) { let tokenAdmin: &FlowToken.Administrator let tokenReceiver: &{FungibleToken.Receiver} - prepare(signer: AuthAccount) { + prepare(signer: &Account) { self.tokenAdmin = signer .borrow<&FlowToken.Administrator>(from: /storage/flowTokenAdmin) ?? panic("Signer is not the token admin") @@ -460,10 +460,10 @@ transaction(amount: UFix64, to: Address) { // The Vault resource that holds the tokens that are being transferred let sentVault: @{FungibleToken.Vault} - prepare(signer: AuthAccount) { + prepare(signer: &Account) { // Get a reference to the signer's stored vault - let vaultRef = signer.borrow<&FlowToken.Vault>(from: /storage/flowTokenVault) + let vaultRef = signer.storage.borrow<&FlowToken.Vault>(from: /storage/flowTokenVault) ?? panic("Could not borrow reference to the owner's Vault!") // Withdraw tokens from the signer's stored vault @@ -567,7 +567,7 @@ func BenchmarkRuntimeFungibleTokenTransfer(b *testing.B) { ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { signer.contracts.add(name: "FlowToken", code: "%s".decodeHex(), signer) } } diff --git a/runtime/import_test.go b/runtime/import_test.go index 965919db3b..cbc663b952 100644 --- a/runtime/import_test.go +++ b/runtime/import_test.go @@ -114,7 +114,7 @@ func TestRuntimeCyclicImport(t *testing.T) { require.IsType(t, &sema.CyclicImportsError{}, errs[0]) } -func TestCheckCyclicImportsAfterUpdate(t *testing.T) { +func TestRuntimeCheckCyclicImportsAfterUpdate(t *testing.T) { runtime := newTestInterpreterRuntime() @@ -211,7 +211,7 @@ func TestCheckCyclicImportsAfterUpdate(t *testing.T) { require.IsType(t, &sema.CyclicImportsError{}, errs[0]) } -func TestCheckCyclicImportAddress(t *testing.T) { +func TestRuntimeCheckCyclicImportAddress(t *testing.T) { runtime := newTestInterpreterRuntime() @@ -322,7 +322,7 @@ func TestCheckCyclicImportAddress(t *testing.T) { require.IsType(t, &sema.CyclicImportsError{}, errs[0]) } -func TestCheckCyclicImportToSelfDuringDeploy(t *testing.T) { +func TestRuntimeCheckCyclicImportToSelfDuringDeploy(t *testing.T) { runtime := newTestInterpreterRuntime() diff --git a/runtime/imported_values_memory_metering_test.go b/runtime/imported_values_memory_metering_test.go index 47b58a6cbe..3418fe15f9 100644 --- a/runtime/imported_values_memory_metering_test.go +++ b/runtime/imported_values_memory_metering_test.go @@ -38,7 +38,7 @@ func testUseMemory(meter map[common.MemoryKind]uint64) func(common.MemoryUsage) } } -func TestImportedValueMemoryMetering(t *testing.T) { +func TestRuntimeImportedValueMemoryMetering(t *testing.T) { t.Parallel() @@ -406,7 +406,7 @@ func (testMemoryError) Error() string { return "memory limit exceeded" } -func TestImportedValueMemoryMeteringForSimpleTypes(t *testing.T) { +func TestRuntimeImportedValueMemoryMeteringForSimpleTypes(t *testing.T) { t.Parallel() @@ -529,7 +529,7 @@ func TestImportedValueMemoryMeteringForSimpleTypes(t *testing.T) { } } -func TestScriptDecodedLocationMetering(t *testing.T) { +func TestRuntimeScriptDecodedLocationMetering(t *testing.T) { t.Parallel() diff --git a/runtime/inbox_test.go b/runtime/inbox_test.go index 5d66655495..3978104c0a 100644 --- a/runtime/inbox_test.go +++ b/runtime/inbox_test.go @@ -27,7 +27,7 @@ import ( "github.com/onflow/cadence" ) -func TestAccountInboxPublishUnpublish(t *testing.T) { +func TestRuntimeAccountInboxPublishUnpublish(t *testing.T) { t.Parallel() storage := newTestLedger(nil, nil) @@ -38,8 +38,8 @@ func TestAccountInboxPublishUnpublish(t *testing.T) { transaction1 := []byte(` transaction { - prepare(signer: AuthAccount) { - signer.save([3], to: /storage/foo) + prepare(signer: auth(Storage, Capabilities, Inbox) &Account) { + signer.storage.save([3], to: /storage/foo) let cap = signer.capabilities.storage.issue<&[Int]>(/storage/foo) log(signer.inbox.publish(cap, name: "foo", recipient: 0x2)) } @@ -48,7 +48,7 @@ func TestAccountInboxPublishUnpublish(t *testing.T) { transaction2 := []byte(` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Inbox) &Account) { let cap = signer.inbox.unpublish<&[Int]>("foo")! log(cap.borrow()![0]) } @@ -116,7 +116,7 @@ func TestAccountInboxPublishUnpublish(t *testing.T) { ) } -func TestAccountInboxUnpublishWrongType(t *testing.T) { +func TestRuntimeAccountInboxUnpublishWrongType(t *testing.T) { t.Parallel() storage := newTestLedger(nil, nil) @@ -127,8 +127,8 @@ func TestAccountInboxUnpublishWrongType(t *testing.T) { transaction1 := []byte(` transaction { - prepare(signer: AuthAccount) { - signer.save([3], to: /storage/foo) + prepare(signer: auth(Storage, Capabilities, Inbox) &Account) { + signer.storage.save([3], to: /storage/foo) let cap = signer.capabilities.storage.issue<&[Int]>(/storage/foo) signer.inbox.publish(cap, name: "foo", recipient: 0x2) } @@ -137,7 +137,7 @@ func TestAccountInboxUnpublishWrongType(t *testing.T) { transaction2 := []byte(` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Inbox) &Account) { let cap = signer.inbox.unpublish<&[String]>("foo")! log(cap.borrow()![0]) } @@ -195,7 +195,7 @@ func TestAccountInboxUnpublishWrongType(t *testing.T) { ) } -func TestAccountInboxUnpublishAbsent(t *testing.T) { +func TestRuntimeAccountInboxUnpublishAbsent(t *testing.T) { t.Parallel() storage := newTestLedger(nil, nil) @@ -206,8 +206,8 @@ func TestAccountInboxUnpublishAbsent(t *testing.T) { transaction1 := []byte(` transaction { - prepare(signer: AuthAccount) { - signer.save([3], to: /storage/foo) + prepare(signer: auth(Storage, Capabilities, Inbox) &Account) { + signer.storage.save([3], to: /storage/foo) let cap = signer.capabilities.storage.issue<&[Int]>(/storage/foo) log(signer.inbox.publish(cap, name: "foo", recipient: 0x2)) } @@ -216,7 +216,7 @@ func TestAccountInboxUnpublishAbsent(t *testing.T) { transaction2 := []byte(` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Inbox) &Account) { let cap = signer.inbox.unpublish<&[Int]>("bar") log(cap) } @@ -284,7 +284,7 @@ func TestAccountInboxUnpublishAbsent(t *testing.T) { ) } -func TestAccountInboxUnpublishRemove(t *testing.T) { +func TestRuntimeAccountInboxUnpublishRemove(t *testing.T) { t.Parallel() storage := newTestLedger(nil, nil) @@ -295,8 +295,8 @@ func TestAccountInboxUnpublishRemove(t *testing.T) { transaction1 := []byte(` transaction { - prepare(signer: AuthAccount) { - signer.save([3], to: /storage/foo) + prepare(signer: auth(Storage, Capabilities, Inbox) &Account) { + signer.storage.save([3], to: /storage/foo) let cap = signer.capabilities.storage.issue<&[Int]>(/storage/foo) log(signer.inbox.publish(cap, name: "foo", recipient: 0x2)) } @@ -305,7 +305,7 @@ func TestAccountInboxUnpublishRemove(t *testing.T) { transaction2 := []byte(` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Inbox) &Account) { let cap = signer.inbox.unpublish<&[Int]>("foo")! log(cap.borrow()![0]) let cap2 = signer.inbox.unpublish<&[Int]>("foo") @@ -378,7 +378,7 @@ func TestAccountInboxUnpublishRemove(t *testing.T) { ) } -func TestAccountInboxUnpublishWrongAccount(t *testing.T) { +func TestRuntimeAccountInboxUnpublishWrongAccount(t *testing.T) { t.Parallel() storage := newTestLedger(nil, nil) @@ -389,8 +389,8 @@ func TestAccountInboxUnpublishWrongAccount(t *testing.T) { transaction1 := []byte(` transaction { - prepare(signer: AuthAccount) { - signer.save([3], to: /storage/foo) + prepare(signer: auth(Storage, Capabilities, Inbox) &Account) { + signer.storage.save([3], to: /storage/foo) let cap = signer.capabilities.storage.issue<&[Int]>(/storage/foo) log(signer.inbox.publish(cap, name: "foo", recipient: 0x2)) } @@ -399,7 +399,7 @@ func TestAccountInboxUnpublishWrongAccount(t *testing.T) { transaction1point5 := []byte(` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Inbox) &Account) { let cap = signer.inbox.unpublish<&[Int]>("foo") log(cap) } @@ -408,7 +408,7 @@ func TestAccountInboxUnpublishWrongAccount(t *testing.T) { transaction2 := []byte(` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Inbox) &Account) { let cap = signer.inbox.unpublish<&[Int]>("foo")! log(cap.borrow()![0]) } @@ -505,7 +505,7 @@ func TestAccountInboxUnpublishWrongAccount(t *testing.T) { ) } -func TestAccountInboxPublishClaim(t *testing.T) { +func TestRuntimeAccountInboxPublishClaim(t *testing.T) { t.Parallel() storage := newTestLedger(nil, nil) @@ -516,8 +516,8 @@ func TestAccountInboxPublishClaim(t *testing.T) { transaction1 := []byte(` transaction { - prepare(signer: AuthAccount) { - signer.save([3], to: /storage/foo) + prepare(signer: auth(Storage, Capabilities, Inbox) &Account) { + signer.storage.save([3], to: /storage/foo) let cap = signer.capabilities.storage.issue<&[Int]>(/storage/foo) log(signer.inbox.publish(cap, name: "foo", recipient: 0x2)) } @@ -526,7 +526,7 @@ func TestAccountInboxPublishClaim(t *testing.T) { transaction2 := []byte(` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Inbox) &Account) { let cap = signer.inbox.claim<&[Int]>("foo", provider: 0x1)! log(cap.borrow()![0]) } @@ -609,7 +609,7 @@ func TestAccountInboxPublishClaim(t *testing.T) { ) } -func TestAccountInboxPublishClaimWrongType(t *testing.T) { +func TestRuntimeAccountInboxPublishClaimWrongType(t *testing.T) { t.Parallel() storage := newTestLedger(nil, nil) @@ -620,8 +620,8 @@ func TestAccountInboxPublishClaimWrongType(t *testing.T) { transaction1 := []byte(` transaction { - prepare(signer: AuthAccount) { - signer.save([3], to: /storage/foo) + prepare(signer: auth(Storage, Capabilities, Inbox) &Account) { + signer.storage.save([3], to: /storage/foo) let cap = signer.capabilities.storage.issue<&[Int]>(/storage/foo) log(signer.inbox.publish(cap, name: "foo", recipient: 0x2)) } @@ -630,7 +630,7 @@ func TestAccountInboxPublishClaimWrongType(t *testing.T) { transaction2 := []byte(` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Inbox) &Account) { let cap = signer.inbox.claim<&[String]>("foo", provider: 0x1)! log(cap.borrow()![0]) } @@ -710,7 +710,7 @@ func TestAccountInboxPublishClaimWrongType(t *testing.T) { ) } -func TestAccountInboxPublishClaimWrongName(t *testing.T) { +func TestRuntimeAccountInboxPublishClaimWrongName(t *testing.T) { t.Parallel() storage := newTestLedger(nil, nil) @@ -721,8 +721,8 @@ func TestAccountInboxPublishClaimWrongName(t *testing.T) { transaction1 := []byte(` transaction { - prepare(signer: AuthAccount) { - signer.save([3], to: /storage/foo) + prepare(signer: auth(Storage, Capabilities, Inbox) &Account) { + signer.storage.save([3], to: /storage/foo) let cap = signer.capabilities.storage.issue<&[Int]>(/storage/foo) log(signer.inbox.publish(cap, name: "foo", recipient: 0x2)) } @@ -731,7 +731,7 @@ func TestAccountInboxPublishClaimWrongName(t *testing.T) { transaction2 := []byte(` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Inbox) &Account) { let cap = signer.inbox.claim<&[String]>("bar", provider: 0x1) log(cap) } @@ -812,7 +812,7 @@ func TestAccountInboxPublishClaimWrongName(t *testing.T) { ) } -func TestAccountInboxPublishClaimRemove(t *testing.T) { +func TestRuntimeAccountInboxPublishClaimRemove(t *testing.T) { t.Parallel() storage := newTestLedger(nil, nil) @@ -823,8 +823,8 @@ func TestAccountInboxPublishClaimRemove(t *testing.T) { transaction1 := []byte(` transaction { - prepare(signer: AuthAccount) { - signer.save([3], to: /storage/foo) + prepare(signer: auth(Storage, Capabilities, Inbox) &Account) { + signer.storage.save([3], to: /storage/foo) let cap = signer.capabilities.storage.issue<&[Int]>(/storage/foo) log(signer.inbox.publish(cap, name: "foo", recipient: 0x2)) } @@ -833,7 +833,7 @@ func TestAccountInboxPublishClaimRemove(t *testing.T) { transaction2 := []byte(` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Inbox) &Account) { let cap = signer.inbox.claim<&[Int]>("foo", provider: 0x1)! log(cap.borrow()![0]) } @@ -842,7 +842,7 @@ func TestAccountInboxPublishClaimRemove(t *testing.T) { transaction3 := []byte(` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Inbox) &Account) { let cap = signer.inbox.claim<&[Int]>("foo", provider: 0x1) log(cap) } @@ -939,7 +939,7 @@ func TestAccountInboxPublishClaimRemove(t *testing.T) { ) } -func TestAccountInboxPublishClaimWrongAccount(t *testing.T) { +func TestRuntimeAccountInboxPublishClaimWrongAccount(t *testing.T) { t.Parallel() storage := newTestLedger(nil, nil) @@ -950,8 +950,8 @@ func TestAccountInboxPublishClaimWrongAccount(t *testing.T) { transaction1 := []byte(` transaction { - prepare(signer: AuthAccount) { - signer.save([3], to: /storage/foo) + prepare(signer: auth(Storage, Capabilities, Inbox) &Account) { + signer.storage.save([3], to: /storage/foo) let cap = signer.capabilities.storage.issue<&[Int]>(/storage/foo) log(signer.inbox.publish(cap, name: "foo", recipient: 0x2)) } @@ -960,7 +960,7 @@ func TestAccountInboxPublishClaimWrongAccount(t *testing.T) { transaction2 := []byte(` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Inbox) &Account) { let cap = signer.inbox.claim<&[Int]>("foo", provider: 0x1) log(cap) } @@ -969,7 +969,7 @@ func TestAccountInboxPublishClaimWrongAccount(t *testing.T) { transaction3 := []byte(` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Inbox) &Account) { let cap = signer.inbox.claim<&[Int]>("foo", provider: 0x1)! log(cap.borrow()![0]) } diff --git a/runtime/interpreter/config.go b/runtime/interpreter/config.go index f6928e422b..c04e8ca59b 100644 --- a/runtime/interpreter/config.go +++ b/runtime/interpreter/config.go @@ -27,8 +27,6 @@ type Config struct { Storage Storage // ImportLocationHandler is used to handle imports of locations ImportLocationHandler ImportLocationHandlerFunc - // PublicAccountHandler is used to handle accounts - PublicAccountHandler PublicAccountHandlerFunc // OnInvokedFunctionReturn is triggered when an invoked function returned OnInvokedFunctionReturn OnInvokedFunctionReturnFunc // OnRecordTrace is triggered when a trace is recorded @@ -45,8 +43,8 @@ type Config struct { OnEventEmitted OnEventEmittedFunc // OnFunctionInvocation is triggered when a function invocation is about to be executed OnFunctionInvocation OnFunctionInvocationFunc - // AuthAccountHandler is used to handle accounts - AuthAccountHandler AuthAccountHandlerFunc + // AccountHandler is used to handle accounts + AccountHandler AccountHandlerFunc // UUIDHandler is used to handle the generation of UUIDs UUIDHandler UUIDHandlerFunc // CompositeTypeHandler is used to load composite types diff --git a/runtime/interpreter/encoding_test.go b/runtime/interpreter/encoding_test.go index 31009a4f01..56650ac62d 100644 --- a/runtime/interpreter/encoding_test.go +++ b/runtime/interpreter/encoding_test.go @@ -4069,6 +4069,41 @@ func TestEncodeDecodeAccountCapabilityControllerValue(t *testing.T) { ) }) + t.Run("unauthorized reference, Account", func(t *testing.T) { + + t.Parallel() + + value := &AccountCapabilityControllerValue{ + BorrowType: ReferenceStaticType{ + Authorization: UnauthorizedAccess, + ReferencedType: PrimitiveStaticTypeAccount, + }, + CapabilityID: capabilityID, + } + + encoded := assemble( + // tag + 0xd8, CBORTagReferenceStaticType, + // array, 2 items follow + 0x82, + // authorization: + // tag + 0xd8, CBORTagUnauthorizedStaticAuthorization, + // null + 0xf6, + 0xd8, CBORTagPrimitiveStaticType, + // unsigned 105 + 0x18, 0x69, + ) + + testEncodeDecode(t, + encodeDecodeTest{ + value: value, + encoded: encoded, + }, + ) + }) + t.Run("unauthorized reference, intersection I1", func(t *testing.T) { t.Parallel() diff --git a/runtime/interpreter/interpreter.go b/runtime/interpreter/interpreter.go index 57b85972af..df602b038e 100644 --- a/runtime/interpreter/interpreter.go +++ b/runtime/interpreter/interpreter.go @@ -156,15 +156,9 @@ type ImportLocationHandlerFunc func( location common.Location, ) Import -// AuthAccountHandlerFunc is a function that handles retrieving an auth account at a given address. -// The account returned must be of type `AuthAccount`. -type AuthAccountHandlerFunc func( - address AddressValue, -) Value - -// PublicAccountHandlerFunc is a function that handles retrieving a public account at a given address. -// The account returned must be of type `PublicAccount`. -type PublicAccountHandlerFunc func( +// AccountHandlerFunc is a function that handles retrieving an auth account at a given address. +// The account returned must be of type `Account`. +type AccountHandlerFunc func( address AddressValue, ) Value @@ -817,7 +811,7 @@ func (interpreter *Interpreter) resultValue(returnValue Value, returnType sema.T SetKind: sema.Conjunction, Entitlements: supportedEntitlements, } - auth = ConvertSemaAccesstoStaticAuthorization(interpreter, access) + auth = ConvertSemaAccessToStaticAuthorization(interpreter, access) } } return auth @@ -1297,7 +1291,7 @@ func (interpreter *Interpreter) declareNonEnumCompositeValue( // the constructor can only be called when in possession of the base resource // if the attachment is declared with access(all) access, then self is unauthorized if attachmentType.AttachmentEntitlementAccess != nil { - auth = ConvertSemaAccesstoStaticAuthorization(interpreter, attachmentType.AttachmentEntitlementAccess.Codomain()) + auth = ConvertSemaAccessToStaticAuthorization(interpreter, attachmentType.AttachmentEntitlementAccess.Codomain()) } self = NewEphemeralReferenceValue(interpreter, auth, value, attachmentType) @@ -1717,11 +1711,13 @@ func (interpreter *Interpreter) substituteMappedEntitlements(ty sema.Type) sema. return ty.Map(interpreter, make(map[*sema.TypeParameter]*sema.TypeParameter), func(t sema.Type) sema.Type { switch refType := t.(type) { case *sema.ReferenceType: - if _, isMappedAuth := refType.Authorization.(sema.EntitlementMapAccess); isMappedAuth { + if _, isMappedAuth := refType.Authorization.(*sema.EntitlementMapAccess); isMappedAuth { return sema.NewReferenceType( interpreter, refType.Type, - interpreter.MustConvertStaticAuthorizationToSemaAccess(interpreter.SharedState.currentEntitlementMappedValue), + interpreter.MustConvertStaticAuthorizationToSemaAccess( + interpreter.SharedState.currentEntitlementMappedValue, + ), ) } } @@ -1798,7 +1794,7 @@ func (interpreter *Interpreter) convertStaticType( if targetReferenceType, isReferenceType := targetSemaType.(*sema.ReferenceType); isReferenceType { return NewReferenceStaticType( interpreter, - ConvertSemaAccesstoStaticAuthorization(interpreter, targetReferenceType.Authorization), + ConvertSemaAccessToStaticAuthorization(interpreter, targetReferenceType.Authorization), valueStaticType.ReferencedType, ) } @@ -2126,7 +2122,7 @@ func (interpreter *Interpreter) convert(value Value, valueType, targetType sema. case *EphemeralReferenceValue: return NewEphemeralReferenceValue( interpreter, - ConvertSemaAccesstoStaticAuthorization(interpreter, unwrappedTargetType.Authorization), + ConvertSemaAccessToStaticAuthorization(interpreter, unwrappedTargetType.Authorization), ref.Value, unwrappedTargetType.Type, ) @@ -2134,19 +2130,12 @@ func (interpreter *Interpreter) convert(value Value, valueType, targetType sema. case *StorageReferenceValue: return NewStorageReferenceValue( interpreter, - ConvertSemaAccesstoStaticAuthorization(interpreter, unwrappedTargetType.Authorization), + ConvertSemaAccessToStaticAuthorization(interpreter, unwrappedTargetType.Authorization), ref.TargetStorageAddress, ref.TargetPath, unwrappedTargetType.Type, ) - case *AccountReferenceValue: - return NewAccountReferenceValue( - interpreter, - ref.Address, - unwrappedTargetType.Type, - ) - default: panic(errors.NewUnexpectedError("unsupported reference value: %T", ref)) } @@ -3253,7 +3242,7 @@ func lookupInterface(interpreter *Interpreter, typeID string) (*sema.InterfaceTy return nil, err } - typ, err := interpreter.getInterfaceType(location, qualifiedIdentifier) + typ, err := interpreter.GetInterfaceType(location, qualifiedIdentifier, TypeID(typeID)) if err != nil { return nil, err } @@ -3426,7 +3415,7 @@ func referenceTypeFunction(invocation Invocation) Value { panic(errors.NewUnreachableError()) } - var authorization Authorization = UnauthorizedAccess + authorization := UnauthorizedAccess errInIteration := false entitlementsCount := entitlementValues.Count() @@ -3921,7 +3910,12 @@ func (interpreter *Interpreter) domainPaths(address common.Address, domain commo return paths } -func (interpreter *Interpreter) accountPaths(addressValue AddressValue, locationRange LocationRange, domain common.PathDomain, pathType StaticType) *ArrayValue { +func (interpreter *Interpreter) accountPaths( + addressValue AddressValue, + locationRange LocationRange, + domain common.PathDomain, + pathType StaticType, +) *ArrayValue { address := addressValue.ToAddress() values := interpreter.domainPaths(address, domain) return NewArrayValue( @@ -3933,16 +3927,28 @@ func (interpreter *Interpreter) accountPaths(addressValue AddressValue, location ) } -func (interpreter *Interpreter) publicAccountPaths(addressValue AddressValue, locationRange LocationRange) *ArrayValue { - return interpreter.accountPaths(addressValue, locationRange, common.PathDomainPublic, PrimitiveStaticTypePublicPath) -} - -func (interpreter *Interpreter) privateAccountPaths(addressValue AddressValue, locationRange LocationRange) *ArrayValue { - return interpreter.accountPaths(addressValue, locationRange, common.PathDomainPrivate, PrimitiveStaticTypePrivatePath) +func (interpreter *Interpreter) publicAccountPaths( + addressValue AddressValue, + locationRange LocationRange, +) *ArrayValue { + return interpreter.accountPaths( + addressValue, + locationRange, + common.PathDomainPublic, + PrimitiveStaticTypePublicPath, + ) } -func (interpreter *Interpreter) storageAccountPaths(addressValue AddressValue, locationRange LocationRange) *ArrayValue { - return interpreter.accountPaths(addressValue, locationRange, common.PathDomainStorage, PrimitiveStaticTypeStoragePath) +func (interpreter *Interpreter) storageAccountPaths( + addressValue AddressValue, + locationRange LocationRange, +) *ArrayValue { + return interpreter.accountPaths( + addressValue, + locationRange, + common.PathDomainStorage, + PrimitiveStaticTypeStoragePath, + ) } func (interpreter *Interpreter) recordStorageMutation() { @@ -4122,7 +4128,7 @@ func (interpreter *Interpreter) authAccountSaveFunction(addressValue AddressValu return NewHostFunctionValue( interpreter, - sema.AuthAccountTypeSaveFunctionType, + sema.Account_StorageTypeSaveFunctionType, func(invocation Invocation) Value { interpreter := invocation.Interpreter @@ -4182,7 +4188,7 @@ func (interpreter *Interpreter) authAccountTypeFunction(addressValue AddressValu return NewHostFunctionValue( interpreter, - sema.AuthAccountTypeTypeFunctionType, + sema.Account_StorageTypeTypeFunctionType, func(invocation Invocation) Value { interpreter := invocation.Interpreter @@ -4228,8 +4234,8 @@ func (interpreter *Interpreter) authAccountReadFunction(addressValue AddressValu return NewHostFunctionValue( interpreter, - // same as sema.AuthAccountTypeCopyFunctionType - sema.AuthAccountTypeLoadFunctionType, + // same as sema.Account_StorageTypeCopyFunctionType + sema.Account_StorageTypeLoadFunctionType, func(invocation Invocation) Value { interpreter := invocation.Interpreter @@ -4308,7 +4314,7 @@ func (interpreter *Interpreter) authAccountBorrowFunction(addressValue AddressVa return NewHostFunctionValue( interpreter, - sema.AuthAccountTypeBorrowFunctionType, + sema.Account_StorageTypeBorrowFunctionType, func(invocation Invocation) Value { interpreter := invocation.Interpreter @@ -4331,7 +4337,7 @@ func (interpreter *Interpreter) authAccountBorrowFunction(addressValue AddressVa reference := NewStorageReferenceValue( interpreter, - ConvertSemaAccesstoStaticAuthorization(interpreter, referenceType.Authorization), + ConvertSemaAccessToStaticAuthorization(interpreter, referenceType.Authorization), address, path, referenceType.Type, @@ -4361,7 +4367,7 @@ func (interpreter *Interpreter) authAccountCheckFunction(addressValue AddressVal return NewHostFunctionValue( interpreter, - sema.AuthAccountTypeCheckFunctionType, + sema.Account_StorageTypeCheckFunctionType, func(invocation Invocation) Value { interpreter := invocation.Interpreter @@ -4398,11 +4404,6 @@ func (interpreter *Interpreter) authAccountCheckFunction(addressValue AddressVal ) } -var AuthAccountReferenceStaticType = ReferenceStaticType{ - ReferencedType: PrimitiveStaticTypeAuthAccount, - Authorization: UnauthorizedAccess, -} - func (interpreter *Interpreter) getEntitlement(typeID common.TypeID) (*sema.EntitlementType, error) { location, qualifiedIdentifier, err := common.DecodeTypeID(interpreter, string(typeID)) if err != nil { @@ -4476,8 +4477,8 @@ func (interpreter *Interpreter) ConvertStaticToSemaType(staticType StaticType) ( return ConvertStaticToSemaType( config.MemoryGauge, staticType, - func(location common.Location, qualifiedIdentifier string) (*sema.InterfaceType, error) { - return interpreter.getInterfaceType(location, qualifiedIdentifier) + func(location common.Location, qualifiedIdentifier string, typeID TypeID) (*sema.InterfaceType, error) { + return interpreter.GetInterfaceType(location, qualifiedIdentifier, typeID) }, func(location common.Location, qualifiedIdentifier string, typeID TypeID) (*sema.CompositeType, error) { return interpreter.GetCompositeType(location, qualifiedIdentifier, typeID) @@ -4500,7 +4501,12 @@ func (interpreter *Interpreter) MustConvertStaticToSemaType(staticType StaticTyp } func (interpreter *Interpreter) MustConvertStaticAuthorizationToSemaAccess(auth Authorization) sema.Access { - access, err := ConvertStaticAuthorizationToSemaAccess(interpreter, auth, interpreter.getEntitlement, interpreter.getEntitlementMapType) + access, err := ConvertStaticAuthorizationToSemaAccess( + interpreter, + auth, + interpreter.getEntitlement, + interpreter.getEntitlementMapType, + ) if err != nil { panic(err) } @@ -4585,13 +4591,15 @@ func (interpreter *Interpreter) getUserCompositeType(location common.Location, t return elaboration.CompositeType(typeID) } -func (interpreter *Interpreter) getInterfaceType(location common.Location, qualifiedIdentifier string) (*sema.InterfaceType, error) { +func (interpreter *Interpreter) GetInterfaceType( + location common.Location, + qualifiedIdentifier string, + typeID TypeID, +) (*sema.InterfaceType, error) { if location == nil { return nil, InterfaceMissingLocationError{QualifiedIdentifier: qualifiedIdentifier} } - typeID := location.TypeID(interpreter, qualifiedIdentifier) - elaboration := interpreter.getElaboration(location) if elaboration == nil { return nil, TypeLoadingError{ @@ -4685,7 +4693,7 @@ func (interpreter *Interpreter) mapMemberValueAuthorization( return resultValue } - if mappedAccess, isMappedAccess := (*memberAccess).(sema.EntitlementMapAccess); isMappedAccess { + if mappedAccess, isMappedAccess := (*memberAccess).(*sema.EntitlementMapAccess); isMappedAccess { var auth Authorization switch selfValue := self.(type) { case AuthorizedValue: @@ -4694,10 +4702,11 @@ func (interpreter *Interpreter) mapMemberValueAuthorization( if err != nil { panic(err) } - auth = ConvertSemaAccesstoStaticAuthorization(interpreter, imageAccess) + auth = ConvertSemaAccessToStaticAuthorization(interpreter, imageAccess) + default: var access sema.Access - if mappedAccess.Type == sema.IdentityMappingType { + if mappedAccess.Type == sema.IdentityType { access = sema.AllSupportedEntitlements(resultingType) } @@ -4705,7 +4714,7 @@ func (interpreter *Interpreter) mapMemberValueAuthorization( access = mappedAccess.Codomain() } - auth = ConvertSemaAccesstoStaticAuthorization(interpreter, access) + auth = ConvertSemaAccessToStaticAuthorization(interpreter, access) } switch refValue := resultValue.(type) { diff --git a/runtime/interpreter/interpreter_expression.go b/runtime/interpreter/interpreter_expression.go index f185de3b7e..b75a1cba59 100644 --- a/runtime/interpreter/interpreter_expression.go +++ b/runtime/interpreter/interpreter_expression.go @@ -268,13 +268,13 @@ func (interpreter *Interpreter) getReferenceValue(value Value, resultType sema.T } func (interpreter *Interpreter) getEffectiveAuthorization(referenceType *sema.ReferenceType) Authorization { - _, isMapped := referenceType.Authorization.(sema.EntitlementMapAccess) + _, isMapped := referenceType.Authorization.(*sema.EntitlementMapAccess) if isMapped && interpreter.SharedState.currentEntitlementMappedValue != nil { return interpreter.SharedState.currentEntitlementMappedValue } - return ConvertSemaAccesstoStaticAuthorization(interpreter, referenceType.Authorization) + return ConvertSemaAccessToStaticAuthorization(interpreter, referenceType.Authorization) } func (interpreter *Interpreter) checkMemberAccess( @@ -1389,7 +1389,7 @@ func (interpreter *Interpreter) VisitAttachExpression(attachExpression *ast.Atta SetKind: sema.Conjunction, Entitlements: attachmentType.RequiredEntitlements, } - auth = ConvertSemaAccesstoStaticAuthorization(interpreter, baseAccess) + auth = ConvertSemaAccessToStaticAuthorization(interpreter, baseAccess) } var baseValue Value = NewEphemeralReferenceValue( diff --git a/runtime/interpreter/interpreter_transaction.go b/runtime/interpreter/interpreter_transaction.go index ffa5508007..3d93c9a3ac 100644 --- a/runtime/interpreter/interpreter_transaction.go +++ b/runtime/interpreter/interpreter_transaction.go @@ -51,7 +51,8 @@ func (interpreter *Interpreter) declareTransactionEntryPoint(declaration *ast.Tr postConditionsRewrite := interpreter.Program.Elaboration.PostConditionsRewrite(declaration.PostConditions) - staticType := NewCompositeStaticTypeComputeTypeID(interpreter, interpreter.Location, "") + const qualifiedIdentifier = "" + staticType := NewCompositeStaticTypeComputeTypeID(interpreter, interpreter.Location, qualifiedIdentifier) self := NewSimpleCompositeValue( interpreter, diff --git a/runtime/interpreter/primitivestatictype.go b/runtime/interpreter/primitivestatictype.go index c31b35ca68..7063c7d03d 100644 --- a/runtime/interpreter/primitivestatictype.go +++ b/runtime/interpreter/primitivestatictype.go @@ -60,7 +60,12 @@ func NewPrimitiveStaticType( // // DO *NOT* REPLACE EXISTING TYPES! // DO *NOT* ADD NEW TYPES IN BETWEEN! - +// +// NOTE: The following types are not primitive types, but CompositeType-s +// - HashAlgorithm +// - SigningAlgorithm +// - AccountKey +// - PublicKey const ( PrimitiveStaticTypeUnknown PrimitiveStaticType = iota PrimitiveStaticTypeVoid @@ -74,8 +79,8 @@ const ( PrimitiveStaticTypeCharacter PrimitiveStaticTypeMetaType PrimitiveStaticTypeBlock - _ - _ + PrimitiveStaticTypeAnyResourceAttachment + PrimitiveStaticTypeAnyStructAttachment _ _ _ @@ -171,21 +176,79 @@ const ( _ _ _ + // Deprecated: PrimitiveStaticTypeAuthAccount only exists for migration purposes. PrimitiveStaticTypeAuthAccount + // Deprecated: PrimitiveStaticTypePublicAccount only exists for migration purposes. PrimitiveStaticTypePublicAccount PrimitiveStaticTypeDeployedContract + // Deprecated: PrimitiveStaticTypeAuthAccountContracts only exists for migration purposes. PrimitiveStaticTypeAuthAccountContracts + // Deprecated: PrimitiveStaticTypePublicAccountContracts only exists for migration purposes. PrimitiveStaticTypePublicAccountContracts + // Deprecated: PrimitiveStaticTypeAuthAccountKeys only exists for migration purposes. PrimitiveStaticTypeAuthAccountKeys + // Deprecated: PrimitiveStaticTypePublicAccountKeys only exists for migration purposes. PrimitiveStaticTypePublicAccountKeys + // Deprecated: PrimitiveStaticTypeAccountKey only exists for migration purposes PrimitiveStaticTypeAccountKey + // Deprecated: PrimitiveStaticTypeAuthAccountInbox only exists for migration purposes. PrimitiveStaticTypeAuthAccountInbox PrimitiveStaticTypeStorageCapabilityController PrimitiveStaticTypeAccountCapabilityController + // Deprecated: PrimitiveStaticTypeAuthAccountStorageCapabilities only exists for migration purposes. PrimitiveStaticTypeAuthAccountStorageCapabilities + // Deprecated: PrimitiveStaticTypeAuthAccountAccountCapabilities only exists for migration purposes. PrimitiveStaticTypeAuthAccountAccountCapabilities + // Deprecated: PrimitiveStaticTypeAuthAccountCapabilities only exists for migration purposes. PrimitiveStaticTypeAuthAccountCapabilities + // Deprecated: PrimitiveStaticTypePublicAccountCapabilities only exists for migration purposes. PrimitiveStaticTypePublicAccountCapabilities + PrimitiveStaticTypeAccount + PrimitiveStaticTypeAccount_Contracts + PrimitiveStaticTypeAccount_Keys + PrimitiveStaticTypeAccount_Inbox + PrimitiveStaticTypeAccount_StorageCapabilities + PrimitiveStaticTypeAccount_AccountCapabilities + PrimitiveStaticTypeAccount_Capabilities + PrimitiveStaticTypeAccount_Storage + _ + _ + _ + _ + _ + PrimitiveStaticTypeMutate + PrimitiveStaticTypeInsert + PrimitiveStaticTypeRemove + PrimitiveStaticTypeIdentity + _ + _ + _ + PrimitiveStaticTypeStorage + PrimitiveStaticTypeSaveValue + PrimitiveStaticTypeLoadValue + PrimitiveStaticTypeBorrowValue + PrimitiveStaticTypeContracts + PrimitiveStaticTypeAddContract + PrimitiveStaticTypeUpdateContract + PrimitiveStaticTypeRemoveContract + PrimitiveStaticTypeKeys + PrimitiveStaticTypeAddKey + PrimitiveStaticTypeRevokeKey + PrimitiveStaticTypeInbox + PrimitiveStaticTypePublishInboxCapability + PrimitiveStaticTypeUnpublishInboxCapability + PrimitiveStaticTypeClaimInboxCapability + PrimitiveStaticTypeCapabilities + PrimitiveStaticTypeStorageCapabilities + PrimitiveStaticTypeAccountCapabilities + PrimitiveStaticTypePublishCapability + PrimitiveStaticTypeUnpublishCapability + PrimitiveStaticTypeGetStorageCapabilityController + PrimitiveStaticTypeIssueStorageCapabilityController + PrimitiveStaticTypeGetAccountCapabilityController + PrimitiveStaticTypeIssueAccountCapabilityController + PrimitiveStaticTypeCapabilitiesMapping + PrimitiveStaticTypeAccountMapping // !!! *WARNING* !!! // ADD NEW TYPES *BEFORE* THIS WARNING. @@ -200,16 +263,23 @@ func (t PrimitiveStaticType) elementSize() uint { case PrimitiveStaticTypeAnyStruct, PrimitiveStaticTypeAnyResource, - PrimitiveStaticTypeAny: + PrimitiveStaticTypeAny, + PrimitiveStaticTypeAnyStructAttachment, + PrimitiveStaticTypeAnyResourceAttachment: return UnknownElementSize + case PrimitiveStaticTypeVoid: return uint(len(cborVoidValue)) + case PrimitiveStaticTypeNever: return cborTagSize + 1 + case PrimitiveStaticTypeBool: return cborTagSize + 1 + case PrimitiveStaticTypeAddress: return cborTagSize + 8 // address length is 8 bytes + case PrimitiveStaticTypeString, PrimitiveStaticTypeCharacter, PrimitiveStaticTypeMetaType, @@ -239,14 +309,17 @@ func (t PrimitiveStaticType) elementSize() uint { PrimitiveStaticTypeUInt8, PrimitiveStaticTypeWord8: return cborTagSize + 2 + case PrimitiveStaticTypeInt16, PrimitiveStaticTypeUInt16, PrimitiveStaticTypeWord16: return cborTagSize + 3 + case PrimitiveStaticTypeInt32, PrimitiveStaticTypeUInt32, PrimitiveStaticTypeWord32: return cborTagSize + 5 + case PrimitiveStaticTypeInt64, PrimitiveStaticTypeUInt64, PrimitiveStaticTypeWord64, @@ -260,24 +333,66 @@ func (t PrimitiveStaticType) elementSize() uint { PrimitiveStaticTypeCapabilityPath, PrimitiveStaticTypePublicPath, PrimitiveStaticTypePrivatePath, - PrimitiveStaticTypeAuthAccount, - PrimitiveStaticTypePublicAccount, PrimitiveStaticTypeDeployedContract, + PrimitiveStaticTypeStorageCapabilityController, + PrimitiveStaticTypeAccountCapabilityController, + PrimitiveStaticTypeAccount, + PrimitiveStaticTypeAccount_Contracts, + PrimitiveStaticTypeAccount_Keys, + PrimitiveStaticTypeAccount_Inbox, + PrimitiveStaticTypeAccount_StorageCapabilities, + PrimitiveStaticTypeAccount_AccountCapabilities, + PrimitiveStaticTypeAccount_Capabilities, + PrimitiveStaticTypeAccount_Storage, + PrimitiveStaticTypeMutate, + PrimitiveStaticTypeInsert, + PrimitiveStaticTypeRemove, + PrimitiveStaticTypeIdentity, + PrimitiveStaticTypeStorage, + PrimitiveStaticTypeSaveValue, + PrimitiveStaticTypeLoadValue, + PrimitiveStaticTypeBorrowValue, + PrimitiveStaticTypeContracts, + PrimitiveStaticTypeAddContract, + PrimitiveStaticTypeUpdateContract, + PrimitiveStaticTypeRemoveContract, + PrimitiveStaticTypeKeys, + PrimitiveStaticTypeAddKey, + PrimitiveStaticTypeRevokeKey, + PrimitiveStaticTypeInbox, + PrimitiveStaticTypePublishInboxCapability, + PrimitiveStaticTypeUnpublishInboxCapability, + PrimitiveStaticTypeClaimInboxCapability, + PrimitiveStaticTypeCapabilities, + PrimitiveStaticTypeStorageCapabilities, + PrimitiveStaticTypeAccountCapabilities, + PrimitiveStaticTypePublishCapability, + PrimitiveStaticTypeUnpublishCapability, + PrimitiveStaticTypeGetStorageCapabilityController, + PrimitiveStaticTypeIssueStorageCapabilityController, + PrimitiveStaticTypeGetAccountCapabilityController, + PrimitiveStaticTypeIssueAccountCapabilityController, + PrimitiveStaticTypeCapabilitiesMapping, + PrimitiveStaticTypeAccountMapping: + return UnknownElementSize + + case PrimitiveStaticTypeAuthAccount, + PrimitiveStaticTypePublicAccount, PrimitiveStaticTypeAuthAccountContracts, PrimitiveStaticTypePublicAccountContracts, - PrimitiveStaticTypeAuthAccountInbox, PrimitiveStaticTypeAuthAccountKeys, PrimitiveStaticTypePublicAccountKeys, - PrimitiveStaticTypeAccountKey, - PrimitiveStaticTypeStorageCapabilityController, - PrimitiveStaticTypeAccountCapabilityController, + PrimitiveStaticTypeAuthAccountInbox, PrimitiveStaticTypeAuthAccountStorageCapabilities, PrimitiveStaticTypeAuthAccountAccountCapabilities, PrimitiveStaticTypeAuthAccountCapabilities, - PrimitiveStaticTypePublicAccountCapabilities: + PrimitiveStaticTypePublicAccountCapabilities, + PrimitiveStaticTypeAccountKey: + // These types are deprecated, and only exist for migration purposes return UnknownElementSize } - return UnknownElementSize + + panic(errors.NewUnexpectedError("missing case for %s", t)) } func (t PrimitiveStaticType) Equal(other StaticType) bool { @@ -323,6 +438,12 @@ func (t PrimitiveStaticType) SemaType() sema.Type { case PrimitiveStaticTypeAnyResource: return sema.AnyResourceType + case PrimitiveStaticTypeAnyResourceAttachment: + return sema.AnyResourceAttachmentType + + case PrimitiveStaticTypeAnyStructAttachment: + return sema.AnyStructAttachmentType + case PrimitiveStaticTypeBool: return sema.BoolType @@ -429,39 +550,115 @@ func (t PrimitiveStaticType) SemaType() sema.Type { return sema.PrivatePathType case PrimitiveStaticTypeCapability: return &sema.CapabilityType{} - case PrimitiveStaticTypeAuthAccount: - return sema.AuthAccountType - case PrimitiveStaticTypePublicAccount: - return sema.PublicAccountType case PrimitiveStaticTypeDeployedContract: return sema.DeployedContractType - case PrimitiveStaticTypeAuthAccountContracts: - return sema.AuthAccountContractsType - case PrimitiveStaticTypePublicAccountContracts: - return sema.PublicAccountContractsType - case PrimitiveStaticTypeAuthAccountKeys: - return sema.AuthAccountKeysType - case PrimitiveStaticTypePublicAccountKeys: - return sema.PublicAccountKeysType - case PrimitiveStaticTypeAccountKey: - return sema.AccountKeyType - case PrimitiveStaticTypeAuthAccountInbox: - return sema.AuthAccountInboxType case PrimitiveStaticTypeStorageCapabilityController: return sema.StorageCapabilityControllerType case PrimitiveStaticTypeAccountCapabilityController: return sema.AccountCapabilityControllerType - case PrimitiveStaticTypeAuthAccountStorageCapabilities: - return sema.AuthAccountStorageCapabilitiesType - case PrimitiveStaticTypeAuthAccountAccountCapabilities: - return sema.AuthAccountAccountCapabilitiesType - case PrimitiveStaticTypeAuthAccountCapabilities: - return sema.AuthAccountCapabilitiesType - case PrimitiveStaticTypePublicAccountCapabilities: - return sema.PublicAccountCapabilitiesType - default: - panic(errors.NewUnexpectedError("missing case for %s", t)) + + case PrimitiveStaticTypeAuthAccount, + PrimitiveStaticTypePublicAccount, + PrimitiveStaticTypeAuthAccountContracts, + PrimitiveStaticTypePublicAccountContracts, + PrimitiveStaticTypeAuthAccountKeys, + PrimitiveStaticTypePublicAccountKeys, + PrimitiveStaticTypeAuthAccountInbox, + PrimitiveStaticTypeAuthAccountStorageCapabilities, + PrimitiveStaticTypeAuthAccountAccountCapabilities, + PrimitiveStaticTypeAuthAccountCapabilities, + PrimitiveStaticTypePublicAccountCapabilities, + PrimitiveStaticTypeAccountKey: + // These types are deprecated, and only exist for migration purposes + return nil + + case PrimitiveStaticTypeAccount: + return sema.AccountType + case PrimitiveStaticTypeAccount_Contracts: + return sema.Account_ContractsType + case PrimitiveStaticTypeAccount_Keys: + return sema.Account_KeysType + case PrimitiveStaticTypeAccount_Inbox: + return sema.Account_InboxType + case PrimitiveStaticTypeAccount_StorageCapabilities: + return sema.Account_StorageCapabilitiesType + case PrimitiveStaticTypeAccount_AccountCapabilities: + return sema.Account_AccountCapabilitiesType + case PrimitiveStaticTypeAccount_Capabilities: + return sema.Account_CapabilitiesType + case PrimitiveStaticTypeAccount_Storage: + return sema.Account_StorageType + + case PrimitiveStaticTypeMutate: + return sema.MutateType + case PrimitiveStaticTypeInsert: + return sema.InsertType + case PrimitiveStaticTypeRemove: + return sema.RemoveType + case PrimitiveStaticTypeIdentity: + return sema.IdentityType + + case PrimitiveStaticTypeStorage: + return sema.StorageType + case PrimitiveStaticTypeSaveValue: + return sema.SaveValueType + case PrimitiveStaticTypeLoadValue: + return sema.LoadValueType + case PrimitiveStaticTypeBorrowValue: + return sema.BorrowValueType + case PrimitiveStaticTypeContracts: + return sema.ContractsType + case PrimitiveStaticTypeAddContract: + return sema.AddContractType + case PrimitiveStaticTypeUpdateContract: + return sema.UpdateContractType + case PrimitiveStaticTypeRemoveContract: + return sema.RemoveContractType + case PrimitiveStaticTypeKeys: + return sema.KeysType + case PrimitiveStaticTypeAddKey: + return sema.AddKeyType + case PrimitiveStaticTypeRevokeKey: + return sema.RevokeKeyType + case PrimitiveStaticTypeInbox: + return sema.InboxType + case PrimitiveStaticTypePublishInboxCapability: + return sema.PublishInboxCapabilityType + case PrimitiveStaticTypeUnpublishInboxCapability: + return sema.UnpublishInboxCapabilityType + case PrimitiveStaticTypeClaimInboxCapability: + return sema.ClaimInboxCapabilityType + case PrimitiveStaticTypeCapabilities: + return sema.CapabilitiesType + case PrimitiveStaticTypeStorageCapabilities: + return sema.StorageCapabilitiesType + case PrimitiveStaticTypeAccountCapabilities: + return sema.AccountCapabilitiesType + case PrimitiveStaticTypePublishCapability: + return sema.PublishCapabilityType + case PrimitiveStaticTypeUnpublishCapability: + return sema.UnpublishCapabilityType + case PrimitiveStaticTypeGetStorageCapabilityController: + return sema.GetStorageCapabilityControllerType + case PrimitiveStaticTypeIssueStorageCapabilityController: + return sema.IssueStorageCapabilityControllerType + case PrimitiveStaticTypeGetAccountCapabilityController: + return sema.GetAccountCapabilityControllerType + case PrimitiveStaticTypeIssueAccountCapabilityController: + return sema.IssueAccountCapabilityControllerType + + case PrimitiveStaticTypeCapabilitiesMapping: + return sema.CapabilitiesMappingType + case PrimitiveStaticTypeAccountMapping: + return sema.AccountMappingType } + + panic(errors.NewUnexpectedError("missing case for %s", t)) +} + +func (t PrimitiveStaticType) IsDefined() bool { + _, ok := _PrimitiveStaticType_map[t] + return ok } // ConvertSemaToPrimitiveStaticType converts a `sema.Type` to a `PrimitiveStaticType`. @@ -575,38 +772,98 @@ func ConvertSemaToPrimitiveStaticType( typ = PrimitiveStaticTypeAnyStruct case sema.AnyResourceType: typ = PrimitiveStaticTypeAnyResource - case sema.AuthAccountType: - typ = PrimitiveStaticTypeAuthAccount - case sema.PublicAccountType: - typ = PrimitiveStaticTypePublicAccount + case sema.AnyStructAttachmentType: + typ = PrimitiveStaticTypeAnyStructAttachment + case sema.AnyResourceAttachmentType: + typ = PrimitiveStaticTypeAnyResourceAttachment case sema.BlockType: typ = PrimitiveStaticTypeBlock case sema.DeployedContractType: typ = PrimitiveStaticTypeDeployedContract - case sema.AuthAccountContractsType: - typ = PrimitiveStaticTypeAuthAccountContracts - case sema.PublicAccountContractsType: - typ = PrimitiveStaticTypePublicAccountContracts - case sema.AuthAccountKeysType: - typ = PrimitiveStaticTypeAuthAccountKeys - case sema.PublicAccountKeysType: - typ = PrimitiveStaticTypePublicAccountKeys - case sema.AccountKeyType: - typ = PrimitiveStaticTypeAccountKey - case sema.AuthAccountInboxType: - typ = PrimitiveStaticTypeAuthAccountInbox case sema.StorageCapabilityControllerType: typ = PrimitiveStaticTypeStorageCapabilityController case sema.AccountCapabilityControllerType: typ = PrimitiveStaticTypeAccountCapabilityController - case sema.AuthAccountStorageCapabilitiesType: - typ = PrimitiveStaticTypeAuthAccountStorageCapabilities - case sema.AuthAccountAccountCapabilitiesType: - typ = PrimitiveStaticTypeAuthAccountAccountCapabilities - case sema.AuthAccountCapabilitiesType: - typ = PrimitiveStaticTypeAuthAccountCapabilities - case sema.PublicAccountCapabilitiesType: - typ = PrimitiveStaticTypePublicAccountCapabilities + + case sema.AccountType: + typ = PrimitiveStaticTypeAccount + case sema.Account_ContractsType: + typ = PrimitiveStaticTypeAccount_Contracts + case sema.Account_KeysType: + typ = PrimitiveStaticTypeAccount_Keys + case sema.Account_InboxType: + typ = PrimitiveStaticTypeAccount_Inbox + case sema.Account_StorageCapabilitiesType: + typ = PrimitiveStaticTypeAccount_StorageCapabilities + case sema.Account_AccountCapabilitiesType: + typ = PrimitiveStaticTypeAccount_AccountCapabilities + case sema.Account_CapabilitiesType: + typ = PrimitiveStaticTypeAccount_Capabilities + case sema.Account_StorageType: + typ = PrimitiveStaticTypeAccount_Storage + + case sema.MutateType: + typ = PrimitiveStaticTypeMutate + case sema.InsertType: + typ = PrimitiveStaticTypeInsert + case sema.RemoveType: + typ = PrimitiveStaticTypeRemove + case sema.IdentityType: + typ = PrimitiveStaticTypeIdentity + + case sema.StorageType: + typ = PrimitiveStaticTypeStorage + case sema.SaveValueType: + typ = PrimitiveStaticTypeSaveValue + case sema.LoadValueType: + typ = PrimitiveStaticTypeLoadValue + case sema.BorrowValueType: + typ = PrimitiveStaticTypeBorrowValue + case sema.ContractsType: + typ = PrimitiveStaticTypeContracts + case sema.AddContractType: + typ = PrimitiveStaticTypeAddContract + case sema.UpdateContractType: + typ = PrimitiveStaticTypeUpdateContract + case sema.RemoveContractType: + typ = PrimitiveStaticTypeRemoveContract + case sema.KeysType: + typ = PrimitiveStaticTypeKeys + case sema.AddKeyType: + typ = PrimitiveStaticTypeAddKey + case sema.RevokeKeyType: + typ = PrimitiveStaticTypeRevokeKey + case sema.InboxType: + typ = PrimitiveStaticTypeInbox + case sema.PublishInboxCapabilityType: + typ = PrimitiveStaticTypePublishInboxCapability + case sema.UnpublishInboxCapabilityType: + typ = PrimitiveStaticTypeUnpublishInboxCapability + case sema.ClaimInboxCapabilityType: + typ = PrimitiveStaticTypeClaimInboxCapability + case sema.CapabilitiesType: + typ = PrimitiveStaticTypeCapabilities + case sema.StorageCapabilitiesType: + typ = PrimitiveStaticTypeStorageCapabilities + case sema.AccountCapabilitiesType: + typ = PrimitiveStaticTypeAccountCapabilities + case sema.PublishCapabilityType: + typ = PrimitiveStaticTypePublishCapability + case sema.UnpublishCapabilityType: + typ = PrimitiveStaticTypeUnpublishCapability + case sema.GetStorageCapabilityControllerType: + typ = PrimitiveStaticTypeGetStorageCapabilityController + case sema.IssueStorageCapabilityControllerType: + typ = PrimitiveStaticTypeIssueStorageCapabilityController + case sema.GetAccountCapabilityControllerType: + typ = PrimitiveStaticTypeGetAccountCapabilityController + case sema.IssueAccountCapabilityControllerType: + typ = PrimitiveStaticTypeIssueAccountCapabilityController + + case sema.CapabilitiesMappingType: + typ = PrimitiveStaticTypeCapabilitiesMapping + case sema.AccountMappingType: + typ = PrimitiveStaticTypeAccountMapping } switch t := t.(type) { diff --git a/runtime/interpreter/primitivestatictype_string.go b/runtime/interpreter/primitivestatictype_string.go index 639e2cff9d..bfd190afb8 100644 --- a/runtime/interpreter/primitivestatictype_string.go +++ b/runtime/interpreter/primitivestatictype_string.go @@ -20,6 +20,8 @@ func _() { _ = x[PrimitiveStaticTypeCharacter-9] _ = x[PrimitiveStaticTypeMetaType-10] _ = x[PrimitiveStaticTypeBlock-11] + _ = x[PrimitiveStaticTypeAnyResourceAttachment-12] + _ = x[PrimitiveStaticTypeAnyStructAttachment-13] _ = x[PrimitiveStaticTypeNumber-18] _ = x[PrimitiveStaticTypeSignedNumber-19] _ = x[PrimitiveStaticTypeInteger-24] @@ -69,10 +71,48 @@ func _() { _ = x[PrimitiveStaticTypeAuthAccountAccountCapabilities-102] _ = x[PrimitiveStaticTypeAuthAccountCapabilities-103] _ = x[PrimitiveStaticTypePublicAccountCapabilities-104] - _ = x[PrimitiveStaticType_Count-105] + _ = x[PrimitiveStaticTypeAccount-105] + _ = x[PrimitiveStaticTypeAccount_Contracts-106] + _ = x[PrimitiveStaticTypeAccount_Keys-107] + _ = x[PrimitiveStaticTypeAccount_Inbox-108] + _ = x[PrimitiveStaticTypeAccount_StorageCapabilities-109] + _ = x[PrimitiveStaticTypeAccount_AccountCapabilities-110] + _ = x[PrimitiveStaticTypeAccount_Capabilities-111] + _ = x[PrimitiveStaticTypeAccount_Storage-112] + _ = x[PrimitiveStaticTypeMutate-118] + _ = x[PrimitiveStaticTypeInsert-119] + _ = x[PrimitiveStaticTypeRemove-120] + _ = x[PrimitiveStaticTypeIdentity-121] + _ = x[PrimitiveStaticTypeStorage-125] + _ = x[PrimitiveStaticTypeSaveValue-126] + _ = x[PrimitiveStaticTypeLoadValue-127] + _ = x[PrimitiveStaticTypeBorrowValue-128] + _ = x[PrimitiveStaticTypeContracts-129] + _ = x[PrimitiveStaticTypeAddContract-130] + _ = x[PrimitiveStaticTypeUpdateContract-131] + _ = x[PrimitiveStaticTypeRemoveContract-132] + _ = x[PrimitiveStaticTypeKeys-133] + _ = x[PrimitiveStaticTypeAddKey-134] + _ = x[PrimitiveStaticTypeRevokeKey-135] + _ = x[PrimitiveStaticTypeInbox-136] + _ = x[PrimitiveStaticTypePublishInboxCapability-137] + _ = x[PrimitiveStaticTypeUnpublishInboxCapability-138] + _ = x[PrimitiveStaticTypeClaimInboxCapability-139] + _ = x[PrimitiveStaticTypeCapabilities-140] + _ = x[PrimitiveStaticTypeStorageCapabilities-141] + _ = x[PrimitiveStaticTypeAccountCapabilities-142] + _ = x[PrimitiveStaticTypePublishCapability-143] + _ = x[PrimitiveStaticTypeUnpublishCapability-144] + _ = x[PrimitiveStaticTypeGetStorageCapabilityController-145] + _ = x[PrimitiveStaticTypeIssueStorageCapabilityController-146] + _ = x[PrimitiveStaticTypeGetAccountCapabilityController-147] + _ = x[PrimitiveStaticTypeIssueAccountCapabilityController-148] + _ = x[PrimitiveStaticTypeCapabilitiesMapping-149] + _ = x[PrimitiveStaticTypeAccountMapping-150] + _ = x[PrimitiveStaticType_Count-151] } -const _PrimitiveStaticType_name = "UnknownVoidAnyNeverAnyStructAnyResourceBoolAddressStringCharacterMetaTypeBlockNumberSignedNumberIntegerSignedIntegerFixedPointSignedFixedPointIntInt8Int16Int32Int64Int128Int256UIntUInt8UInt16UInt32UInt64UInt128UInt256Word8Word16Word32Word64Word128Word256Fix64UFix64PathCapabilityStoragePathCapabilityPathPublicPathPrivatePathAuthAccountPublicAccountDeployedContractAuthAccountContractsPublicAccountContractsAuthAccountKeysPublicAccountKeysAccountKeyAuthAccountInboxStorageCapabilityControllerAccountCapabilityControllerAuthAccountStorageCapabilitiesAuthAccountAccountCapabilitiesAuthAccountCapabilitiesPublicAccountCapabilities_Count" +const _PrimitiveStaticType_name = "UnknownVoidAnyNeverAnyStructAnyResourceBoolAddressStringCharacterMetaTypeBlockAnyResourceAttachmentAnyStructAttachmentNumberSignedNumberIntegerSignedIntegerFixedPointSignedFixedPointIntInt8Int16Int32Int64Int128Int256UIntUInt8UInt16UInt32UInt64UInt128UInt256Word8Word16Word32Word64Word128Word256Fix64UFix64PathCapabilityStoragePathCapabilityPathPublicPathPrivatePathAuthAccountPublicAccountDeployedContractAuthAccountContractsPublicAccountContractsAuthAccountKeysPublicAccountKeysAccountKeyAuthAccountInboxStorageCapabilityControllerAccountCapabilityControllerAuthAccountStorageCapabilitiesAuthAccountAccountCapabilitiesAuthAccountCapabilitiesPublicAccountCapabilitiesAccountAccount_ContractsAccount_KeysAccount_InboxAccount_StorageCapabilitiesAccount_AccountCapabilitiesAccount_CapabilitiesAccount_StorageMutateInsertRemoveIdentityStorageSaveValueLoadValueBorrowValueContractsAddContractUpdateContractRemoveContractKeysAddKeyRevokeKeyInboxPublishInboxCapabilityUnpublishInboxCapabilityClaimInboxCapabilityCapabilitiesStorageCapabilitiesAccountCapabilitiesPublishCapabilityUnpublishCapabilityGetStorageCapabilityControllerIssueStorageCapabilityControllerGetAccountCapabilityControllerIssueAccountCapabilityControllerCapabilitiesMappingAccountMapping_Count" var _PrimitiveStaticType_map = map[PrimitiveStaticType]string{ 0: _PrimitiveStaticType_name[0:7], @@ -87,56 +127,96 @@ var _PrimitiveStaticType_map = map[PrimitiveStaticType]string{ 9: _PrimitiveStaticType_name[56:65], 10: _PrimitiveStaticType_name[65:73], 11: _PrimitiveStaticType_name[73:78], - 18: _PrimitiveStaticType_name[78:84], - 19: _PrimitiveStaticType_name[84:96], - 24: _PrimitiveStaticType_name[96:103], - 25: _PrimitiveStaticType_name[103:116], - 30: _PrimitiveStaticType_name[116:126], - 31: _PrimitiveStaticType_name[126:142], - 36: _PrimitiveStaticType_name[142:145], - 37: _PrimitiveStaticType_name[145:149], - 38: _PrimitiveStaticType_name[149:154], - 39: _PrimitiveStaticType_name[154:159], - 40: _PrimitiveStaticType_name[159:164], - 41: _PrimitiveStaticType_name[164:170], - 42: _PrimitiveStaticType_name[170:176], - 44: _PrimitiveStaticType_name[176:180], - 45: _PrimitiveStaticType_name[180:185], - 46: _PrimitiveStaticType_name[185:191], - 47: _PrimitiveStaticType_name[191:197], - 48: _PrimitiveStaticType_name[197:203], - 49: _PrimitiveStaticType_name[203:210], - 50: _PrimitiveStaticType_name[210:217], - 53: _PrimitiveStaticType_name[217:222], - 54: _PrimitiveStaticType_name[222:228], - 55: _PrimitiveStaticType_name[228:234], - 56: _PrimitiveStaticType_name[234:240], - 57: _PrimitiveStaticType_name[240:247], - 58: _PrimitiveStaticType_name[247:254], - 64: _PrimitiveStaticType_name[254:259], - 72: _PrimitiveStaticType_name[259:265], - 76: _PrimitiveStaticType_name[265:269], - 77: _PrimitiveStaticType_name[269:279], - 78: _PrimitiveStaticType_name[279:290], - 79: _PrimitiveStaticType_name[290:304], - 80: _PrimitiveStaticType_name[304:314], - 81: _PrimitiveStaticType_name[314:325], - 90: _PrimitiveStaticType_name[325:336], - 91: _PrimitiveStaticType_name[336:349], - 92: _PrimitiveStaticType_name[349:365], - 93: _PrimitiveStaticType_name[365:385], - 94: _PrimitiveStaticType_name[385:407], - 95: _PrimitiveStaticType_name[407:422], - 96: _PrimitiveStaticType_name[422:439], - 97: _PrimitiveStaticType_name[439:449], - 98: _PrimitiveStaticType_name[449:465], - 99: _PrimitiveStaticType_name[465:492], - 100: _PrimitiveStaticType_name[492:519], - 101: _PrimitiveStaticType_name[519:549], - 102: _PrimitiveStaticType_name[549:579], - 103: _PrimitiveStaticType_name[579:602], - 104: _PrimitiveStaticType_name[602:627], - 105: _PrimitiveStaticType_name[627:633], + 12: _PrimitiveStaticType_name[78:99], + 13: _PrimitiveStaticType_name[99:118], + 18: _PrimitiveStaticType_name[118:124], + 19: _PrimitiveStaticType_name[124:136], + 24: _PrimitiveStaticType_name[136:143], + 25: _PrimitiveStaticType_name[143:156], + 30: _PrimitiveStaticType_name[156:166], + 31: _PrimitiveStaticType_name[166:182], + 36: _PrimitiveStaticType_name[182:185], + 37: _PrimitiveStaticType_name[185:189], + 38: _PrimitiveStaticType_name[189:194], + 39: _PrimitiveStaticType_name[194:199], + 40: _PrimitiveStaticType_name[199:204], + 41: _PrimitiveStaticType_name[204:210], + 42: _PrimitiveStaticType_name[210:216], + 44: _PrimitiveStaticType_name[216:220], + 45: _PrimitiveStaticType_name[220:225], + 46: _PrimitiveStaticType_name[225:231], + 47: _PrimitiveStaticType_name[231:237], + 48: _PrimitiveStaticType_name[237:243], + 49: _PrimitiveStaticType_name[243:250], + 50: _PrimitiveStaticType_name[250:257], + 53: _PrimitiveStaticType_name[257:262], + 54: _PrimitiveStaticType_name[262:268], + 55: _PrimitiveStaticType_name[268:274], + 56: _PrimitiveStaticType_name[274:280], + 57: _PrimitiveStaticType_name[280:287], + 58: _PrimitiveStaticType_name[287:294], + 64: _PrimitiveStaticType_name[294:299], + 72: _PrimitiveStaticType_name[299:305], + 76: _PrimitiveStaticType_name[305:309], + 77: _PrimitiveStaticType_name[309:319], + 78: _PrimitiveStaticType_name[319:330], + 79: _PrimitiveStaticType_name[330:344], + 80: _PrimitiveStaticType_name[344:354], + 81: _PrimitiveStaticType_name[354:365], + 90: _PrimitiveStaticType_name[365:376], + 91: _PrimitiveStaticType_name[376:389], + 92: _PrimitiveStaticType_name[389:405], + 93: _PrimitiveStaticType_name[405:425], + 94: _PrimitiveStaticType_name[425:447], + 95: _PrimitiveStaticType_name[447:462], + 96: _PrimitiveStaticType_name[462:479], + 97: _PrimitiveStaticType_name[479:489], + 98: _PrimitiveStaticType_name[489:505], + 99: _PrimitiveStaticType_name[505:532], + 100: _PrimitiveStaticType_name[532:559], + 101: _PrimitiveStaticType_name[559:589], + 102: _PrimitiveStaticType_name[589:619], + 103: _PrimitiveStaticType_name[619:642], + 104: _PrimitiveStaticType_name[642:667], + 105: _PrimitiveStaticType_name[667:674], + 106: _PrimitiveStaticType_name[674:691], + 107: _PrimitiveStaticType_name[691:703], + 108: _PrimitiveStaticType_name[703:716], + 109: _PrimitiveStaticType_name[716:743], + 110: _PrimitiveStaticType_name[743:770], + 111: _PrimitiveStaticType_name[770:790], + 112: _PrimitiveStaticType_name[790:805], + 118: _PrimitiveStaticType_name[805:811], + 119: _PrimitiveStaticType_name[811:817], + 120: _PrimitiveStaticType_name[817:823], + 121: _PrimitiveStaticType_name[823:831], + 125: _PrimitiveStaticType_name[831:838], + 126: _PrimitiveStaticType_name[838:847], + 127: _PrimitiveStaticType_name[847:856], + 128: _PrimitiveStaticType_name[856:867], + 129: _PrimitiveStaticType_name[867:876], + 130: _PrimitiveStaticType_name[876:887], + 131: _PrimitiveStaticType_name[887:901], + 132: _PrimitiveStaticType_name[901:915], + 133: _PrimitiveStaticType_name[915:919], + 134: _PrimitiveStaticType_name[919:925], + 135: _PrimitiveStaticType_name[925:934], + 136: _PrimitiveStaticType_name[934:939], + 137: _PrimitiveStaticType_name[939:961], + 138: _PrimitiveStaticType_name[961:985], + 139: _PrimitiveStaticType_name[985:1005], + 140: _PrimitiveStaticType_name[1005:1017], + 141: _PrimitiveStaticType_name[1017:1036], + 142: _PrimitiveStaticType_name[1036:1055], + 143: _PrimitiveStaticType_name[1055:1072], + 144: _PrimitiveStaticType_name[1072:1091], + 145: _PrimitiveStaticType_name[1091:1121], + 146: _PrimitiveStaticType_name[1121:1153], + 147: _PrimitiveStaticType_name[1153:1183], + 148: _PrimitiveStaticType_name[1183:1215], + 149: _PrimitiveStaticType_name[1215:1234], + 150: _PrimitiveStaticType_name[1234:1248], + 151: _PrimitiveStaticType_name[1248:1254], } func (i PrimitiveStaticType) String() string { diff --git a/runtime/interpreter/primitivestatictype_test.go b/runtime/interpreter/primitivestatictype_test.go index df98c08aec..9dca22c6d0 100644 --- a/runtime/interpreter/primitivestatictype_test.go +++ b/runtime/interpreter/primitivestatictype_test.go @@ -19,7 +19,6 @@ package interpreter import ( - "regexp" "testing" "github.com/stretchr/testify/require" @@ -29,23 +28,48 @@ func TestPrimitiveStaticTypeSemaTypeConversion(t *testing.T) { t.Parallel() - placeholderTypePattern := regexp.MustCompile(`PrimitiveStaticType\(\d+\)`) - test := func(ty PrimitiveStaticType) { t.Run(ty.String(), func(t *testing.T) { t.Parallel() semaType := ty.SemaType() + + // Some primitive static types are deprecated, + // and only exist for migration purposes, + // so do not have an equivalent sema type + if semaType == nil { + return + } + ty2 := ConvertSemaToPrimitiveStaticType(nil, semaType) require.True(t, ty2.Equal(ty)) }) } for ty := PrimitiveStaticType(1); ty < PrimitiveStaticType_Count; ty++ { - if placeholderTypePattern.MatchString(ty.String()) { + if !ty.IsDefined() { continue } test(ty) } +} + +func TestPrimitiveStaticType_elementSize(t *testing.T) { + t.Parallel() + + test := func(ty PrimitiveStaticType) { + t.Run(ty.String(), func(t *testing.T) { + t.Parallel() + + _ = ty.elementSize() + }) + } + + for ty := PrimitiveStaticType(1); ty < PrimitiveStaticType_Count; ty++ { + if !ty.IsDefined() { + continue + } + test(ty) + } } diff --git a/runtime/interpreter/statictype.go b/runtime/interpreter/statictype.go index b488c3b88f..84e1225f15 100644 --- a/runtime/interpreter/statictype.go +++ b/runtime/interpreter/statictype.go @@ -578,6 +578,8 @@ type Unauthorized struct{} var UnauthorizedAccess Authorization = Unauthorized{} +var FullyEntitledAccountAccess = ConvertSemaAccessToStaticAuthorization(nil, sema.FullyEntitledAccountAccess) + func (Unauthorized) isAuthorization() {} func (Unauthorized) String() string { @@ -877,19 +879,19 @@ func ConvertSemaToStaticType(memoryGauge common.MemoryGauge, t sema.Type) Static ) case *sema.IntersectionType: - var intersectedTypess []InterfaceStaticType + var intersectedTypes []InterfaceStaticType typeCount := len(t.Types) if typeCount > 0 { - intersectedTypess = make([]InterfaceStaticType, typeCount) + intersectedTypes = make([]InterfaceStaticType, typeCount) for i, typ := range t.Types { - intersectedTypess[i] = ConvertSemaInterfaceTypeToStaticInterfaceType(memoryGauge, typ) + intersectedTypes[i] = ConvertSemaInterfaceTypeToStaticInterfaceType(memoryGauge, typ) } } return NewIntersectionStaticType( memoryGauge, - intersectedTypess, + intersectedTypes, ) case *sema.ReferenceType: @@ -943,7 +945,7 @@ func ConvertSemaDictionaryTypeToStaticDictionaryType( ) } -func ConvertSemaAccesstoStaticAuthorization( +func ConvertSemaAccessToStaticAuthorization( memoryGauge common.MemoryGauge, access sema.Access, ) Authorization { @@ -972,7 +974,7 @@ func ConvertSemaAccesstoStaticAuthorization( access.SetKind, ) - case sema.EntitlementMapAccess: + case *sema.EntitlementMapAccess: typeId := access.Type.ID() return NewEntitlementMapAuthorization(memoryGauge, typeId) } @@ -985,7 +987,7 @@ func ConvertSemaReferenceTypeToStaticReferenceType( ) ReferenceStaticType { return NewReferenceStaticType( memoryGauge, - ConvertSemaAccesstoStaticAuthorization(memoryGauge, t.Authorization), + ConvertSemaAccessToStaticAuthorization(memoryGauge, t.Authorization), ConvertSemaToStaticType(memoryGauge, t.Type), ) } @@ -1029,6 +1031,7 @@ func ConvertStaticAuthorizationToSemaAccess( return nil, err } return sema.NewEntitlementMapAccess(entitlement), nil + case EntitlementSetAuthorization: var entitlements []*sema.EntitlementType err := auth.Entitlements.ForeachWithError(func(id common.TypeID, value struct{}) error { @@ -1044,13 +1047,14 @@ func ConvertStaticAuthorizationToSemaAccess( } return sema.NewEntitlementSetAccess(entitlements, auth.SetKind), nil } + panic(errors.NewUnreachableError()) } func ConvertStaticToSemaType( memoryGauge common.MemoryGauge, typ StaticType, - getInterface func(location common.Location, qualifiedIdentifier string) (*sema.InterfaceType, error), + getInterface func(location common.Location, qualifiedIdentifier string, typeID TypeID) (*sema.InterfaceType, error), getComposite func(location common.Location, qualifiedIdentifier string, typeID TypeID) (*sema.CompositeType, error), getEntitlement func(typeID TypeID) (*sema.EntitlementType, error), getEntitlementMapType func(typeID TypeID) (*sema.EntitlementMapType, error), @@ -1060,7 +1064,7 @@ func ConvertStaticToSemaType( return getComposite(t.Location, t.QualifiedIdentifier, t.TypeID) case InterfaceStaticType: - return getInterface(t.Location, t.QualifiedIdentifier) + return getInterface(t.Location, t.QualifiedIdentifier, t.TypeID) case VariableSizedStaticType: ty, err := ConvertStaticToSemaType( @@ -1148,7 +1152,7 @@ func ConvertStaticToSemaType( intersectedTypes = make([]*sema.InterfaceType, typeCount) for i, typ := range t.Types { - intersectedTypes[i], err = getInterface(typ.Location, typ.QualifiedIdentifier) + intersectedTypes[i], err = getInterface(typ.Location, typ.QualifiedIdentifier, typ.TypeID) if err != nil { return nil, err } diff --git a/runtime/interpreter/statictype_test.go b/runtime/interpreter/statictype_test.go index 90b85bfd8e..2bbbc41e7a 100644 --- a/runtime/interpreter/statictype_test.go +++ b/runtime/interpreter/statictype_test.go @@ -879,7 +879,7 @@ func TestPrimitiveStaticTypeCount(t *testing.T) { // (before the PrimitiveStaticType_Count of course). // Only update this test if you are certain your change to this enum was to append new types to the end. t.Run("No new types added in between", func(t *testing.T) { - require.Equal(t, byte(105), byte(PrimitiveStaticType_Count)) + require.Equal(t, byte(151), byte(PrimitiveStaticType_Count)) }) } @@ -917,18 +917,21 @@ func TestStaticTypeConversion(t *testing.T) { testFunctionType := &sema.FunctionType{} - tests := []struct { + type testCase struct { name string semaType sema.Type staticType StaticType getInterface func( + t *testing.T, location common.Location, qualifiedIdentifier string, + typeID TypeID, ) ( *sema.InterfaceType, error, ) getComposite func( + t *testing.T, location common.Location, qualifiedIdentifier string, typeID TypeID, @@ -936,7 +939,9 @@ func TestStaticTypeConversion(t *testing.T) { *sema.CompositeType, error, ) - }{ + } + + tests := []testCase{ { name: "Void", semaType: sema.VoidType, @@ -1171,52 +1176,237 @@ func TestStaticTypeConversion(t *testing.T) { semaType: sema.PrivatePathType, staticType: PrimitiveStaticTypePrivatePath, }, - { - name: "AuthAccount", - semaType: sema.AuthAccountType, - staticType: PrimitiveStaticTypeAuthAccount, + name: "Account", + semaType: sema.AccountType, + staticType: PrimitiveStaticTypeAccount, }, - { - name: "PublicAccount", - semaType: sema.PublicAccountType, - staticType: PrimitiveStaticTypePublicAccount, - }, - { name: "DeployedContract", semaType: sema.DeployedContractType, staticType: PrimitiveStaticTypeDeployedContract, }, { - name: "AuthAccount.Contracts", - semaType: sema.AuthAccountContractsType, - staticType: PrimitiveStaticTypeAuthAccountContracts, + name: "Account.Storage", + semaType: sema.Account_StorageType, + staticType: PrimitiveStaticTypeAccount_Storage, }, { - name: "PublicAccount.Contracts", - semaType: sema.PublicAccountContractsType, - staticType: PrimitiveStaticTypePublicAccountContracts, + name: "Account.Contracts", + semaType: sema.Account_ContractsType, + staticType: PrimitiveStaticTypeAccount_Contracts, }, { - name: "AuthAccount.Keys", - semaType: sema.AuthAccountKeysType, - staticType: PrimitiveStaticTypeAuthAccountKeys, + name: "Account.Keys", + semaType: sema.Account_KeysType, + staticType: PrimitiveStaticTypeAccount_Keys, }, { - name: "PublicAccount.Keys", - semaType: sema.PublicAccountKeysType, - staticType: PrimitiveStaticTypePublicAccountKeys, + name: "Account.Inbox", + semaType: sema.Account_InboxType, + staticType: PrimitiveStaticTypeAccount_Inbox, + }, + { + name: "Account.Capabilities", + semaType: sema.Account_CapabilitiesType, + staticType: PrimitiveStaticTypeAccount_Capabilities, + }, + { + name: "Account.StorageCapabilities", + semaType: sema.Account_StorageCapabilitiesType, + staticType: PrimitiveStaticTypeAccount_StorageCapabilities, + }, + { + name: "Account.AccountCapabilities", + semaType: sema.Account_AccountCapabilitiesType, + staticType: PrimitiveStaticTypeAccount_AccountCapabilities, + }, + { + name: "StorageCapabilityController", + semaType: sema.StorageCapabilityControllerType, + staticType: PrimitiveStaticTypeStorageCapabilityController, + }, + { + name: "AccountCapabilityController", + semaType: sema.AccountCapabilityControllerType, + staticType: PrimitiveStaticTypeAccountCapabilityController, + }, + + { + name: "AnyResourceAttachment", + semaType: sema.AnyResourceAttachmentType, + staticType: PrimitiveStaticTypeAnyResourceAttachment, + }, + + { + name: "AnyStructAttachment", + semaType: sema.AnyStructAttachmentType, + staticType: PrimitiveStaticTypeAnyStructAttachment, }, { name: "AccountKey", semaType: sema.AccountKeyType, - staticType: PrimitiveStaticTypeAccountKey, + staticType: AccountKeyStaticType, + getComposite: func( + t *testing.T, + location common.Location, + qualifiedIdentifier string, + _ TypeID, + ) (*sema.CompositeType, error) { + require.Nil(t, location) + require.Equal(t, "AccountKey", qualifiedIdentifier) + return sema.AccountKeyType, nil + }, }, { - name: "AuthAccount.Inbox", - semaType: sema.AuthAccountInboxType, - staticType: PrimitiveStaticTypeAuthAccountInbox, + name: "Mutate", + semaType: sema.MutateType, + staticType: PrimitiveStaticTypeMutate, + }, + { + name: "Insert", + semaType: sema.InsertType, + staticType: PrimitiveStaticTypeInsert, + }, + { + name: "Remove", + semaType: sema.RemoveType, + staticType: PrimitiveStaticTypeRemove, + }, + { + name: "Storage", + semaType: sema.StorageType, + staticType: PrimitiveStaticTypeStorage, + }, + { + name: "SaveValue", + semaType: sema.SaveValueType, + staticType: PrimitiveStaticTypeSaveValue, + }, + { + name: "LoadValue", + semaType: sema.LoadValueType, + staticType: PrimitiveStaticTypeLoadValue, + }, + { + name: "BorrowValue", + semaType: sema.BorrowValueType, + staticType: PrimitiveStaticTypeBorrowValue, + }, + { + name: "Contracts", + semaType: sema.ContractsType, + staticType: PrimitiveStaticTypeContracts, + }, + { + name: "AddContract", + semaType: sema.AddContractType, + staticType: PrimitiveStaticTypeAddContract, + }, + { + name: "UpdateContract", + semaType: sema.UpdateContractType, + staticType: PrimitiveStaticTypeUpdateContract, + }, + { + name: "RemoveContract", + semaType: sema.RemoveContractType, + staticType: PrimitiveStaticTypeRemoveContract, + }, + { + name: "Keys", + semaType: sema.KeysType, + staticType: PrimitiveStaticTypeKeys, + }, + { + name: "AddKey", + semaType: sema.AddKeyType, + staticType: PrimitiveStaticTypeAddKey, + }, + { + name: "RevokeKey", + semaType: sema.RevokeKeyType, + staticType: PrimitiveStaticTypeRevokeKey, + }, + { + name: "Inbox", + semaType: sema.InboxType, + staticType: PrimitiveStaticTypeInbox, + }, + { + name: "PublishInboxCapability", + semaType: sema.PublishInboxCapabilityType, + staticType: PrimitiveStaticTypePublishInboxCapability, + }, + { + name: "UnpublishInboxCapability", + semaType: sema.UnpublishInboxCapabilityType, + staticType: PrimitiveStaticTypeUnpublishInboxCapability, + }, + { + name: "ClaimInboxCapability", + semaType: sema.ClaimInboxCapabilityType, + staticType: PrimitiveStaticTypeClaimInboxCapability, + }, + { + name: "Capabilities", + semaType: sema.CapabilitiesType, + staticType: PrimitiveStaticTypeCapabilities, + }, + { + name: "StorageCapabilities", + semaType: sema.StorageCapabilitiesType, + staticType: PrimitiveStaticTypeStorageCapabilities, + }, + { + name: "AccountCapabilities", + semaType: sema.AccountCapabilitiesType, + staticType: PrimitiveStaticTypeAccountCapabilities, + }, + { + name: "PublishCapability", + semaType: sema.PublishCapabilityType, + staticType: PrimitiveStaticTypePublishCapability, + }, + { + name: "UnpublishCapability", + semaType: sema.UnpublishCapabilityType, + staticType: PrimitiveStaticTypeUnpublishCapability, + }, + { + name: "GetStorageCapabilityController", + semaType: sema.GetStorageCapabilityControllerType, + staticType: PrimitiveStaticTypeGetStorageCapabilityController, + }, + { + name: "IssueStorageCapabilityController", + semaType: sema.IssueStorageCapabilityControllerType, + staticType: PrimitiveStaticTypeIssueStorageCapabilityController, + }, + { + name: "GetAccountCapabilityController", + semaType: sema.GetAccountCapabilityControllerType, + staticType: PrimitiveStaticTypeGetAccountCapabilityController, + }, + { + name: "IssueAccountCapabilityController", + semaType: sema.IssueAccountCapabilityControllerType, + staticType: PrimitiveStaticTypeIssueAccountCapabilityController, + }, + { + name: "CapabilitiesMapping", + semaType: sema.CapabilitiesMappingType, + staticType: PrimitiveStaticTypeCapabilitiesMapping, + }, + { + name: "AccountMapping", + semaType: sema.AccountMappingType, + staticType: PrimitiveStaticTypeAccountMapping, + }, + { + name: "Identity", + semaType: sema.IdentityType, + staticType: PrimitiveStaticTypeIdentity, }, { @@ -1297,7 +1487,12 @@ func TestStaticTypeConversion(t *testing.T) { testInterfaceStaticType, }, }, - getInterface: func(location common.Location, qualifiedIdentifier string) (*sema.InterfaceType, error) { + getInterface: func( + t *testing.T, + location common.Location, + qualifiedIdentifier string, + typeID TypeID, + ) (*sema.InterfaceType, error) { require.Equal(t, testLocation, location) require.Equal(t, testInterfaceQualifiedIdentifier, qualifiedIdentifier) return testInterfaceSemaType, nil @@ -1307,7 +1502,12 @@ func TestStaticTypeConversion(t *testing.T) { name: "Interface", semaType: testInterfaceSemaType, staticType: testInterfaceStaticType, - getInterface: func(location common.Location, qualifiedIdentifier string) (*sema.InterfaceType, error) { + getInterface: func( + t *testing.T, + location common.Location, + qualifiedIdentifier string, + typeID TypeID, + ) (*sema.InterfaceType, error) { require.Equal(t, testLocation, location) require.Equal(t, testInterfaceQualifiedIdentifier, qualifiedIdentifier) return testInterfaceSemaType, nil @@ -1317,7 +1517,12 @@ func TestStaticTypeConversion(t *testing.T) { name: "Composite", semaType: testCompositeSemaType, staticType: testCompositeStaticType, - getComposite: func(location common.Location, qualifiedIdentifier string, typeID TypeID) (*sema.CompositeType, error) { + getComposite: func( + t *testing.T, + location common.Location, + qualifiedIdentifier string, + typeID TypeID, + ) (*sema.CompositeType, error) { require.Equal(t, testLocation, location) require.Equal(t, testCompositeQualifiedIdentifier, qualifiedIdentifier) return testCompositeSemaType, nil @@ -1330,24 +1535,95 @@ func TestStaticTypeConversion(t *testing.T) { Type: testFunctionType, }, }, + + // Deprecated primitive static types, only exist for migration purposes + { + name: "AuthAccount", + semaType: nil, + staticType: PrimitiveStaticTypeAuthAccount, + }, + { + name: "PublicAccount", + semaType: nil, + staticType: PrimitiveStaticTypePublicAccount, + }, + { + name: "AuthAccount.Contracts", + staticType: PrimitiveStaticTypeAuthAccountContracts, + semaType: nil, + }, + { + name: "PublicAccount.Contracts", + staticType: PrimitiveStaticTypePublicAccountContracts, + semaType: nil, + }, + { + name: "AuthAccount.Keys", + staticType: PrimitiveStaticTypeAuthAccountKeys, + semaType: nil, + }, + { + name: "PublicAccount.Keys", + staticType: PrimitiveStaticTypePublicAccountKeys, + semaType: nil, + }, + { + name: "AuthAccount.Inbox", + staticType: PrimitiveStaticTypeAuthAccountInbox, + semaType: nil, + }, + { + name: "AuthAccount.StorageCapabilities", + staticType: PrimitiveStaticTypeAuthAccountStorageCapabilities, + semaType: nil, + }, + { + name: "AuthAccount.AccountCapabilities", + staticType: PrimitiveStaticTypeAuthAccountAccountCapabilities, + semaType: nil, + }, + { + name: "AuthAccount.Capabilities", + staticType: PrimitiveStaticTypeAuthAccountCapabilities, + semaType: nil, + }, + { + name: "PublicAccount.Capabilities", + staticType: PrimitiveStaticTypePublicAccountCapabilities, + semaType: nil, + }, + { + name: "AccountKey", + staticType: PrimitiveStaticTypeAccountKey, + semaType: nil, + }, } - for _, test := range tests { + test := func(test testCase) { t.Run(test.name, func(t *testing.T) { + t.Parallel() + // Test sema to static - convertedStaticType := ConvertSemaToStaticType(nil, test.semaType) - require.Equal(t, - test.staticType, - convertedStaticType, - ) + if test.semaType != nil { + convertedStaticType := ConvertSemaToStaticType(nil, test.semaType) + require.Equal(t, + test.staticType, + convertedStaticType, + ) + } // Test static to sema getInterface := test.getInterface if getInterface == nil { - getInterface = func(_ common.Location, _ string) (*sema.InterfaceType, error) { + getInterface = func( + _ *testing.T, + _ common.Location, + _ string, + _ TypeID, + ) (*sema.InterfaceType, error) { require.FailNow(t, "getInterface should not be called") return nil, nil } @@ -1355,7 +1631,12 @@ func TestStaticTypeConversion(t *testing.T) { getComposite := test.getComposite if getComposite == nil { - getComposite = func(_ common.Location, _ string, _ TypeID) (*sema.CompositeType, error) { + getComposite = func( + _ *testing.T, + _ common.Location, + _ string, + _ TypeID, + ) (*sema.CompositeType, error) { require.FailNow(t, "getComposite should not be called") return nil, nil } @@ -1374,8 +1655,12 @@ func TestStaticTypeConversion(t *testing.T) { convertedSemaType, err := ConvertStaticToSemaType( nil, test.staticType, - getInterface, - getComposite, + func(location common.Location, qualifiedIdentifier string, typeID TypeID) (*sema.InterfaceType, error) { + return getInterface(t, location, qualifiedIdentifier, typeID) + }, + func(location common.Location, qualifiedIdentifier string, typeID TypeID) (*sema.CompositeType, error) { + return getComposite(t, location, qualifiedIdentifier, typeID) + }, getEntitlement, getEntitlementMap, ) @@ -1386,4 +1671,21 @@ func TestStaticTypeConversion(t *testing.T) { ) }) } + + testedStaticTypes := map[StaticType]struct{}{} + + for _, testCase := range tests { + testedStaticTypes[testCase.staticType] = struct{}{} + test(testCase) + } + + for ty := PrimitiveStaticType(1); ty < PrimitiveStaticType_Count; ty++ { + if !ty.IsDefined() { + continue + } + if _, ok := testedStaticTypes[ty]; !ok { + t.Errorf("missing test case for primitive static type %s", ty) + } + } + } diff --git a/runtime/interpreter/value.go b/runtime/interpreter/value.go index 21e53a98e7..1ec1c1e545 100644 --- a/runtime/interpreter/value.go +++ b/runtime/interpreter/value.go @@ -16394,7 +16394,7 @@ func (v *CompositeValue) StaticType(interpreter *Interpreter) StaticType { interpreter, v.Location, v.QualifiedIdentifier, - v.TypeID(), // TODO TypeID metering + v.TypeID(), ) } return v.staticType @@ -16649,12 +16649,23 @@ func (v *CompositeValue) OwnerValue(interpreter *Interpreter, locationRange Loca config := interpreter.SharedState.Config - ownerAccount := config.PublicAccountHandler(AddressValue(address)) + ownerAccount := config.AccountHandler(AddressValue(address)) - // Owner must be of `PublicAccount` type. - interpreter.ExpectType(ownerAccount, sema.PublicAccountType, locationRange) + // Owner must be of `Account` type. + interpreter.ExpectType( + ownerAccount, + sema.AccountType, + locationRange, + ) + + reference := NewEphemeralReferenceValue( + interpreter, + UnauthorizedAccess, + ownerAccount, + sema.AccountType, + ) - return NewSomeValueNonCopying(interpreter, ownerAccount) + return NewSomeValueNonCopying(interpreter, reference) } func (v *CompositeValue) RemoveMember( @@ -17614,7 +17625,7 @@ func attachmentReferenceAuthorization( if err != nil { return nil, err } - return ConvertSemaAccesstoStaticAuthorization(interpreter, attachmentReferenceAccess), nil + return ConvertSemaAccessToStaticAuthorization(interpreter, attachmentReferenceAccess), nil } func attachmentBaseAuthorization( @@ -17628,7 +17639,7 @@ func attachmentBaseAuthorization( SetKind: sema.Conjunction, Entitlements: attachmentType.RequiredEntitlements, } - auth = ConvertSemaAccesstoStaticAuthorization(interpreter, baseAccess) + auth = ConvertSemaAccessToStaticAuthorization(interpreter, baseAccess) } return auth } @@ -17643,7 +17654,7 @@ func attachmentBaseAndSelfValues( var attachmentReferenceAuth Authorization = UnauthorizedAccess if attachmentType.AttachmentEntitlementAccess != nil { - attachmentReferenceAuth = ConvertSemaAccesstoStaticAuthorization(interpreter, attachmentType.AttachmentEntitlementAccess.Codomain()) + attachmentReferenceAuth = ConvertSemaAccessToStaticAuthorization(interpreter, attachmentType.AttachmentEntitlementAccess.Codomain()) } // in attachment functions, self is a reference value diff --git a/runtime/interpreter/value_account.go b/runtime/interpreter/value_account.go index 94460f9ab3..28b585e1fc 100644 --- a/runtime/interpreter/value_account.go +++ b/runtime/interpreter/value_account.go @@ -25,26 +25,26 @@ import ( "github.com/onflow/cadence/runtime/sema" ) -// AuthAccount - -var authAccountTypeID = sema.AuthAccountType.ID() -var authAccountStaticType StaticType = PrimitiveStaticTypeAuthAccount // unmetered -var authAccountFieldNames = []string{ - sema.AuthAccountTypeAddressFieldName, - sema.AuthAccountTypeContractsFieldName, - sema.AuthAccountTypeKeysFieldName, - sema.AuthAccountTypeInboxFieldName, - sema.AuthAccountTypeCapabilitiesFieldName, +// Account + +var accountTypeID = sema.AccountType.ID() +var accountStaticType StaticType = PrimitiveStaticTypeAccount // unmetered +var accountFieldNames = []string{ + sema.AccountTypeAddressFieldName, + sema.AccountTypeStorageFieldName, + sema.AccountTypeContractsFieldName, + sema.AccountTypeKeysFieldName, + sema.AccountTypeInboxFieldName, + sema.AccountTypeCapabilitiesFieldName, } -// NewAuthAccountValue constructs an auth account value. -func NewAuthAccountValue( +// NewAccountValue constructs an account value. +func NewAccountValue( gauge common.MemoryGauge, address AddressValue, accountBalanceGet func() UFix64Value, accountAvailableBalanceGet func() UFix64Value, - storageUsedGet func(interpreter *Interpreter) UInt64Value, - storageCapacityGet func(interpreter *Interpreter) UInt64Value, + storageConstructor func() Value, contractsConstructor func() Value, keysConstructor func() Value, inboxConstructor func() Value, @@ -52,243 +52,52 @@ func NewAuthAccountValue( ) Value { fields := map[string]Value{ - sema.AuthAccountTypeAddressFieldName: address, + sema.AccountTypeAddressFieldName: address, } + var storage Value var contracts Value var keys Value var inbox Value var capabilities Value - var forEachStoredFunction *HostFunctionValue - var forEachPublicFunction *HostFunctionValue - var forEachPrivateFunction *HostFunctionValue - var typeFunction *HostFunctionValue - var loadFunction *HostFunctionValue - var copyFunction *HostFunctionValue - var saveFunction *HostFunctionValue - var borrowFunction *HostFunctionValue - var checkFunction *HostFunctionValue computeField := func(name string, inter *Interpreter, locationRange LocationRange) Value { switch name { - case sema.AuthAccountTypeContractsFieldName: + case sema.AccountTypeStorageFieldName: + if storage == nil { + storage = storageConstructor() + } + return storage + + case sema.AccountTypeContractsFieldName: if contracts == nil { contracts = contractsConstructor() } return contracts - case sema.AuthAccountTypeKeysFieldName: + case sema.AccountTypeKeysFieldName: if keys == nil { keys = keysConstructor() } return keys - case sema.AuthAccountTypeInboxFieldName: + case sema.AccountTypeInboxFieldName: if inbox == nil { inbox = inboxConstructor() } return inbox - case sema.AuthAccountTypeCapabilitiesFieldName: - if capabilities == nil { - capabilities = capabilitiesConstructor() - } - return capabilities - - case sema.AuthAccountTypePublicPathsFieldName: - return inter.publicAccountPaths(address, locationRange) - - case sema.AuthAccountTypePrivatePathsFieldName: - return inter.privateAccountPaths(address, locationRange) - - case sema.AuthAccountTypeStoragePathsFieldName: - return inter.storageAccountPaths(address, locationRange) - - case sema.AuthAccountTypeForEachPublicFunctionName: - if forEachPublicFunction == nil { - forEachPublicFunction = inter.newStorageIterationFunction( - sema.AuthAccountTypeForEachPublicFunctionType, - address, - common.PathDomainPublic, - sema.PublicPathType, - ) - } - return forEachPublicFunction - - case sema.AuthAccountTypeForEachPrivateFunctionName: - if forEachPrivateFunction == nil { - forEachPrivateFunction = inter.newStorageIterationFunction( - sema.AuthAccountTypeForEachPrivateFunctionType, - address, - common.PathDomainPrivate, - sema.PrivatePathType, - ) - } - return forEachPrivateFunction - - case sema.AuthAccountTypeForEachStoredFunctionName: - if forEachStoredFunction == nil { - forEachStoredFunction = inter.newStorageIterationFunction( - sema.AuthAccountTypeForEachStoredFunctionType, - address, - common.PathDomainStorage, - sema.StoragePathType, - ) - } - return forEachStoredFunction - - case sema.AuthAccountTypeBalanceFieldName: - return accountBalanceGet() - - case sema.AuthAccountTypeAvailableBalanceFieldName: - return accountAvailableBalanceGet() - - case sema.AuthAccountTypeStorageUsedFieldName: - return storageUsedGet(inter) - - case sema.AuthAccountTypeStorageCapacityFieldName: - return storageCapacityGet(inter) - - case sema.AuthAccountTypeTypeFunctionName: - if typeFunction == nil { - typeFunction = inter.authAccountTypeFunction(address) - } - return typeFunction - - case sema.AuthAccountTypeLoadFunctionName: - if loadFunction == nil { - loadFunction = inter.authAccountLoadFunction(address) - } - return loadFunction - - case sema.AuthAccountTypeCopyFunctionName: - if copyFunction == nil { - copyFunction = inter.authAccountCopyFunction(address) - } - return copyFunction - - case sema.AuthAccountTypeSaveFunctionName: - if saveFunction == nil { - saveFunction = inter.authAccountSaveFunction(address) - } - return saveFunction - - case sema.AuthAccountTypeBorrowFunctionName: - if borrowFunction == nil { - borrowFunction = inter.authAccountBorrowFunction(address) - } - return borrowFunction - - case sema.AuthAccountTypeCheckFunctionName: - if checkFunction == nil { - checkFunction = inter.authAccountCheckFunction(address) - } - return checkFunction - } - - return nil - } - - var str string - stringer := func(memoryGauge common.MemoryGauge, seenReferences SeenReferences) string { - if str == "" { - common.UseMemory(memoryGauge, common.AuthAccountValueStringMemoryUsage) - addressStr := address.MeteredString(memoryGauge, seenReferences) - str = fmt.Sprintf("AuthAccount(%s)", addressStr) - } - return str - } - - return NewSimpleCompositeValue( - gauge, - authAccountTypeID, - authAccountStaticType, - authAccountFieldNames, - fields, - computeField, - nil, - stringer, - ) -} - -// PublicAccount - -var publicAccountTypeID = sema.PublicAccountType.ID() -var publicAccountStaticType StaticType = PrimitiveStaticTypePublicAccount // unmetered -var publicAccountFieldNames = []string{ - sema.PublicAccountTypeAddressFieldName, - sema.PublicAccountTypeContractsFieldName, - sema.PublicAccountTypeKeysFieldName, - sema.PublicAccountTypeCapabilitiesFieldName, -} - -// NewPublicAccountValue constructs a public account value. -func NewPublicAccountValue( - gauge common.MemoryGauge, - address AddressValue, - accountBalanceGet func() UFix64Value, - accountAvailableBalanceGet func() UFix64Value, - storageUsedGet func(interpreter *Interpreter) UInt64Value, - storageCapacityGet func(interpreter *Interpreter) UInt64Value, - keysConstructor func() Value, - contractsConstructor func() Value, - capabilitiesConstructor func() Value, -) Value { - - fields := map[string]Value{ - sema.PublicAccountTypeAddressFieldName: address, - } - - var keys Value - var contracts Value - var capabilities Value - var forEachPublicFunction *HostFunctionValue - - computeField := func(name string, inter *Interpreter, locationRange LocationRange) Value { - switch name { - case sema.PublicAccountTypeKeysFieldName: - if keys == nil { - keys = keysConstructor() - } - return keys - - case sema.PublicAccountTypeContractsFieldName: - if contracts == nil { - contracts = contractsConstructor() - } - return contracts - - case sema.PublicAccountTypeCapabilitiesFieldName: + case sema.AccountTypeCapabilitiesFieldName: if capabilities == nil { capabilities = capabilitiesConstructor() } return capabilities - case sema.PublicAccountTypePublicPathsFieldName: - return inter.publicAccountPaths(address, locationRange) - - case sema.PublicAccountTypeForEachPublicFunctionName: - if forEachPublicFunction == nil { - forEachPublicFunction = inter.newStorageIterationFunction( - sema.PublicAccountTypeForEachPublicFunctionType, - address, - common.PathDomainPublic, - sema.PublicPathType, - ) - } - return forEachPublicFunction - - case sema.PublicAccountTypeBalanceFieldName: + case sema.AccountTypeBalanceFieldName: return accountBalanceGet() - case sema.PublicAccountTypeAvailableBalanceFieldName: + case sema.AccountTypeAvailableBalanceFieldName: return accountAvailableBalanceGet() - - case sema.PublicAccountTypeStorageUsedFieldName: - return storageUsedGet(inter) - - case sema.PublicAccountTypeStorageCapacityFieldName: - return storageCapacityGet(inter) } return nil @@ -297,18 +106,18 @@ func NewPublicAccountValue( var str string stringer := func(memoryGauge common.MemoryGauge, seenReferences SeenReferences) string { if str == "" { - common.UseMemory(memoryGauge, common.PublicAccountValueStringMemoryUsage) + common.UseMemory(memoryGauge, common.AccountValueStringMemoryUsage) addressStr := address.MeteredString(memoryGauge, seenReferences) - str = fmt.Sprintf("PublicAccount(%s)", addressStr) + str = fmt.Sprintf("Account(%s)", addressStr) } return str } return NewSimpleCompositeValue( gauge, - publicAccountTypeID, - publicAccountStaticType, - publicAccountFieldNames, + accountTypeID, + accountStaticType, + accountFieldNames, fields, computeField, nil, diff --git a/runtime/interpreter/value_account_accountcapabilities.go b/runtime/interpreter/value_account_accountcapabilities.go index b884a55e53..068c7f73df 100644 --- a/runtime/interpreter/value_account_accountcapabilities.go +++ b/runtime/interpreter/value_account_accountcapabilities.go @@ -25,13 +25,13 @@ import ( "github.com/onflow/cadence/runtime/sema" ) -// AuthAccount.AccountCapabilities +// Account.AccountCapabilities -var authAccountAccountCapabilitiesTypeID = sema.AuthAccountAccountCapabilitiesType.ID() -var authAccountAccountCapabilitiesStaticType StaticType = PrimitiveStaticTypeAuthAccountAccountCapabilities // unmetered -var authAccountAccountCapabilitiesFieldNames []string = nil +var account_AccountCapabilitiesTypeID = sema.Account_AccountCapabilitiesType.ID() +var account_AccountCapabilitiesStaticType StaticType = PrimitiveStaticTypeAccount_AccountCapabilities // unmetered +var account_AccountCapabilitiesFieldNames []string = nil -func NewAuthAccountAccountCapabilitiesValue( +func NewAccountAccountCapabilitiesValue( gauge common.MemoryGauge, address AddressValue, getControllerFunction FunctionValue, @@ -41,27 +41,27 @@ func NewAuthAccountAccountCapabilitiesValue( ) Value { fields := map[string]Value{ - sema.AuthAccountAccountCapabilitiesTypeGetControllerFunctionName: getControllerFunction, - sema.AuthAccountAccountCapabilitiesTypeGetControllersFunctionName: getControllersFunction, - sema.AuthAccountAccountCapabilitiesTypeForEachControllerFunctionName: forEachControllerFunction, - sema.AuthAccountAccountCapabilitiesTypeIssueFunctionName: issueFunction, + sema.Account_AccountCapabilitiesTypeGetControllerFunctionName: getControllerFunction, + sema.Account_AccountCapabilitiesTypeGetControllersFunctionName: getControllersFunction, + sema.Account_AccountCapabilitiesTypeForEachControllerFunctionName: forEachControllerFunction, + sema.Account_AccountCapabilitiesTypeIssueFunctionName: issueFunction, } var str string stringer := func(memoryGauge common.MemoryGauge, seenReferences SeenReferences) string { if str == "" { - common.UseMemory(memoryGauge, common.AuthAccountAccountCapabilitiesStringMemoryUsage) + common.UseMemory(memoryGauge, common.AccountAccountCapabilitiesStringMemoryUsage) addressStr := address.MeteredString(memoryGauge, seenReferences) - str = fmt.Sprintf("AuthAccount.AccountCapabilities(%s)", addressStr) + str = fmt.Sprintf("Account.AccountCapabilities(%s)", addressStr) } return str } return NewSimpleCompositeValue( gauge, - authAccountAccountCapabilitiesTypeID, - authAccountAccountCapabilitiesStaticType, - authAccountAccountCapabilitiesFieldNames, + account_AccountCapabilitiesTypeID, + account_AccountCapabilitiesStaticType, + account_AccountCapabilitiesFieldNames, fields, nil, nil, diff --git a/runtime/interpreter/value_account_capabilities.go b/runtime/interpreter/value_account_capabilities.go index b85fa03644..977b9989e1 100644 --- a/runtime/interpreter/value_account_capabilities.go +++ b/runtime/interpreter/value_account_capabilities.go @@ -25,12 +25,12 @@ import ( "github.com/onflow/cadence/runtime/sema" ) -// AuthAccount.Capabilities +// Account.Capabilities -var authAccountCapabilitiesTypeID = sema.AuthAccountCapabilitiesType.ID() -var authAccountCapabilitiesStaticType StaticType = PrimitiveStaticTypeAuthAccountCapabilities +var account_CapabilitiesTypeID = sema.AccountCapabilitiesType.ID() +var account_CapabilitiesStaticType StaticType = PrimitiveStaticTypeAccount_Capabilities -func NewAuthAccountCapabilitiesValue( +func NewAccountCapabilitiesValue( gauge common.MemoryGauge, address AddressValue, getFunction FunctionValue, @@ -42,10 +42,10 @@ func NewAuthAccountCapabilitiesValue( ) Value { fields := map[string]Value{ - sema.AuthAccountCapabilitiesTypeGetFunctionName: getFunction, - sema.AuthAccountCapabilitiesTypeBorrowFunctionName: borrowFunction, - sema.AuthAccountCapabilitiesTypePublishFunctionName: publishFunction, - sema.AuthAccountCapabilitiesTypeUnpublishFunctionName: unpublishFunction, + sema.Account_CapabilitiesTypeGetFunctionName: getFunction, + sema.Account_CapabilitiesTypeBorrowFunctionName: borrowFunction, + sema.Account_CapabilitiesTypePublishFunctionName: publishFunction, + sema.Account_CapabilitiesTypeUnpublishFunctionName: unpublishFunction, } var storageCapabilities Value @@ -53,13 +53,13 @@ func NewAuthAccountCapabilitiesValue( computeField := func(name string, inter *Interpreter, locationRange LocationRange) Value { switch name { - case sema.AuthAccountCapabilitiesTypeStorageFieldName: + case sema.Account_CapabilitiesTypeStorageFieldName: if storageCapabilities == nil { storageCapabilities = storageCapabilitiesConstructor() } return storageCapabilities - case sema.AuthAccountCapabilitiesTypeAccountFieldName: + case sema.Account_CapabilitiesTypeAccountFieldName: if accountCapabilities == nil { accountCapabilities = accountCapabilitiesConstructor() } @@ -72,17 +72,17 @@ func NewAuthAccountCapabilitiesValue( var str string stringer := func(memoryGauge common.MemoryGauge, seenReferences SeenReferences) string { if str == "" { - common.UseMemory(memoryGauge, common.AuthAccountCapabilitiesStringMemoryUsage) + common.UseMemory(memoryGauge, common.AccountCapabilitiesStringMemoryUsage) addressStr := address.MeteredString(memoryGauge, seenReferences) - str = fmt.Sprintf("AuthAccount.Capabilities(%s)", addressStr) + str = fmt.Sprintf("Account.Capabilities(%s)", addressStr) } return str } return NewSimpleCompositeValue( gauge, - authAccountCapabilitiesTypeID, - authAccountCapabilitiesStaticType, + account_CapabilitiesTypeID, + account_CapabilitiesStaticType, nil, fields, computeField, @@ -90,42 +90,3 @@ func NewAuthAccountCapabilitiesValue( stringer, ) } - -// PublicAccount.Capabilities - -var publicAccountCapabilitiesTypeID = sema.PublicAccountCapabilitiesType.ID() -var publicAccountCapabilitiesStaticType StaticType = PrimitiveStaticTypePublicAccountCapabilities - -func NewPublicAccountCapabilitiesValue( - gauge common.MemoryGauge, - address AddressValue, - getFunction FunctionValue, - borrowFunction FunctionValue, -) Value { - - fields := map[string]Value{ - sema.PublicAccountCapabilitiesTypeGetFunctionName: getFunction, - sema.PublicAccountCapabilitiesTypeBorrowFunctionName: borrowFunction, - } - - var str string - stringer := func(memoryGauge common.MemoryGauge, seenReferences SeenReferences) string { - if str == "" { - common.UseMemory(memoryGauge, common.PublicAccountCapabilitiesStringMemoryUsage) - addressStr := address.MeteredString(memoryGauge, seenReferences) - str = fmt.Sprintf("PublicAccount.Capabilities(%s)", addressStr) - } - return str - } - - return NewSimpleCompositeValue( - gauge, - publicAccountCapabilitiesTypeID, - publicAccountCapabilitiesStaticType, - nil, - fields, - nil, - nil, - stringer, - ) -} diff --git a/runtime/interpreter/value_account_contracts.go b/runtime/interpreter/value_account_contracts.go index 47daddd3df..655b86e902 100644 --- a/runtime/interpreter/value_account_contracts.go +++ b/runtime/interpreter/value_account_contracts.go @@ -25,15 +25,15 @@ import ( "github.com/onflow/cadence/runtime/sema" ) -// AuthAccount.Contracts +// Account.Contracts -var authAccountContractsTypeID = sema.AuthAccountContractsType.ID() -var authAccountContractsStaticType StaticType = PrimitiveStaticTypeAuthAccountContracts // unmetered -var authAccountContractsFieldNames []string = nil +var account_ContractsTypeID = sema.Account_ContractsType.ID() +var account_ContractsStaticType StaticType = PrimitiveStaticTypeAccount_Contracts // unmetered +var account_ContractsFieldNames []string = nil type ContractNamesGetter func(interpreter *Interpreter, locationRange LocationRange) *ArrayValue -func NewAuthAccountContractsValue( +func NewAccountContractsValue( gauge common.MemoryGauge, address AddressValue, addFunction FunctionValue, @@ -45,11 +45,11 @@ func NewAuthAccountContractsValue( ) Value { fields := map[string]Value{ - sema.AuthAccountContractsTypeAddFunctionName: addFunction, - sema.AuthAccountContractsTypeGetFunctionName: getFunction, - sema.AuthAccountContractsTypeBorrowFunctionName: borrowFunction, - sema.AuthAccountContractsTypeRemoveFunctionName: removeFunction, - sema.AuthAccountContractsTypeUpdate__experimentalFunctionName: updateFunction, + sema.Account_ContractsTypeAddFunctionName: addFunction, + sema.Account_ContractsTypeGetFunctionName: getFunction, + sema.Account_ContractsTypeBorrowFunctionName: borrowFunction, + sema.Account_ContractsTypeRemoveFunctionName: removeFunction, + sema.Account_ContractsTypeUpdateFunctionName: updateFunction, } computeField := func( @@ -58,7 +58,7 @@ func NewAuthAccountContractsValue( locationRange LocationRange, ) Value { switch name { - case sema.AuthAccountContractsTypeNamesFieldName: + case sema.Account_ContractsTypeNamesFieldName: return namesGetter(interpreter, locationRange) } return nil @@ -67,70 +67,18 @@ func NewAuthAccountContractsValue( var str string stringer := func(memoryGauge common.MemoryGauge, seenReferences SeenReferences) string { if str == "" { - common.UseMemory(memoryGauge, common.AuthAccountContractsStringMemoryUsage) + common.UseMemory(memoryGauge, common.AccountContractsStringMemoryUsage) addressStr := address.MeteredString(memoryGauge, seenReferences) - str = fmt.Sprintf("AuthAccount.Contracts(%s)", addressStr) + str = fmt.Sprintf("Account.Contracts(%s)", addressStr) } return str } return NewSimpleCompositeValue( gauge, - authAccountContractsTypeID, - authAccountContractsStaticType, - authAccountContractsFieldNames, - fields, - computeField, - nil, - stringer, - ) -} - -// PublicAccount.Contracts - -var publicAccountContractsTypeID = sema.PublicAccountContractsType.ID() -var publicAccountContractsStaticType StaticType = PrimitiveStaticTypePublicAccountContracts - -func NewPublicAccountContractsValue( - gauge common.MemoryGauge, - address AddressValue, - getFunction FunctionValue, - borrowFunction FunctionValue, - namesGetter ContractNamesGetter, -) Value { - - fields := map[string]Value{ - sema.PublicAccountContractsTypeGetFunctionName: getFunction, - sema.PublicAccountContractsTypeBorrowFunctionName: borrowFunction, - } - - computeField := func( - name string, - interpreter *Interpreter, - locationRange LocationRange, - ) Value { - switch name { - case sema.PublicAccountContractsTypeNamesFieldName: - return namesGetter(interpreter, locationRange) - } - return nil - } - - var str string - stringer := func(memoryGauge common.MemoryGauge, seenReferences SeenReferences) string { - if str == "" { - common.UseMemory(memoryGauge, common.PublicAccountContractsStringMemoryUsage) - addressStr := address.MeteredString(memoryGauge, seenReferences) - str = fmt.Sprintf("PublicAccount.Contracts(%s)", addressStr) - } - return str - } - - return NewSimpleCompositeValue( - gauge, - publicAccountContractsTypeID, - publicAccountContractsStaticType, - nil, + account_ContractsTypeID, + account_ContractsStaticType, + account_ContractsFieldNames, fields, computeField, nil, diff --git a/runtime/interpreter/value_authaccount_inbox.go b/runtime/interpreter/value_account_inbox.go similarity index 66% rename from runtime/interpreter/value_authaccount_inbox.go rename to runtime/interpreter/value_account_inbox.go index 2e10c78e82..76f551cccc 100644 --- a/runtime/interpreter/value_authaccount_inbox.go +++ b/runtime/interpreter/value_account_inbox.go @@ -25,13 +25,13 @@ import ( "github.com/onflow/cadence/runtime/sema" ) -// AuthAccount.Inbox +// Account.Inbox -var authAccountInboxTypeID = sema.AuthAccountInboxType.ID() -var authAccountInboxStaticType StaticType = PrimitiveStaticTypeAuthAccountInbox +var account_InboxTypeID = sema.Account_InboxType.ID() +var account_InboxStaticType StaticType = PrimitiveStaticTypeAccount_Inbox -// NewAuthAccountInboxValue constructs a AuthAccount.Inbox value. -func NewAuthAccountInboxValue( +// NewAccountInboxValue constructs an Account.Inbox value. +func NewAccountInboxValue( gauge common.MemoryGauge, addressValue AddressValue, publishFunction FunctionValue, @@ -40,25 +40,25 @@ func NewAuthAccountInboxValue( ) Value { fields := map[string]Value{ - sema.AuthAccountInboxTypePublishFunctionName: publishFunction, - sema.AuthAccountInboxTypeUnpublishFunctionName: unpublishFunction, - sema.AuthAccountInboxTypeClaimFunctionName: claimFunction, + sema.Account_InboxTypePublishFunctionName: publishFunction, + sema.Account_InboxTypeUnpublishFunctionName: unpublishFunction, + sema.Account_InboxTypeClaimFunctionName: claimFunction, } var str string stringer := func(memoryGauge common.MemoryGauge, seenReferences SeenReferences) string { if str == "" { - common.UseMemory(memoryGauge, common.AuthAccountInboxStringMemoryUsage) + common.UseMemory(memoryGauge, common.AccountInboxStringMemoryUsage) addressStr := addressValue.MeteredString(memoryGauge, seenReferences) - str = fmt.Sprintf("AuthAccount.Inbox(%s)", addressStr) + str = fmt.Sprintf("Account.Inbox(%s)", addressStr) } return str } return NewSimpleCompositeValue( gauge, - authAccountInboxTypeID, - authAccountInboxStaticType, + account_InboxTypeID, + account_InboxStaticType, nil, fields, nil, diff --git a/runtime/interpreter/value_account_storage.go b/runtime/interpreter/value_account_storage.go new file mode 100644 index 0000000000..a86ec24617 --- /dev/null +++ b/runtime/interpreter/value_account_storage.go @@ -0,0 +1,146 @@ +/* + * Cadence - The resource-oriented smart contract programming language + * + * Copyright Dapper Labs, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package interpreter + +import ( + "fmt" + + "github.com/onflow/cadence/runtime/common" + "github.com/onflow/cadence/runtime/sema" +) + +// Account.Storage + +var account_StorageTypeID = sema.Account_StorageType.ID() +var account_StorageStaticType StaticType = PrimitiveStaticTypeAccount_Storage + +// NewAccountStorageValue constructs an Account.Storage value. +func NewAccountStorageValue( + gauge common.MemoryGauge, + address AddressValue, + storageUsedGet func(interpreter *Interpreter) UInt64Value, + storageCapacityGet func(interpreter *Interpreter) UInt64Value, +) Value { + + var forEachStoredFunction *HostFunctionValue + var forEachPublicFunction *HostFunctionValue + var typeFunction *HostFunctionValue + var loadFunction *HostFunctionValue + var copyFunction *HostFunctionValue + var saveFunction *HostFunctionValue + var borrowFunction *HostFunctionValue + var checkFunction *HostFunctionValue + + computeField := func(name string, inter *Interpreter, locationRange LocationRange) Value { + switch name { + case sema.Account_StorageTypePublicPathsFieldName: + return inter.publicAccountPaths(address, locationRange) + + case sema.Account_StorageTypeStoragePathsFieldName: + return inter.storageAccountPaths(address, locationRange) + + case sema.Account_StorageTypeForEachPublicFunctionName: + if forEachPublicFunction == nil { + forEachPublicFunction = inter.newStorageIterationFunction( + sema.Account_StorageTypeForEachPublicFunctionType, + address, + common.PathDomainPublic, + sema.PublicPathType, + ) + } + return forEachPublicFunction + + case sema.Account_StorageTypeForEachStoredFunctionName: + if forEachStoredFunction == nil { + forEachStoredFunction = inter.newStorageIterationFunction( + sema.Account_StorageTypeForEachStoredFunctionType, + address, + common.PathDomainStorage, + sema.StoragePathType, + ) + } + return forEachStoredFunction + + case sema.Account_StorageTypeUsedFieldName: + return storageUsedGet(inter) + + case sema.Account_StorageTypeCapacityFieldName: + return storageCapacityGet(inter) + + case sema.Account_StorageTypeTypeFunctionName: + if typeFunction == nil { + typeFunction = inter.authAccountTypeFunction(address) + } + return typeFunction + + case sema.Account_StorageTypeLoadFunctionName: + if loadFunction == nil { + loadFunction = inter.authAccountLoadFunction(address) + } + return loadFunction + + case sema.Account_StorageTypeCopyFunctionName: + if copyFunction == nil { + copyFunction = inter.authAccountCopyFunction(address) + } + return copyFunction + + case sema.Account_StorageTypeSaveFunctionName: + if saveFunction == nil { + saveFunction = inter.authAccountSaveFunction(address) + } + return saveFunction + + case sema.Account_StorageTypeBorrowFunctionName: + if borrowFunction == nil { + borrowFunction = inter.authAccountBorrowFunction(address) + } + return borrowFunction + + case sema.Account_StorageTypeCheckFunctionName: + if checkFunction == nil { + checkFunction = inter.authAccountCheckFunction(address) + } + return checkFunction + } + + return nil + } + + var str string + stringer := func(memoryGauge common.MemoryGauge, seenReferences SeenReferences) string { + if str == "" { + common.UseMemory(memoryGauge, common.AccountStorageStringMemoryUsage) + addressStr := address.MeteredString(memoryGauge, seenReferences) + str = fmt.Sprintf("Account.Storage(%s)", addressStr) + } + return str + } + + return NewSimpleCompositeValue( + gauge, + account_StorageTypeID, + account_StorageStaticType, + nil, + nil, + computeField, + nil, + stringer, + ) +} diff --git a/runtime/interpreter/value_account_storagecapabilities.go b/runtime/interpreter/value_account_storagecapabilities.go index 9f7cfc73e8..821a146506 100644 --- a/runtime/interpreter/value_account_storagecapabilities.go +++ b/runtime/interpreter/value_account_storagecapabilities.go @@ -25,13 +25,13 @@ import ( "github.com/onflow/cadence/runtime/sema" ) -// AuthAccount.StorageCapabilities +// Account.StorageCapabilities -var authAccountStorageCapabilitiesTypeID = sema.AuthAccountStorageCapabilitiesType.ID() -var authAccountStorageCapabilitiesStaticType StaticType = PrimitiveStaticTypeAuthAccountStorageCapabilities // unmetered -var authAccountStorageCapabilitiesFieldNames []string = nil +var account_StorageCapabilitiesTypeID = sema.Account_StorageCapabilitiesType.ID() +var account_StorageCapabilitiesStaticType StaticType = PrimitiveStaticTypeAccount_StorageCapabilities // unmetered +var account_StorageCapabilitiesFieldNames []string = nil -func NewAuthAccountStorageCapabilitiesValue( +func NewAccountStorageCapabilitiesValue( gauge common.MemoryGauge, address AddressValue, getControllerFunction FunctionValue, @@ -41,27 +41,27 @@ func NewAuthAccountStorageCapabilitiesValue( ) Value { fields := map[string]Value{ - sema.AuthAccountStorageCapabilitiesTypeGetControllerFunctionName: getControllerFunction, - sema.AuthAccountStorageCapabilitiesTypeGetControllersFunctionName: getControllersFunction, - sema.AuthAccountStorageCapabilitiesTypeForEachControllerFunctionName: forEachControllerFunction, - sema.AuthAccountStorageCapabilitiesTypeIssueFunctionName: issueFunction, + sema.Account_StorageCapabilitiesTypeGetControllerFunctionName: getControllerFunction, + sema.Account_StorageCapabilitiesTypeGetControllersFunctionName: getControllersFunction, + sema.Account_StorageCapabilitiesTypeForEachControllerFunctionName: forEachControllerFunction, + sema.Account_StorageCapabilitiesTypeIssueFunctionName: issueFunction, } var str string stringer := func(memoryGauge common.MemoryGauge, seenReferences SeenReferences) string { if str == "" { - common.UseMemory(memoryGauge, common.AuthAccountStorageCapabilitiesStringMemoryUsage) + common.UseMemory(memoryGauge, common.AccountStorageCapabilitiesStringMemoryUsage) addressStr := address.MeteredString(memoryGauge, seenReferences) - str = fmt.Sprintf("AuthAccount.StorageCapabilities(%s)", addressStr) + str = fmt.Sprintf("Account.StorageCapabilities(%s)", addressStr) } return str } return NewSimpleCompositeValue( gauge, - authAccountStorageCapabilitiesTypeID, - authAccountStorageCapabilitiesStaticType, - authAccountStorageCapabilitiesFieldNames, + account_StorageCapabilitiesTypeID, + account_StorageCapabilitiesStaticType, + account_StorageCapabilitiesFieldNames, fields, nil, nil, diff --git a/runtime/interpreter/value_accountcapabilitycontroller.go b/runtime/interpreter/value_accountcapabilitycontroller.go index 701a020a06..d43a78e239 100644 --- a/runtime/interpreter/value_accountcapabilitycontroller.go +++ b/runtime/interpreter/value_accountcapabilitycontroller.go @@ -275,9 +275,25 @@ func (v *AccountCapabilityControllerValue) ReferenceValue( capabilityAddress common.Address, resultBorrowType *sema.ReferenceType, ) ReferenceValue { - return NewAccountReferenceValue( + config := interpreter.SharedState.Config + + account := config.AccountHandler(AddressValue(capabilityAddress)) + + // Account must be of `Account` type. + interpreter.ExpectType( + account, + sema.AccountType, + EmptyLocationRange, + ) + + authorization := ConvertSemaAccessToStaticAuthorization( + interpreter, + resultBorrowType.Authorization, + ) + return NewEphemeralReferenceValue( interpreter, - capabilityAddress, + authorization, + account, resultBorrowType.Type, ) } diff --git a/runtime/interpreter/value_accountkey.go b/runtime/interpreter/value_accountkey.go index 9f1b37b78a..05013dbbf8 100644 --- a/runtime/interpreter/value_accountkey.go +++ b/runtime/interpreter/value_accountkey.go @@ -23,7 +23,7 @@ import ( ) var accountKeyTypeID = sema.AccountKeyType.ID() -var accountKeyStaticType StaticType = PrimitiveStaticTypeAccountKey // unmetered +var AccountKeyStaticType StaticType = ConvertSemaCompositeTypeToStaticCompositeType(nil, sema.AccountKeyType) var accountKeyFieldNames = []string{ sema.AccountKeyKeyIndexFieldName, sema.AccountKeyPublicKeyFieldName, @@ -52,7 +52,7 @@ func NewAccountKeyValue( return NewSimpleCompositeValue( inter, accountKeyTypeID, - accountKeyStaticType, + AccountKeyStaticType, accountKeyFieldNames, fields, nil, diff --git a/runtime/interpreter/value_accountreference.go b/runtime/interpreter/value_accountreference.go deleted file mode 100644 index 665cf7793f..0000000000 --- a/runtime/interpreter/value_accountreference.go +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Cadence - The resource-oriented smart contract programming language - * - * Copyright Dapper Labs, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package interpreter - -import ( - "github.com/onflow/atree" - - "github.com/onflow/cadence/runtime/common" - "github.com/onflow/cadence/runtime/format" - "github.com/onflow/cadence/runtime/sema" -) - -// TODO: maybe replace with EphemeralReferenceValue - -// AccountReferenceValue - -type AccountReferenceValue struct { - BorrowedType sema.Type - _authAccount Value - Address common.Address -} - -var _ Value = &AccountReferenceValue{} -var _ EquatableValue = &AccountReferenceValue{} -var _ ValueIndexableValue = &AccountReferenceValue{} -var _ MemberAccessibleValue = &AccountReferenceValue{} -var _ ReferenceValue = &AccountReferenceValue{} - -func NewUnmeteredAccountReferenceValue( - address common.Address, - borrowedType sema.Type, -) *AccountReferenceValue { - return &AccountReferenceValue{ - Address: address, - BorrowedType: borrowedType, - } -} - -func NewAccountReferenceValue( - memoryGauge common.MemoryGauge, - address common.Address, - borrowedType sema.Type, -) *AccountReferenceValue { - common.UseMemory(memoryGauge, common.AccountReferenceValueMemoryUsage) - return NewUnmeteredAccountReferenceValue( - address, - borrowedType, - ) -} - -func (*AccountReferenceValue) isValue() {} - -func (*AccountReferenceValue) isReference() {} - -func (v *AccountReferenceValue) Accept(interpreter *Interpreter, visitor Visitor) { - visitor.VisitAccountReferenceValue(interpreter, v) -} - -func (*AccountReferenceValue) Walk(_ *Interpreter, _ func(Value)) { - // NO-OP - // NOTE: *not* walking referenced value! -} - -func (*AccountReferenceValue) String() string { - return format.AccountReference -} - -func (v *AccountReferenceValue) RecursiveString(_ SeenReferences) string { - return v.String() -} - -func (v *AccountReferenceValue) MeteredString(memoryGauge common.MemoryGauge, _ SeenReferences) string { - common.UseMemory(memoryGauge, common.AccountReferenceValueStringMemoryUsage) - return v.String() -} - -func (v *AccountReferenceValue) StaticType(inter *Interpreter) StaticType { - return NewReferenceStaticType( - inter, - UnauthorizedAccess, - PrimitiveStaticTypeAuthAccount, - ) -} - -func (*AccountReferenceValue) IsImportable(_ *Interpreter) bool { - return false -} - -func (v *AccountReferenceValue) GetMember( - interpreter *Interpreter, - locationRange LocationRange, - name string, -) Value { - self := v.authAccount(interpreter) - return interpreter.getMember(self, locationRange, name) -} - -func (v *AccountReferenceValue) RemoveMember( - interpreter *Interpreter, - locationRange LocationRange, - name string, -) Value { - self := v.authAccount(interpreter) - return self.(MemberAccessibleValue).RemoveMember(interpreter, locationRange, name) -} - -func (v *AccountReferenceValue) SetMember( - interpreter *Interpreter, - locationRange LocationRange, - name string, - value Value, -) bool { - self := v.authAccount(interpreter) - return interpreter.setMember(self, locationRange, name, value) -} - -func (v *AccountReferenceValue) GetKey( - interpreter *Interpreter, - locationRange LocationRange, - key Value, -) Value { - self := v.authAccount(interpreter) - return self.(ValueIndexableValue). - GetKey(interpreter, locationRange, key) -} - -func (v *AccountReferenceValue) SetKey( - interpreter *Interpreter, - locationRange LocationRange, - key Value, - value Value, -) { - self := v.authAccount(interpreter) - self.(ValueIndexableValue). - SetKey(interpreter, locationRange, key, value) -} - -func (v *AccountReferenceValue) InsertKey( - interpreter *Interpreter, - locationRange LocationRange, - key Value, - value Value, -) { - self := v.authAccount(interpreter) - self.(ValueIndexableValue). - InsertKey(interpreter, locationRange, key, value) -} - -func (v *AccountReferenceValue) RemoveKey( - interpreter *Interpreter, - locationRange LocationRange, - key Value, -) Value { - self := v.authAccount(interpreter) - return self.(ValueIndexableValue). - RemoveKey(interpreter, locationRange, key) -} - -func (v *AccountReferenceValue) Equal(_ *Interpreter, _ LocationRange, other Value) bool { - otherReference, ok := other.(*AccountReferenceValue) - if !ok || - v.Address != otherReference.Address { - - return false - } - - if v.BorrowedType == nil { - return otherReference.BorrowedType == nil - } else { - return v.BorrowedType.Equal(otherReference.BorrowedType) - } -} - -func (v *AccountReferenceValue) ConformsToStaticType( - interpreter *Interpreter, - locationRange LocationRange, - results TypeConformanceResults, -) bool { - if !interpreter.IsSubTypeOfSemaType( - PrimitiveStaticTypeAuthAccount, - v.BorrowedType, - ) { - return false - } - - self := v.authAccount(interpreter) - - return self.ConformsToStaticType( - interpreter, - locationRange, - results, - ) -} - -func (*AccountReferenceValue) IsStorable() bool { - return false -} - -func (v *AccountReferenceValue) Storable(_ atree.SlabStorage, _ atree.Address, _ uint64) (atree.Storable, error) { - return NonStorable{Value: v}, nil -} - -func (*AccountReferenceValue) NeedsStoreTo(_ atree.Address) bool { - return false -} - -func (*AccountReferenceValue) IsResourceKinded(_ *Interpreter) bool { - return false -} - -func (v *AccountReferenceValue) Transfer( - interpreter *Interpreter, - _ LocationRange, - _ atree.Address, - remove bool, - storable atree.Storable, - _ map[atree.StorageID]struct{}, -) Value { - if remove { - interpreter.RemoveReferencedSlab(storable) - } - return v -} - -func (v *AccountReferenceValue) Clone(_ *Interpreter) Value { - return NewUnmeteredAccountReferenceValue( - v.Address, - v.BorrowedType, - ) -} - -func (*AccountReferenceValue) DeepRemove(_ *Interpreter) { - // NO-OP -} - -func (v *AccountReferenceValue) authAccount(interpreter *Interpreter) Value { - if v._authAccount == nil { - v._authAccount = interpreter.SharedState.Config.AuthAccountHandler(AddressValue(v.Address)) - } - return v._authAccount -} - -func (v *AccountReferenceValue) ReferencedValue(interpreter *Interpreter, _ LocationRange, _ bool) *Value { - authAccount := v.authAccount(interpreter) - return &authAccount -} diff --git a/runtime/interpreter/value_authaccount_keys.go b/runtime/interpreter/value_authaccount_keys.go index a60ab309b6..0fd6913b98 100644 --- a/runtime/interpreter/value_authaccount_keys.go +++ b/runtime/interpreter/value_authaccount_keys.go @@ -25,13 +25,13 @@ import ( "github.com/onflow/cadence/runtime/sema" ) -// AuthAccount.Keys +// Account.Keys -var authAccountKeysTypeID = sema.AuthAccountKeysType.ID() -var authAccountKeysStaticType StaticType = PrimitiveStaticTypeAuthAccountKeys +var account_KeysTypeID = sema.Account_KeysType.ID() +var account_KeysStaticType StaticType = PrimitiveStaticTypeAccount_Keys -// NewAuthAccountKeysValue constructs a AuthAccount.Keys value. -func NewAuthAccountKeysValue( +// NewAccountKeysValue constructs an Account.Keys value. +func NewAccountKeysValue( gauge common.MemoryGauge, address AddressValue, addFunction FunctionValue, @@ -42,15 +42,15 @@ func NewAuthAccountKeysValue( ) Value { fields := map[string]Value{ - sema.AuthAccountKeysTypeAddFunctionName: addFunction, - sema.AuthAccountKeysTypeGetFunctionName: getFunction, - sema.AuthAccountKeysTypeRevokeFunctionName: revokeFunction, - sema.AuthAccountKeysTypeForEachFunctionName: forEachFunction, + sema.Account_KeysTypeAddFunctionName: addFunction, + sema.Account_KeysTypeGetFunctionName: getFunction, + sema.Account_KeysTypeRevokeFunctionName: revokeFunction, + sema.Account_KeysTypeForEachFunctionName: forEachFunction, } computeField := func(name string, _ *Interpreter, _ LocationRange) Value { switch name { - case sema.AuthAccountKeysTypeCountFieldName: + case sema.Account_KeysTypeCountFieldName: return getKeysCount() } return nil @@ -59,65 +59,17 @@ func NewAuthAccountKeysValue( var str string stringer := func(memoryGauge common.MemoryGauge, seenReferences SeenReferences) string { if str == "" { - common.UseMemory(memoryGauge, common.AuthAccountKeysStringMemoryUsage) + common.UseMemory(memoryGauge, common.AccountKeysStringMemoryUsage) addressStr := address.MeteredString(memoryGauge, seenReferences) - str = fmt.Sprintf("AuthAccount.Keys(%s)", addressStr) + str = fmt.Sprintf("Account.Keys(%s)", addressStr) } return str } return NewSimpleCompositeValue( gauge, - authAccountKeysTypeID, - authAccountKeysStaticType, - nil, - fields, - computeField, - nil, - stringer, - ) -} - -// PublicAccountKeys - -var publicAccountKeysTypeID = sema.PublicAccountKeysType.ID() -var publicAccountKeysStaticType StaticType = PrimitiveStaticTypePublicAccountKeys - -// NewPublicAccountKeysValue constructs a PublicAccount.Keys value. -func NewPublicAccountKeysValue( - gauge common.MemoryGauge, - address AddressValue, - getFunction FunctionValue, - forEachFunction FunctionValue, - getKeysCount AccountKeysCountGetter, -) Value { - - fields := map[string]Value{ - sema.PublicAccountKeysTypeGetFunctionName: getFunction, - sema.PublicAccountKeysTypeForEachFunctionName: forEachFunction, - } - - computeField := func(name string, _ *Interpreter, _ LocationRange) Value { - switch name { - case sema.PublicAccountKeysTypeCountFieldName: - return getKeysCount() - } - return nil - } - var str string - stringer := func(memoryGauge common.MemoryGauge, seenReferences SeenReferences) string { - if str == "" { - common.UseMemory(memoryGauge, common.PublicAccountKeysStringMemoryUsage) - addressStr := address.MeteredString(memoryGauge, seenReferences) - str = fmt.Sprintf("PublicAccount.Keys(%s)", addressStr) - } - return str - } - - return NewSimpleCompositeValue( - gauge, - publicAccountKeysTypeID, - publicAccountKeysStaticType, + account_KeysTypeID, + account_KeysStaticType, nil, fields, computeField, diff --git a/runtime/interpreter/value_deployedcontract.go b/runtime/interpreter/value_deployedcontract.go index 6b9c8575fe..745c9fc3bf 100644 --- a/runtime/interpreter/value_deployedcontract.go +++ b/runtime/interpreter/value_deployedcontract.go @@ -80,7 +80,7 @@ func newPublicTypesFunctionValue(inter *Interpreter, addressValue AddressValue, nestedTypes := compositeType.NestedTypes pair := nestedTypes.Oldest() // all top-level type declarations in a contract must be public - // no need to filter here for public visiblity + // no need to filter here for public visibility yieldNext := func() Value { if pair == nil { return nil diff --git a/runtime/interpreter/value_storagecapabilitycontroller.go b/runtime/interpreter/value_storagecapabilitycontroller.go index fbe4d9dbb6..fc2a1082f6 100644 --- a/runtime/interpreter/value_storagecapabilitycontroller.go +++ b/runtime/interpreter/value_storagecapabilitycontroller.go @@ -307,9 +307,13 @@ func (v *StorageCapabilityControllerValue) ReferenceValue( capabilityAddress common.Address, resultBorrowType *sema.ReferenceType, ) ReferenceValue { + authorization := ConvertSemaAccessToStaticAuthorization( + interpreter, + resultBorrowType.Authorization, + ) return NewStorageReferenceValue( interpreter, - ConvertSemaAccesstoStaticAuthorization(interpreter, resultBorrowType.Authorization), + authorization, capabilityAddress, v.TargetPath, resultBorrowType.Type, diff --git a/runtime/interpreter/visitor.go b/runtime/interpreter/visitor.go index 27b68515e1..ffd125917f 100644 --- a/runtime/interpreter/visitor.go +++ b/runtime/interpreter/visitor.go @@ -53,7 +53,6 @@ type Visitor interface { VisitNilValue(interpreter *Interpreter, value NilValue) VisitSomeValue(interpreter *Interpreter, value *SomeValue) bool VisitStorageReferenceValue(interpreter *Interpreter, value *StorageReferenceValue) - VisitAccountReferenceValue(interpreter *Interpreter, value *AccountReferenceValue) VisitEphemeralReferenceValue(interpreter *Interpreter, value *EphemeralReferenceValue) VisitAddressValue(interpreter *Interpreter, value AddressValue) VisitPathValue(interpreter *Interpreter, value PathValue) @@ -101,7 +100,6 @@ type EmptyVisitor struct { NilValueVisitor func(interpreter *Interpreter, value NilValue) SomeValueVisitor func(interpreter *Interpreter, value *SomeValue) bool StorageReferenceValueVisitor func(interpreter *Interpreter, value *StorageReferenceValue) - AccountReferenceValueVisitor func(interpreter *Interpreter, value *AccountReferenceValue) EphemeralReferenceValueVisitor func(interpreter *Interpreter, value *EphemeralReferenceValue) AddressValueVisitor func(interpreter *Interpreter, value AddressValue) PathValueVisitor func(interpreter *Interpreter, value PathValue) @@ -354,13 +352,6 @@ func (v EmptyVisitor) VisitStorageReferenceValue(interpreter *Interpreter, value v.StorageReferenceValueVisitor(interpreter, value) } -func (v EmptyVisitor) VisitAccountReferenceValue(interpreter *Interpreter, value *AccountReferenceValue) { - if v.AccountReferenceValueVisitor == nil { - return - } - v.AccountReferenceValueVisitor(interpreter, value) -} - func (v EmptyVisitor) VisitEphemeralReferenceValue(interpreter *Interpreter, value *EphemeralReferenceValue) { if v.EphemeralReferenceValueVisitor == nil { return diff --git a/runtime/literal_test.go b/runtime/literal_test.go index b0f80e8d4e..6e7939c81c 100644 --- a/runtime/literal_test.go +++ b/runtime/literal_test.go @@ -31,7 +31,7 @@ import ( . "github.com/onflow/cadence/runtime/tests/utils" ) -func TestParseLiteral(t *testing.T) { +func TestRuntimeParseLiteral(t *testing.T) { t.Parallel() t.Run("String, valid literal", func(t *testing.T) { @@ -690,7 +690,7 @@ func TestParseLiteral(t *testing.T) { } } -func TestParseLiteralArgumentList(t *testing.T) { +func TestRuntimeParseLiteralArgumentList(t *testing.T) { t.Parallel() t.Run("invalid", func(t *testing.T) { diff --git a/runtime/nft_test.go b/runtime/nft_test.go index ed9edcc879..f0fd51c3d2 100644 --- a/runtime/nft_test.go +++ b/runtime/nft_test.go @@ -894,14 +894,14 @@ access(all) contract TopShot: NonFungibleToken { self.totalSupply = 0 // Put a new Collection in storage - self.account.save<@Collection>(<- create Collection(), to: /storage/MomentCollection) + self.account.storage.save<@Collection>(<- create Collection(), to: /storage/MomentCollection) // create a public capability for the collection let cap = self.account.capabilities.storage.issue<&{MomentCollectionPublic}>(/storage/MomentCollection) self.account.capabilities.publish(cap, at: /public/MomentCollection) // Put the Minter in storage - self.account.save<@Admin>(<- create Admin(), to: /storage/TopShotAdmin) + self.account.storage.save<@Admin>(<- create Admin(), to: /storage/TopShotAdmin) emit ContractInitialized() } @@ -917,8 +917,8 @@ access(all) contract TopShotShardedCollection { // ShardedCollection stores a dictionary of TopShot Collections // A Moment is stored in the field that corresponds to its id % numBuckets - access(all) resource ShardedCollection: TopShot.MomentCollectionPublic, NonFungibleToken.Provider, NonFungibleToken.Receiver, NonFungibleToken.CollectionPublic { - + access(all) resource ShardedCollection: TopShot.MomentCollectionPublic, NonFungibleToken.Provider, NonFungibleToken.Receiver, NonFungibleToken.CollectionPublic { + // Dictionary of topshot collections access(all) var collections: @{UInt64: TopShot.Collection} @@ -940,7 +940,7 @@ access(all) contract TopShotShardedCollection { } } - // withdraw removes a Moment from one of the Collections + // withdraw removes a Moment from one of the Collections // and moves it to the caller access(all) fun withdraw(withdrawID: UInt64): @{NonFungibleToken.NFT} { post { @@ -951,7 +951,7 @@ access(all) contract TopShotShardedCollection { // Withdraw the moment let token <- self.collections[bucket]?.withdraw(withdrawID: withdrawID)! - + return <-token } @@ -963,7 +963,7 @@ access(all) contract TopShotShardedCollection { // that were withdrawn access(all) fun batchWithdraw(ids: [UInt64]): @{NonFungibleToken.Collection} { var batchCollection <- TopShot.createEmptyCollection() - + // Iterate through the ids and withdraw them from the Collection for id in ids { batchCollection.deposit(token: <-self.withdraw(withdrawID: id)) @@ -1064,19 +1064,19 @@ import TopShotShardedCollection from 0x0b2a3299cc857e29 access(all) contract TopshotAdminReceiver { - // storeAdmin takes a TopShot Admin resource and + // storeAdmin takes a TopShot Admin resource and // saves it to the account storage of the account // where the contract is deployed access(all) fun storeAdmin(newAdmin: @TopShot.Admin) { - self.account.save(<-newAdmin, to: /storage/TopShotAdmin) + self.account.storage.save(<-newAdmin, to: /storage/TopShotAdmin) } - + init() { // Save a copy of the sharded Moment Collection to the account storage - if self.account.borrow<&TopShotShardedCollection.ShardedCollection>(from: /storage/ShardedMomentCollection) == nil { + if self.account.storage.borrow<&TopShotShardedCollection.ShardedCollection>(from: /storage/ShardedMomentCollection) == nil { let collection <- TopShotShardedCollection.createEmptyCollection(numBuckets: 32) // Put a new Collection in storage - self.account.save(<-collection, to: /storage/ShardedMomentCollection) + self.account.storage.save(<-collection, to: /storage/ShardedMomentCollection) let cap = self.account.capabilities.storage.issue<&{TopShot.MomentCollectionPublic}>(/storage/ShardedMomentCollection) self.account.capabilities.publish(cap, at: /public/ShardedMomentCollection) diff --git a/runtime/parser/declaration_test.go b/runtime/parser/declaration_test.go index ac4921ff64..81aaed3223 100644 --- a/runtime/parser/declaration_test.go +++ b/runtime/parser/declaration_test.go @@ -5010,7 +5010,7 @@ func TestParseTransactionDeclaration(t *testing.T) { var x: Int - prepare(signer: AuthAccount) { + prepare(signer: &Account) { x = 0 } @@ -5067,11 +5067,18 @@ func TestParseTransactionDeclaration(t *testing.T) { }, TypeAnnotation: &ast.TypeAnnotation{ IsResource: false, - Type: &ast.NominalType{ - Identifier: ast.Identifier{ - Identifier: "AuthAccount", - Pos: ast.Position{Offset: 60, Line: 6, Column: 22}, + Type: &ast.ReferenceType{ + Type: &ast.NominalType{ + Identifier: ast.Identifier{ + Identifier: "Account", + Pos: ast.Position{ + Offset: 61, + Line: 6, + Column: 23, + }, + }, }, + StartPos: ast.Position{Offset: 60, Line: 6, Column: 22}, }, StartPos: ast.Position{Offset: 60, Line: 6, Column: 22}, }, @@ -5080,7 +5087,7 @@ func TestParseTransactionDeclaration(t *testing.T) { }, Range: ast.Range{ StartPos: ast.Position{Offset: 51, Line: 6, Column: 13}, - EndPos: ast.Position{Offset: 71, Line: 6, Column: 33}, + EndPos: ast.Position{Offset: 68, Line: 6, Column: 30}, }, }, ReturnTypeAnnotation: nil, @@ -5091,27 +5098,27 @@ func TestParseTransactionDeclaration(t *testing.T) { Target: &ast.IdentifierExpression{ Identifier: ast.Identifier{ Identifier: "x", - Pos: ast.Position{Offset: 86, Line: 7, Column: 11}, + Pos: ast.Position{Offset: 83, Line: 7, Column: 11}, }, }, Transfer: &ast.Transfer{ Operation: ast.TransferOperationCopy, - Pos: ast.Position{Offset: 88, Line: 7, Column: 13}, + Pos: ast.Position{Offset: 85, Line: 7, Column: 13}, }, Value: &ast.IntegerExpression{ PositiveLiteral: []byte("0"), Value: new(big.Int), Base: 10, Range: ast.Range{ - StartPos: ast.Position{Offset: 90, Line: 7, Column: 15}, - EndPos: ast.Position{Offset: 90, Line: 7, Column: 15}, + StartPos: ast.Position{Offset: 87, Line: 7, Column: 15}, + EndPos: ast.Position{Offset: 87, Line: 7, Column: 15}, }, }, }, }, Range: ast.Range{ - StartPos: ast.Position{Offset: 73, Line: 6, Column: 35}, - EndPos: ast.Position{Offset: 95, Line: 8, Column: 3}, + StartPos: ast.Position{Offset: 70, Line: 6, Column: 32}, + EndPos: ast.Position{Offset: 92, Line: 8, Column: 3}, }, }, PreConditions: nil, @@ -5128,7 +5135,7 @@ func TestParseTransactionDeclaration(t *testing.T) { Access: ast.AccessNotSpecified, Identifier: ast.Identifier{ Identifier: "execute", - Pos: ast.Position{Offset: 104, Line: 10, Column: 6}, + Pos: ast.Position{Offset: 101, Line: 10, Column: 6}, }, ReturnTypeAnnotation: nil, FunctionBlock: &ast.FunctionBlock{ @@ -5138,12 +5145,12 @@ func TestParseTransactionDeclaration(t *testing.T) { Target: &ast.IdentifierExpression{ Identifier: ast.Identifier{ Identifier: "x", - Pos: ast.Position{Offset: 125, Line: 11, Column: 11}, + Pos: ast.Position{Offset: 122, Line: 11, Column: 11}, }, }, Transfer: &ast.Transfer{ Operation: ast.TransferOperationCopy, - Pos: ast.Position{Offset: 127, Line: 11, Column: 13}, + Pos: ast.Position{Offset: 124, Line: 11, Column: 13}, }, Value: &ast.BinaryExpression{ Operation: ast.OperationPlus, @@ -5152,8 +5159,8 @@ func TestParseTransactionDeclaration(t *testing.T) { Value: big.NewInt(1), Base: 10, Range: ast.Range{ - StartPos: ast.Position{Offset: 129, Line: 11, Column: 15}, - EndPos: ast.Position{Offset: 129, Line: 11, Column: 15}, + StartPos: ast.Position{Offset: 126, Line: 11, Column: 15}, + EndPos: ast.Position{Offset: 126, Line: 11, Column: 15}, }, }, Right: &ast.IntegerExpression{ @@ -5161,27 +5168,27 @@ func TestParseTransactionDeclaration(t *testing.T) { Value: big.NewInt(1), Base: 10, Range: ast.Range{ - StartPos: ast.Position{Offset: 133, Line: 11, Column: 19}, - EndPos: ast.Position{Offset: 133, Line: 11, Column: 19}, + StartPos: ast.Position{Offset: 130, Line: 11, Column: 19}, + EndPos: ast.Position{Offset: 130, Line: 11, Column: 19}, }, }, }, }, }, Range: ast.Range{ - StartPos: ast.Position{Offset: 112, Line: 10, Column: 14}, - EndPos: ast.Position{Offset: 138, Line: 12, Column: 3}, + StartPos: ast.Position{Offset: 109, Line: 10, Column: 14}, + EndPos: ast.Position{Offset: 135, Line: 12, Column: 3}, }, }, PreConditions: nil, PostConditions: nil, }, - StartPos: ast.Position{Offset: 104, Line: 10, Column: 6}, + StartPos: ast.Position{Offset: 101, Line: 10, Column: 6}, }, }, Range: ast.Range{ StartPos: ast.Position{Offset: 5, Line: 2, Column: 4}, - EndPos: ast.Position{Offset: 144, Line: 13, Column: 4}, + EndPos: ast.Position{Offset: 141, Line: 13, Column: 4}, }, }, }, diff --git a/runtime/program_params_validation_test.go b/runtime/program_params_validation_test.go index 39662283c5..e313da2687 100644 --- a/runtime/program_params_validation_test.go +++ b/runtime/program_params_validation_test.go @@ -29,6 +29,7 @@ import ( "github.com/onflow/cadence/encoding/json" "github.com/onflow/cadence/runtime/common" "github.com/onflow/cadence/runtime/sema" + "github.com/onflow/cadence/runtime/tests/checker" . "github.com/onflow/cadence/runtime/tests/utils" ) @@ -68,7 +69,7 @@ func TestRuntimeScriptParameterTypeValidation(t *testing.T) { newPublicAccountKeys := func() cadence.Struct { return cadence.Struct{ StructType: &cadence.StructType{ - QualifiedIdentifier: "PublicAccount.Keys", + QualifiedIdentifier: "Account.Keys", Fields: []cadence.Field{}, }, Fields: []cadence.Value{}, @@ -113,11 +114,11 @@ func TestRuntimeScriptParameterTypeValidation(t *testing.T) { t.Parallel() script := ` - access(all) fun main(arg: Foo) { - } + access(all) + fun main(arg: Foo) {} - access(all) struct Foo { - } + access(all) + struct Foo {} ` err := executeScript(t, script, newFooStruct()) @@ -128,16 +129,18 @@ func TestRuntimeScriptParameterTypeValidation(t *testing.T) { t.Parallel() script := ` - access(all) fun main(arg: Foo?) { - } - - access(all) struct Foo { - access(all) var funcTypedField: fun(): Void - - init() { - self.funcTypedField = fun() {} - } - } + access(all) + fun main(arg: Foo?) {} + + access(all) + struct Foo { + access(all) + var funcTypedField: fun(): Void + + init() { + self.funcTypedField = fun() {} + } + } ` err := executeScript(t, script, cadence.NewOptional(nil)) @@ -148,8 +151,8 @@ func TestRuntimeScriptParameterTypeValidation(t *testing.T) { t.Parallel() script := ` - access(all) fun main(arg: AnyStruct?) { - } + access(all) + fun main(arg: AnyStruct?) {} ` err := executeScript(t, script, cadence.NewOptional(nil)) @@ -160,14 +163,14 @@ func TestRuntimeScriptParameterTypeValidation(t *testing.T) { t.Parallel() script := ` - access(all) fun main(arg: {Bar}) { - } + access(all) + fun main(arg: {Bar}) {} - access(all) struct Foo: Bar { - } + access(all) + struct Foo: Bar {} - access(all) struct interface Bar { - } + access(all) + struct interface Bar {} ` err := executeScript(t, script, newFooStruct()) @@ -178,12 +181,15 @@ func TestRuntimeScriptParameterTypeValidation(t *testing.T) { t.Parallel() script := ` - access(all) fun main(arg: {Bar}?) { - } + access(all) + fun main(arg: {Bar}?) {} + + access(all) + struct interface Bar { - access(all) struct interface Bar { - access(all) var funcTypedField: fun():Void - } + access(all) + var funcTypedField: fun(): Void + } ` err := executeScript(t, script, cadence.NewOptional(nil)) @@ -194,12 +200,13 @@ func TestRuntimeScriptParameterTypeValidation(t *testing.T) { t.Parallel() script := ` - access(all) fun main(arg: @Baz?) { - destroy arg - } + access(all) + fun main(arg: @Baz?) { + destroy arg + } - access(all) resource Baz { - } + access(all) + resource Baz {} ` err := executeScript(t, script, cadence.NewOptional(nil)) @@ -210,9 +217,10 @@ func TestRuntimeScriptParameterTypeValidation(t *testing.T) { t.Parallel() script := ` - access(all) fun main(arg: @AnyResource?) { - destroy arg - } + access(all) + fun main(arg: @AnyResource?) { + destroy arg + } ` err := executeScript(t, script, cadence.NewOptional(nil)) @@ -223,11 +231,11 @@ func TestRuntimeScriptParameterTypeValidation(t *testing.T) { t.Parallel() script := ` - access(all) fun main(arg: Foo?) { - } + access(all) + fun main(arg: Foo?) {} - access(all) contract Foo { - } + access(all) + contract Foo {} ` err := executeScript(t, script, cadence.NewOptional(nil)) @@ -238,8 +246,8 @@ func TestRuntimeScriptParameterTypeValidation(t *testing.T) { t.Parallel() script := ` - access(all) fun main(arg: [String]) { - } + access(all) + fun main(arg: [String]) {} ` err := executeScript( @@ -255,8 +263,8 @@ func TestRuntimeScriptParameterTypeValidation(t *testing.T) { t.Parallel() script := ` - access(all) fun main(arg: [fun():Void]) { - } + access(all) + fun main(arg: [fun(): Void]) {} ` err := executeScript( @@ -272,8 +280,8 @@ func TestRuntimeScriptParameterTypeValidation(t *testing.T) { t.Parallel() script := ` - access(all) fun main(arg: {String: Bool}) { - } + access(all) + fun main(arg: {String: Bool}) {} ` err := executeScript( @@ -289,8 +297,8 @@ func TestRuntimeScriptParameterTypeValidation(t *testing.T) { t.Parallel() script := ` - access(all) fun main(arg: Capability<&Int>?) { - } + access(all) + fun main(arg: Capability<&Int>?) {} ` err := executeScript(t, script, cadence.NewOptional(nil)) @@ -301,8 +309,8 @@ func TestRuntimeScriptParameterTypeValidation(t *testing.T) { t.Parallel() script := ` - access(all) fun main(arg: {String: fun():Void}) { - } + access(all) + fun main(arg: {String: fun(): Void}) {} ` err := executeScript( @@ -323,9 +331,10 @@ func TestRuntimeScriptParameterTypeValidation(t *testing.T) { t.Run(typString, func(t *testing.T) { t.Parallel() - script := fmt.Sprintf(` - access(all) fun main(arg: %s?) { - } + script := fmt.Sprintf( + ` + access(all) + fun main(arg: %s?) {} `, typString, ) @@ -430,15 +439,20 @@ func TestRuntimeScriptParameterTypeValidation(t *testing.T) { t.Parallel() script := ` - access(all) fun main(arg: AnyStruct?) { - } - access(all) struct Foo { - access(all) var nonImportableField: PublicAccount.Keys? - init() { - self.nonImportableField = nil - } - } - ` + access(all) + fun main(arg: AnyStruct?) {} + + access(all) + struct Foo { + + access(all) + var nonImportableField: Account.Keys? + + init() { + self.nonImportableField = nil + } + } + ` err := executeScript(t, script, newFooStruct()) expectRuntimeError(t, err, &ArgumentNotImportableError{}) @@ -448,17 +462,22 @@ func TestRuntimeScriptParameterTypeValidation(t *testing.T) { t.Parallel() script := ` - access(all) fun main(arg: {Bar}?) { - } - access(all) struct Foo: Bar { - access(all) var nonImportableField: PublicAccount.Keys? - init() { - self.nonImportableField = nil - } - } - access(all) struct interface Bar { - } - ` + access(all) + fun main(arg: {Bar}?) {} + + access(all) + struct Foo: Bar { + access(all) + var nonImportableField: Account.Keys? + + init() { + self.nonImportableField = nil + } + } + + access(all) + struct interface Bar {} + ` err := executeScript(t, script, newFooStruct()) expectRuntimeError(t, err, &ArgumentNotImportableError{}) @@ -475,16 +494,16 @@ func TestRuntimeScriptParameterTypeValidation(t *testing.T) { err := executeScript(t, script, newPublicAccountKeys()) RequireError(t, err) - assert.Contains(t, err.Error(), "cannot import value of type PublicAccount.Keys") + assert.Contains(t, err.Error(), "cannot import value of type Account.Keys") }) t.Run("Invalid struct in array", func(t *testing.T) { t.Parallel() script := ` - access(all) fun main(arg: [AnyStruct]) { - } - ` + access(all) + fun main(arg: [AnyStruct]) {} + ` err := executeScript( t, @@ -495,14 +514,17 @@ func TestRuntimeScriptParameterTypeValidation(t *testing.T) { ) RequireError(t, err) - assert.Contains(t, err.Error(), "cannot import value of type PublicAccount.Keys") + assert.Contains(t, err.Error(), "cannot import value of type Account.Keys") }) t.Run("invalid HashAlgorithm", func(t *testing.T) { t.Parallel() err := executeScript(t, - `access(all) fun main(arg: HashAlgorithm) {}`, + ` + access(all) + fun main(arg: HashAlgorithm) {} + `, cadence.NewEnum( []cadence.Value{ cadence.NewUInt8(0), @@ -519,7 +541,10 @@ func TestRuntimeScriptParameterTypeValidation(t *testing.T) { t.Parallel() err := executeScript(t, - `access(all) fun main(arg: SignatureAlgorithm) {}`, + ` + access(all) + fun main(arg: SignatureAlgorithm) {} + `, cadence.NewEnum( []cadence.Value{ cadence.NewUInt8(0), @@ -537,24 +562,6 @@ func TestRuntimeTransactionParameterTypeValidation(t *testing.T) { t.Parallel() - RequireCheckerErrors := func(t *testing.T, err error, expectedErrors ...error) { - RequireError(t, err) - - require.IsType(t, Error{}, err) - runtimeErr := err.(Error) - - require.IsType(t, &ParsingCheckingError{}, runtimeErr.Err) - parsingCheckingErr := runtimeErr.Err.(*ParsingCheckingError) - - require.IsType(t, &sema.CheckerError{}, parsingCheckingErr.Err) - checkerErr := parsingCheckingErr.Err.(*sema.CheckerError) - - require.Len(t, checkerErr.Errors, len(expectedErrors)) - for i, err := range expectedErrors { - assert.IsType(t, err, checkerErr.Errors[i]) - } - } - expectRuntimeError := func(t *testing.T, err error, expectedError error) { RequireError(t, err) @@ -581,7 +588,7 @@ func TestRuntimeTransactionParameterTypeValidation(t *testing.T) { newPublicAccountKeys := func() cadence.Struct { return cadence.Struct{ StructType: &cadence.StructType{ - QualifiedIdentifier: "PublicAccount.Keys", + QualifiedIdentifier: "Account.Keys", Fields: []cadence.Field{}, }, Fields: []cadence.Value{}, @@ -680,11 +687,10 @@ func TestRuntimeTransactionParameterTypeValidation(t *testing.T) { ` err := executeTransaction(t, script, contracts, cadence.NewOptional(nil)) - RequireCheckerErrors( - t, - err, - &sema.InvalidNonImportableTransactionParameterTypeError{}, - ) + + errs := checker.RequireCheckerErrors(t, err, 1) + + require.IsType(t, &sema.InvalidNonImportableTransactionParameterTypeError{}, errs[0]) }) t.Run("AnyStruct", func(t *testing.T) { @@ -747,11 +753,9 @@ func TestRuntimeTransactionParameterTypeValidation(t *testing.T) { err := executeTransaction(t, script, contracts, cadence.NewOptional(nil)) - RequireCheckerErrors( - t, - err, - &sema.InvalidNonImportableTransactionParameterTypeError{}, - ) + errs := checker.RequireCheckerErrors(t, err, 1) + + require.IsType(t, &sema.InvalidNonImportableTransactionParameterTypeError{}, errs[0]) }) t.Run("Resource", func(t *testing.T) { @@ -776,12 +780,10 @@ func TestRuntimeTransactionParameterTypeValidation(t *testing.T) { err := executeTransaction(t, script, contracts, cadence.NewOptional(nil)) - RequireCheckerErrors( - t, - err, - &sema.InvalidNonImportableTransactionParameterTypeError{}, - &sema.ResourceLossError{}, - ) + errs := checker.RequireCheckerErrors(t, err, 2) + + require.IsType(t, &sema.InvalidNonImportableTransactionParameterTypeError{}, errs[0]) + require.IsType(t, &sema.ResourceLossError{}, errs[1]) }) t.Run("AnyResource", func(t *testing.T) { @@ -793,12 +795,10 @@ func TestRuntimeTransactionParameterTypeValidation(t *testing.T) { err := executeTransaction(t, script, nil, cadence.NewOptional(nil)) - RequireCheckerErrors( - t, - err, - &sema.InvalidNonImportableTransactionParameterTypeError{}, - &sema.ResourceLossError{}, - ) + errs := checker.RequireCheckerErrors(t, err, 2) + + require.IsType(t, &sema.InvalidNonImportableTransactionParameterTypeError{}, errs[0]) + require.IsType(t, &sema.ResourceLossError{}, errs[1]) }) t.Run("Contract", func(t *testing.T) { @@ -820,11 +820,9 @@ func TestRuntimeTransactionParameterTypeValidation(t *testing.T) { err := executeTransaction(t, script, contracts, cadence.NewOptional(nil)) - RequireCheckerErrors( - t, - err, - &sema.InvalidNonImportableTransactionParameterTypeError{}, - ) + errs := checker.RequireCheckerErrors(t, err, 1) + + require.IsType(t, &sema.InvalidNonImportableTransactionParameterTypeError{}, errs[0]) }) t.Run("Array", func(t *testing.T) { @@ -847,11 +845,9 @@ func TestRuntimeTransactionParameterTypeValidation(t *testing.T) { err := executeTransaction(t, script, nil, cadence.NewArray([]cadence.Value{})) - RequireCheckerErrors( - t, - err, - &sema.InvalidNonImportableTransactionParameterTypeError{}, - ) + errs := checker.RequireCheckerErrors(t, err, 1) + + require.IsType(t, &sema.InvalidNonImportableTransactionParameterTypeError{}, errs[0]) }) t.Run("Dictionary", func(t *testing.T) { @@ -885,11 +881,9 @@ func TestRuntimeTransactionParameterTypeValidation(t *testing.T) { err := executeTransaction(t, script, nil, cadence.NewArray([]cadence.Value{})) - RequireCheckerErrors( - t, - err, - &sema.InvalidNonImportableTransactionParameterTypeError{}, - ) + errs := checker.RequireCheckerErrors(t, err, 1) + + require.IsType(t, &sema.InvalidNonImportableTransactionParameterTypeError{}, errs[0]) }) t.Run("Numeric Types", func(t *testing.T) { @@ -992,11 +986,10 @@ func TestRuntimeTransactionParameterTypeValidation(t *testing.T) { err := executeTransaction(t, script, nil, test.argument) if test.expectErrors { - RequireCheckerErrors( - t, - err, - &sema.InvalidNonImportableTransactionParameterTypeError{}, - ) + + errs := checker.RequireCheckerErrors(t, err, 1) + + require.IsType(t, &sema.InvalidNonImportableTransactionParameterTypeError{}, errs[0]) } else { assert.NoError(t, err) } @@ -1018,7 +1011,7 @@ func TestRuntimeTransactionParameterTypeValidation(t *testing.T) { }: []byte(` access(all) contract C { access(all) struct Foo { - access(all) var nonImportableField: PublicAccount.Keys? + access(all) var nonImportableField: &Account.Keys? init() { self.nonImportableField = nil @@ -1048,7 +1041,7 @@ func TestRuntimeTransactionParameterTypeValidation(t *testing.T) { }: []byte(` access(all) contract C { access(all) struct Foo: Bar { - access(all) var nonImportableField: PublicAccount.Keys? + access(all) var nonImportableField: &Account.Keys? init() { self.nonImportableField = nil } @@ -1079,7 +1072,7 @@ func TestRuntimeTransactionParameterTypeValidation(t *testing.T) { err := executeTransaction(t, script, nil, newPublicAccountKeys()) RequireError(t, err) - assert.Contains(t, err.Error(), "cannot import value of type PublicAccount.Keys") + assert.Contains(t, err.Error(), "cannot import value of type Account.Keys") }) t.Run("Invalid native struct in array", func(t *testing.T) { @@ -1098,7 +1091,7 @@ func TestRuntimeTransactionParameterTypeValidation(t *testing.T) { ) RequireError(t, err) - assert.Contains(t, err.Error(), "cannot import value of type PublicAccount.Keys") + assert.Contains(t, err.Error(), "cannot import value of type Account.Keys") }) t.Run("invalid HashAlgorithm", func(t *testing.T) { diff --git a/runtime/resource_duplicate_test.go b/runtime/resource_duplicate_test.go index 828c472273..0e36f4ac44 100644 --- a/runtime/resource_duplicate_test.go +++ b/runtime/resource_duplicate_test.go @@ -43,81 +43,82 @@ func TestRuntimeResourceDuplicationUsingDestructorIteration(t *testing.T) { t.Parallel() script := ` - // This Vault class is from Flow docs, used as our "victim" in this example - access(all) resource Vault { - // Balance of a user's Vault - // we use unsigned fixed point numbers for balances - // because they can represent decimals and do not allow negative values - access(all) var balance: UFix64 - - init(balance: UFix64) { - self.balance = balance - } - - access(all) fun withdraw(amount: UFix64): @Vault { - self.balance = self.balance - amount - return <-create Vault(balance: amount) - } - - access(all) fun deposit(from: @Vault) { - self.balance = self.balance + from.balance - destroy from - } - } - - // --- this code actually makes use of the vuln --- - access(all) resource DummyResource { - access(all) var dictRef: auth(Mutate) &{Bool: AnyResource}; - access(all) var arrRef: auth(Mutate) &[Vault]; - access(all) var victim: @Vault; - init(dictRef: auth(Mutate) &{Bool: AnyResource}, arrRef: auth(Mutate) &[Vault], victim: @Vault) { - self.dictRef = dictRef; - self.arrRef = arrRef; - self.victim <- victim; - } - - destroy() { - self.arrRef.append(<- self.victim) - self.dictRef[false] <-> self.dictRef[true]; // This screws up the destruction order - } - } - - access(all) fun duplicateResource(victim1: @Vault, victim2: @Vault): @[Vault]{ - let arr : @[Vault] <- []; - let dict: @{Bool: DummyResource} <- { } - let ref = &dict as auth(Mutate) &{Bool: AnyResource}; - let arrRef = &arr as auth(Mutate) &[Vault]; - - var v1: @DummyResource? <- create DummyResource(dictRef: ref, arrRef: arrRef, victim: <- victim1); - dict[false] <-> v1; - destroy v1; - - var v2: @DummyResource? <- create DummyResource(dictRef: ref, arrRef: arrRef, victim: <- victim2); - dict[true] <-> v2; - destroy v2; - - destroy dict // Trigger the destruction chain where dict[false] will be destructed twice - return <- arr; - } - - // --- end of vuln code --- - - access(all) fun main() { - - var v1 <- create Vault(balance: 1000.0); // This will be duplicated - var v2 <- create Vault(balance: 1.0); // This will be lost - var v3 <- create Vault(balance: 0.0); // We'll collect the spoils here - - // The call will return an array of [v1, v1] - var res <- duplicateResource(victim1: <- v1, victim2: <-v2) - - v3.deposit(from: <- res.removeLast()); - v3.deposit(from: <- res.removeLast()); - destroy res; - - log(v3.balance); - destroy v3; - }` + // This Vault class is from Flow docs, used as our "victim" in this example + access(all) resource Vault { + // Balance of a user's Vault + // we use unsigned fixed point numbers for balances + // because they can represent decimals and do not allow negative values + access(all) var balance: UFix64 + + init(balance: UFix64) { + self.balance = balance + } + + access(all) fun withdraw(amount: UFix64): @Vault { + self.balance = self.balance - amount + return <-create Vault(balance: amount) + } + + access(all) fun deposit(from: @Vault) { + self.balance = self.balance + from.balance + destroy from + } + } + + // --- this code actually makes use of the vuln --- + access(all) resource DummyResource { + access(all) var dictRef: auth(Mutate) &{Bool: AnyResource}; + access(all) var arrRef: auth(Mutate) &[Vault]; + access(all) var victim: @Vault; + init(dictRef: auth(Mutate) &{Bool: AnyResource}, arrRef: auth(Mutate) &[Vault], victim: @Vault) { + self.dictRef = dictRef; + self.arrRef = arrRef; + self.victim <- victim; + } + + destroy() { + self.arrRef.append(<- self.victim) + self.dictRef[false] <-> self.dictRef[true]; // This screws up the destruction order + } + } + + access(all) fun duplicateResource(victim1: @Vault, victim2: @Vault): @[Vault]{ + let arr : @[Vault] <- []; + let dict: @{Bool: DummyResource} <- { } + let ref = &dict as auth(Mutate) &{Bool: AnyResource}; + let arrRef = &arr as auth(Mutate) &[Vault]; + + var v1: @DummyResource? <- create DummyResource(dictRef: ref, arrRef: arrRef, victim: <- victim1); + dict[false] <-> v1; + destroy v1; + + var v2: @DummyResource? <- create DummyResource(dictRef: ref, arrRef: arrRef, victim: <- victim2); + dict[true] <-> v2; + destroy v2; + + destroy dict // Trigger the destruction chain where dict[false] will be destructed twice + return <- arr; + } + + // --- end of vuln code --- + + access(all) fun main() { + + var v1 <- create Vault(balance: 1000.0); // This will be duplicated + var v2 <- create Vault(balance: 1.0); // This will be lost + var v3 <- create Vault(balance: 0.0); // We'll collect the spoils here + + // The call will return an array of [v1, v1] + var res <- duplicateResource(victim1: <- v1, victim2: <-v2) + + v3.deposit(from: <- res.removeLast()); + v3.deposit(from: <- res.removeLast()); + destroy res; + + log(v3.balance); + destroy v3; + } + ` runtime := newTestInterpreterRuntime() @@ -181,48 +182,49 @@ func TestRuntimeResourceDuplicationUsingDestructorIteration(t *testing.T) { t.Parallel() script := ` - access(all) resource Vault { - access(all) var balance: UFix64 - access(all) var dictRef: auth(Mutate) &{Bool: Vault}; - - init(balance: UFix64, _ dictRef: auth(Mutate) &{Bool: Vault}) { - self.balance = balance - self.dictRef = dictRef; - } - - access(all) fun withdraw(amount: UFix64): @Vault { - self.balance = self.balance - amount - return <-create Vault(balance: amount, self.dictRef) - } - - access(all) fun deposit(from: @Vault) { - self.balance = self.balance + from.balance - destroy from - } - - destroy() { - self.dictRef[false] <-> self.dictRef[true]; // This screws up the destruction order - } - } + access(all) resource Vault { + access(all) var balance: UFix64 + access(all) var dictRef: auth(Mutate) &{Bool: Vault}; + + init(balance: UFix64, _ dictRef: auth(Mutate) &{Bool: Vault}) { + self.balance = balance + self.dictRef = dictRef; + } + + access(all) fun withdraw(amount: UFix64): @Vault { + self.balance = self.balance - amount + return <-create Vault(balance: amount, self.dictRef) + } + + access(all) fun deposit(from: @Vault) { + self.balance = self.balance + from.balance + destroy from + } + + destroy() { + self.dictRef[false] <-> self.dictRef[true]; // This screws up the destruction order + } + } - access(all) fun main(): UFix64 { + access(all) fun main(): UFix64 { - let dict: @{Bool: Vault} <- { } - let dictRef = &dict as auth(Mutate) &{Bool: Vault}; + let dict: @{Bool: Vault} <- { } + let dictRef = &dict as auth(Mutate) &{Bool: Vault}; - var v1 <- create Vault(balance: 1000.0, dictRef); // This will be duplicated - var v2 <- create Vault(balance: 1.0, dictRef); // This will be lost + var v1 <- create Vault(balance: 1000.0, dictRef); // This will be duplicated + var v2 <- create Vault(balance: 1.0, dictRef); // This will be lost - var v1Ref = &v1 as &Vault + var v1Ref = &v1 as &Vault - destroy dict.insert(key: false, <- v1) - destroy dict.insert(key: true, <- v2) + destroy dict.insert(key: false, <- v1) + destroy dict.insert(key: true, <- v2) - destroy dict; + destroy dict; - // v1 is not destroyed! - return v1Ref.balance - }` + // v1 is not destroyed! + return v1Ref.balance + } + ` runtime := newTestInterpreterRuntime() @@ -285,35 +287,36 @@ func TestRuntimeResourceDuplicationUsingDestructorIteration(t *testing.T) { t.Parallel() script := ` - access(all) resource R{} + access(all) resource R{} - access(all) fun main() { - var dict: @{Int: R} <- {} + access(all) fun main() { + var dict: @{Int: R} <- {} - var r1: @R? <- create R() - var r2: @R? <- create R() - var r3: @R? <- create R() + var r1: @R? <- create R() + var r2: @R? <- create R() + var r3: @R? <- create R() - dict[0] <-> r1 - dict[1] <-> r2 - dict[2] <-> r3 + dict[0] <-> r1 + dict[1] <-> r2 + dict[2] <-> r3 - destroy r1 - destroy r2 - destroy r3 + destroy r1 + destroy r2 + destroy r3 - let acc = getAuthAccount(0x1) - acc.save(<-dict, to: /storage/foo) + let acc = getAuthAccount(0x1) + acc.storage.save(<-dict, to: /storage/foo) - let ref = acc.borrow(from: /storage/foo)! + let ref = acc.storage.borrow(from: /storage/foo)! - ref.forEachKey(fun(i: Int): Bool { - var r4: @R? <- create R() - ref[i+1] <-> r4 - destroy r4 - return true - }) - }` + ref.forEachKey(fun(i: Int): Bool { + var r4: @R? <- create R() + ref[i+1] <-> r4 + destroy r4 + return true + }) + } + ` runtime := newTestInterpreterRuntime() @@ -370,7 +373,7 @@ func TestRuntimeResourceDuplicationUsingDestructorIteration(t *testing.T) { t.Parallel() script := ` - access(all) resource Vault { + access(all) resource Vault { access(all) var balance: UFix64 access(all) var arrRef: auth(Mutate) &[Vault] @@ -404,8 +407,8 @@ func TestRuntimeResourceDuplicationUsingDestructorIteration(t *testing.T) { var v1Ref = &v1 as &Vault - arr.append(<- v1) - arr.append(<- v2) + arr.append(<- v1) + arr.append(<- v2) destroy arr @@ -534,7 +537,7 @@ func TestRuntimeResourceDuplicationWithContractTransfer(t *testing.T) { ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Storage, Contracts, Capabilities) &Account) { signer.contracts.add(name: "FlowToken", code: "%s".decodeHex(), signer) } } @@ -564,15 +567,15 @@ func TestRuntimeResourceDuplicationWithContractTransfer(t *testing.T) { self.content <- nil } - access(all) fun setContent(_ vault: @FlowToken.Vault?) { - self.content <-! vault - } + access(all) fun setContent(_ vault: @FlowToken.Vault?) { + self.content <-! vault + } + + access(all) fun swapContent(_ vault: @FlowToken.Vault?): @FlowToken.Vault? { + let oldVault <- self.content <- vault + return <-oldVault + } - access(all) fun swapContent(_ vault: @FlowToken.Vault?): @FlowToken.Vault? { - let oldVault <- self.content <- vault - return <-oldVault - } - } ` err = runtime.ExecuteTransaction( @@ -598,7 +601,7 @@ func TestRuntimeResourceDuplicationWithContractTransfer(t *testing.T) { transaction { - prepare(acct: AuthAccount) { + prepare(acct: auth(Storage) &Account) { // Create vault let vault <- FlowToken.createEmptyVault() as! @FlowToken.Vault? @@ -607,14 +610,14 @@ func TestRuntimeResourceDuplicationWithContractTransfer(t *testing.T) { Holder.setContent(<-vault) // Save the contract into storage (invalid, even if same account) - acct.save(Holder as AnyStruct, to: /storage/holder) + acct.storage.save(Holder as AnyStruct, to: /storage/holder) // Move vault back out of the contract let vault2 <- Holder.swapContent(nil) let unwrappedVault2 <- vault2! // Load the contract back from storage - let dupeContract = acct.load(from: /storage/holder)! as! Holder + let dupeContract = acct.storage.load(from: /storage/holder)! as! Holder // Move the vault of of the duplicated contract let dupeVault <- dupeContract.swapContent(nil) diff --git a/runtime/resourcedictionary_test.go b/runtime/resourcedictionary_test.go index b511bceb9c..503d955e5e 100644 --- a/runtime/resourcedictionary_test.go +++ b/runtime/resourcedictionary_test.go @@ -106,8 +106,8 @@ func TestRuntimeResourceDictionaryValues(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - signer.save(<-Test.createC(), to: /storage/c) + prepare(signer: auth(Storage) &Account) { + signer.storage.save(<-Test.createC(), to: /storage/c) } } `) @@ -169,8 +169,8 @@ func TestRuntimeResourceDictionaryValues(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - let c = signer.borrow<&Test.C>(from: /storage/c)! + prepare(signer: auth(Storage) &Account) { + let c = signer.storage.borrow<&Test.C>(from: /storage/c)! c.forceInsert("a", <- Test.createR(1)) c.forceInsert("b", <- Test.createR(2)) } @@ -193,8 +193,8 @@ func TestRuntimeResourceDictionaryValues(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - let c = signer.borrow<&Test.C>(from: /storage/c)! + prepare(signer: auth(Storage) &Account) { + let c = signer.storage.borrow<&Test.C>(from: /storage/c)! log(c.rs["b"]?.value) log(c.rs["b"]?.value) } @@ -220,8 +220,8 @@ func TestRuntimeResourceDictionaryValues(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - let c = signer.borrow<&Test.C>(from: /storage/c)! + prepare(signer: auth(Storage) &Account) { + let c = signer.storage.borrow<&Test.C>(from: /storage/c)! c.rs["b"]?.increment() log(c.rs["b"]?.value) @@ -251,8 +251,8 @@ func TestRuntimeResourceDictionaryValues(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - let c = signer.borrow<&Test.C>(from: /storage/c)! + prepare(signer: auth(Storage) &Account) { + let c = signer.storage.borrow<&Test.C>(from: /storage/c)! log(c.rs["b"]?.value) destroy c.remove("b") c.forceInsert("b", <- Test.createR(4)) @@ -291,8 +291,8 @@ func TestRuntimeResourceDictionaryValues(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - let c = signer.borrow<&Test.C>(from: /storage/c)! + prepare(signer: auth(Storage) &Account) { + let c = signer.storage.borrow<&Test.C>(from: /storage/c)! log(c.rs["b"]?.value) destroy c.remove("b") log(c.rs["b"]?.value) @@ -347,15 +347,15 @@ func TestRuntimeResourceDictionaryValues(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - if let c <- signer.load<@Test.C>(from: /storage/c) { + prepare(signer: auth(Storage) &Account) { + if let c <- signer.storage.load<@Test.C>(from: /storage/c) { log(c.rs["a"]?.value) destroy c } let c2 <- Test.createC() c2.forceInsert("x", <-Test.createR(10)) - signer.save(<-c2, to: /storage/c) + signer.storage.save(<-c2, to: /storage/c) } } `) @@ -466,8 +466,11 @@ func TestRuntimeResourceDictionaryValues_Nested(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - signer.save(<-Test.createC(), to: /storage/c) + prepare(signer: auth(Storage) &Account) { + signer.storage.save( + <-Test.createC(), + to: /storage/c + ) } } `) @@ -532,8 +535,8 @@ func TestRuntimeResourceDictionaryValues_Nested(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - let c = signer.borrow<&Test.C>(from: /storage/c)! + prepare(signer: auth(Storage) &Account) { + let c = signer.storage.borrow<&Test.C>(from: /storage/c)! let c2 <- Test.createC2() c2.forceInsert("a", <- Test.createR(1)) c2.forceInsert("b", <- Test.createR(2)) @@ -558,8 +561,8 @@ func TestRuntimeResourceDictionaryValues_Nested(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - let c = signer.borrow<&Test.C>(from: /storage/c)! + prepare(signer: auth(Storage) &Account) { + let c = signer.storage.borrow<&Test.C>(from: /storage/c)! // TODO: use nested optional chaining log(c.c2s["x"]?.value(key: "b")) } @@ -638,7 +641,10 @@ func TestRuntimeResourceDictionaryValues_DictionaryTransfer(t *testing.T) { ` transaction { - prepare(signer1: AuthAccount, signer2: AuthAccount) { + prepare( + signer1: auth(Contracts) &Account, + signer2: &Account + ) { signer1.contracts.add(name: "Test", code: "%s".decodeHex()) } } @@ -651,11 +657,14 @@ func TestRuntimeResourceDictionaryValues_DictionaryTransfer(t *testing.T) { transaction { - prepare(signer1: AuthAccount, signer2: AuthAccount) { + prepare( + signer1: auth(Storage) &Account, + signer2: &Account + ) { let c <- Test.createC() c.setRs(key: "a", r: <- Test.createR(1)) c.setRs(key: "b", r: <- Test.createR(2)) - signer1.save(<-c, to: /storage/c) + signer1.storage.save(<-c, to: /storage/c) } } `) @@ -725,10 +734,13 @@ func TestRuntimeResourceDictionaryValues_DictionaryTransfer(t *testing.T) { transaction { - prepare(signer1: AuthAccount, signer2: AuthAccount) { - let c <- signer1.load<@Test.C>(from: /storage/c) ?? panic("missing C") + prepare( + signer1: auth(Storage) &Account, + signer2: auth(Storage) &Account + ) { + let c <- signer1.storage.load<@Test.C>(from: /storage/c) ?? panic("missing C") c.setRs(key: "x", r: <- Test.createR(42)) - signer2.save(<-c, to: /storage/c2) + signer2.storage.save(<-c, to: /storage/c2) } } `) @@ -762,11 +774,11 @@ func TestRuntimeResourceDictionaryValues_Removal(t *testing.T) { transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Storage) &Account) { let c <- Test.createC() c.forceInsert("a", <- Test.createR(1)) c.forceInsert("b", <- Test.createR(2)) - signer.save(<-c, to: /storage/c) + signer.storage.save(<-c, to: /storage/c) } } `) @@ -776,8 +788,8 @@ func TestRuntimeResourceDictionaryValues_Removal(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - let c = signer.borrow<&Test.C>(from: /storage/c)! + prepare(signer: auth(Storage) &Account) { + let c = signer.storage.borrow<&Test.C>(from: /storage/c)! let r <- c.remove("a") destroy r } @@ -789,8 +801,8 @@ func TestRuntimeResourceDictionaryValues_Removal(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - let c <- signer.load<@Test.C>(from: /storage/c)! + prepare(signer: auth(Storage) &Account) { + let c <- signer.storage.load<@Test.C>(from: /storage/c)! let r <- c.remove("b") destroy r destroy c @@ -876,7 +888,7 @@ func TestRuntimeResourceDictionaryValues_Removal(t *testing.T) { require.NoError(t, err) } -func TestRuntimeSResourceDictionaryValues_Destruction(t *testing.T) { +func TestRuntimeResourceDictionaryValues_Destruction(t *testing.T) { t.Parallel() @@ -891,11 +903,11 @@ func TestRuntimeSResourceDictionaryValues_Destruction(t *testing.T) { transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Storage) &Account) { let c <- Test.createC() c.forceInsert("a", <- Test.createR(1)) c.forceInsert("b", <- Test.createR(2)) - signer.save(<-c, to: /storage/c) + signer.storage.save(<-c, to: /storage/c) } } `) @@ -905,8 +917,8 @@ func TestRuntimeSResourceDictionaryValues_Destruction(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - let c <- signer.load<@Test.C>(from: /storage/c) + prepare(signer: auth(Storage) &Account) { + let c <- signer.storage.load<@Test.C>(from: /storage/c) destroy c } } @@ -1005,11 +1017,11 @@ func TestRuntimeResourceDictionaryValues_Insertion(t *testing.T) { transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Storage) &Account) { let c <- Test.createC() c.forceInsert("a", <- Test.createR(1)) c.forceInsert("b", <- Test.createR(2)) - signer.save(<-c, to: /storage/c) + signer.storage.save(<-c, to: /storage/c) } } `) @@ -1019,8 +1031,8 @@ func TestRuntimeResourceDictionaryValues_Insertion(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - let c = signer.borrow<&Test.C>(from: /storage/c)! + prepare(signer: auth(Storage) &Account) { + let c = signer.storage.borrow<&Test.C>(from: /storage/c)! let e1 <- c.insert("c", <-Test.createR(3)) assert(e1 == nil) @@ -1038,8 +1050,8 @@ func TestRuntimeResourceDictionaryValues_Insertion(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - let c <- signer.load<@Test.C>(from: /storage/c)! + prepare(signer: auth(Storage) &Account) { + let c <- signer.storage.load<@Test.C>(from: /storage/c)! let e1 <- c.insert("d", <-Test.createR(4)) assert(e1 == nil) destroy e1 @@ -1146,9 +1158,9 @@ func TestRuntimeResourceDictionaryValues_ValueTransferAndDestroy(t *testing.T) { transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Storage) &Account) { let c <- Test.createC() - signer.save(<-c, to: /storage/c) + signer.storage.save(<-c, to: /storage/c) } } `) @@ -1158,8 +1170,8 @@ func TestRuntimeResourceDictionaryValues_ValueTransferAndDestroy(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - let c = signer.borrow<&Test.C>(from: /storage/c)! + prepare(signer: auth(Storage) &Account) { + let c = signer.storage.borrow<&Test.C>(from: /storage/c)! let existing <- c.insert("1", <-Test.createR(1)) assert(existing == nil) @@ -1173,9 +1185,12 @@ func TestRuntimeResourceDictionaryValues_ValueTransferAndDestroy(t *testing.T) { transaction { - prepare(signer1: AuthAccount, signer2: AuthAccount) { - let c1 = signer1.borrow<&Test.C>(from: /storage/c)! - let c2 = signer2.borrow<&Test.C>(from: /storage/c)! + prepare( + signer1: auth(Storage) &Account, + signer2: auth(Storage) &Account + ) { + let c1 = signer1.storage.borrow<&Test.C>(from: /storage/c)! + let c2 = signer2.storage.borrow<&Test.C>(from: /storage/c)! let r <- c1.remove("1") @@ -1191,8 +1206,8 @@ func TestRuntimeResourceDictionaryValues_ValueTransferAndDestroy(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - let c = signer.borrow<&Test.C>(from: /storage/c)! + prepare(signer: auth(Storage) &Account) { + let c = signer.storage.borrow<&Test.C>(from: /storage/c)! let r <- c.remove("1") destroy r @@ -1336,14 +1351,14 @@ func BenchmarkRuntimeResourceDictionaryValues(b *testing.B) { transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { let data: @{Int: Test.R} <- {} var i = 0 while i < 1000 { data[i] <-! Test.createR() i = i + 1 } - signer.save(<-data, to: /storage/data) + signer.storage.save(<-data, to: /storage/data) } } `) @@ -1403,8 +1418,8 @@ func BenchmarkRuntimeResourceDictionaryValues(b *testing.B) { transaction { - prepare(signer: AuthAccount) { - let ref = signer.borrow<&{Int: Test.R}>(from: /storage/data)! + prepare(signer: &Account) { + let ref = signer.storage.borrow<&{Int: Test.R}>(from: /storage/data)! assert(ref[50] != nil) } } diff --git a/runtime/rlp_test.go b/runtime/rlp_test.go index 11cae14e66..c4789e7bfa 100644 --- a/runtime/rlp_test.go +++ b/runtime/rlp_test.go @@ -30,7 +30,7 @@ import ( . "github.com/onflow/cadence/runtime/tests/utils" ) -func TestRLPDecodeString(t *testing.T) { +func TestRuntimeRLPDecodeString(t *testing.T) { t.Parallel() @@ -139,7 +139,7 @@ func TestRLPDecodeString(t *testing.T) { Arguments: encodeArgs([]cadence.Value{ cadence.Array{ ArrayType: &cadence.VariableSizedArrayType{ - ElementType: cadence.UInt8Type{}, + ElementType: cadence.UInt8Type, }, Values: test.input, }, @@ -160,7 +160,7 @@ func TestRLPDecodeString(t *testing.T) { cadence.Array{ Values: test.output, }.WithType(&cadence.VariableSizedArrayType{ - ElementType: cadence.UInt8Type{}, + ElementType: cadence.UInt8Type, }), result, ) @@ -173,7 +173,7 @@ func TestRLPDecodeString(t *testing.T) { } } -func TestRLPDecodeList(t *testing.T) { +func TestRuntimeRLPDecodeList(t *testing.T) { t.Parallel() @@ -298,7 +298,7 @@ func TestRLPDecodeList(t *testing.T) { Arguments: encodeArgs([]cadence.Value{ cadence.Array{ ArrayType: &cadence.VariableSizedArrayType{ - ElementType: cadence.UInt8Type{}, + ElementType: cadence.UInt8Type, }, Values: test.input, }, @@ -321,7 +321,7 @@ func TestRLPDecodeList(t *testing.T) { arrays = append(arrays, cadence.Array{Values: values}. WithType(&cadence.VariableSizedArrayType{ - ElementType: cadence.UInt8Type{}, + ElementType: cadence.UInt8Type, })) } @@ -330,7 +330,7 @@ func TestRLPDecodeList(t *testing.T) { Values: arrays, }.WithType(&cadence.VariableSizedArrayType{ ElementType: &cadence.VariableSizedArrayType{ - ElementType: cadence.UInt8Type{}, + ElementType: cadence.UInt8Type, }, }), result, diff --git a/runtime/runtime.go b/runtime/runtime.go index 675f46f191..fe0243c7ff 100644 --- a/runtime/runtime.go +++ b/runtime/runtime.go @@ -128,8 +128,9 @@ type Runtime interface { // InvokeContractFunction invokes a contract function with the given arguments. // // This function returns an error if the execution fails. - // If the contract function accepts an AuthAccount as a parameter the corresponding argument can be an interpreter.Address. - // returns a cadence.Value + // If the contract function accepts an &Account as a parameter, + // the corresponding argument can be an interpreter.Address. + // Returns a cadence.Value InvokeContractFunction( contractLocation common.AddressLocation, functionName string, diff --git a/runtime/runtime_memory_metering_test.go b/runtime/runtime_memory_metering_test.go index 96c0d43b38..9ec4886c76 100644 --- a/runtime/runtime_memory_metering_test.go +++ b/runtime/runtime_memory_metering_test.go @@ -53,7 +53,7 @@ func (g *testMemoryGauge) getMemory(kind common.MemoryKind) uint64 { return g.meter[kind] } -func TestInterpreterAddressLocationMetering(t *testing.T) { +func TestRuntimeInterpreterAddressLocationMetering(t *testing.T) { t.Parallel() @@ -102,7 +102,7 @@ func TestInterpreterAddressLocationMetering(t *testing.T) { }) } -func TestInterpreterElaborationImportMetering(t *testing.T) { +func TestRuntimeInterpreterElaborationImportMetering(t *testing.T) { t.Parallel() @@ -202,7 +202,7 @@ func TestInterpreterElaborationImportMetering(t *testing.T) { } } -func TestCadenceValueAndTypeMetering(t *testing.T) { +func TestRuntimeCadenceValueAndTypeMetering(t *testing.T) { t.Parallel() @@ -759,7 +759,7 @@ func TestCadenceValueAndTypeMetering(t *testing.T) { }) } -func TestLogFunctionStringConversionMetering(t *testing.T) { +func TestRuntimeLogFunctionStringConversionMetering(t *testing.T) { t.Parallel() @@ -821,7 +821,7 @@ func TestLogFunctionStringConversionMetering(t *testing.T) { assert.Equal(t, diffOfActualLen, diffOfMeteredAmount) } -func TestStorageCommitsMetering(t *testing.T) { +func TestRuntimeStorageCommitsMetering(t *testing.T) { t.Parallel() @@ -830,8 +830,8 @@ func TestStorageCommitsMetering(t *testing.T) { code := []byte(` transaction { - prepare(signer: AuthAccount) { - signer.storageUsed + prepare(signer: &Account) { + signer.storage.used } } `) @@ -872,13 +872,13 @@ func TestStorageCommitsMetering(t *testing.T) { assert.Equal(t, uint64(0), meter.getMemory(common.MemoryKindAtreeEncodedSlab)) }) - t.Run("account save", func(t *testing.T) { + t.Run("account.storage.save", func(t *testing.T) { t.Parallel() code := []byte(` transaction { - prepare(signer: AuthAccount) { - signer.save([[1, 2, 3], [4, 5, 6]], to: /storage/test) + prepare(signer: auth(Storage) &Account) { + signer.storage.save([[1, 2, 3], [4, 5, 6]], to: /storage/test) } } `) @@ -914,9 +914,9 @@ func TestStorageCommitsMetering(t *testing.T) { code := []byte(` transaction { - prepare(signer: AuthAccount) { - signer.save([[1, 2, 3], [4, 5, 6]], to: /storage/test) - signer.storageUsed + prepare(signer: auth(Storage) &Account) { + signer.storage.save([[1, 2, 3], [4, 5, 6]], to: /storage/test) + signer.storage.used } } `) @@ -957,7 +957,7 @@ func TestStorageCommitsMetering(t *testing.T) { }) } -func TestMemoryMeteringErrors(t *testing.T) { +func TestRuntimeMemoryMeteringErrors(t *testing.T) { t.Parallel() @@ -1064,7 +1064,7 @@ func TestMemoryMeteringErrors(t *testing.T) { }) } -func TestMeterEncoding(t *testing.T) { +func TestRuntimeMeterEncoding(t *testing.T) { t.Parallel() @@ -1093,9 +1093,9 @@ func TestMeterEncoding(t *testing.T) { Script{ Source: []byte(fmt.Sprintf(` transaction() { - prepare(acc: AuthAccount) { + prepare(acc: auth(Storage) &Account) { var s = "%s" - acc.save(s, to:/storage/some_path) + acc.storage.save(s, to:/storage/some_path) } }`, text, @@ -1136,12 +1136,12 @@ func TestMeterEncoding(t *testing.T) { Script{ Source: []byte(fmt.Sprintf(` transaction() { - prepare(acc: AuthAccount) { + prepare(acc: auth(Storage) &Account) { var i = 0 var s = "%s" while i<1000 { let path = StoragePath(identifier: "i".concat(i.toString()))! - acc.save(s, to: path) + acc.storage.save(s, to: path) i=i+1 } } @@ -1182,12 +1182,12 @@ func TestMeterEncoding(t *testing.T) { Script{ Source: []byte(` access(all) fun main() { - let acc = getAuthAccount(0x02) + let acc = getAuthAccount(0x02) var i = 0 var f = Foo() while i<1000 { let path = StoragePath(identifier: "i".concat(i.toString()))! - acc.save(f, to: path) + acc.storage.save(f, to: path) i=i+1 } } diff --git a/runtime/runtime_test.go b/runtime/runtime_test.go index 431794fd41..305cc21b01 100644 --- a/runtime/runtime_test.go +++ b/runtime/runtime_test.go @@ -1049,7 +1049,7 @@ func TestRuntimeTransactionWithAccount(t *testing.T) { script := []byte(` transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { log(signer.address) } } @@ -1117,7 +1117,7 @@ func TestRuntimeTransactionWithArguments(t *testing.T) { label: "Single argument with authorizer", script: ` transaction(x: Int) { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { log(signer.address) } @@ -1318,7 +1318,7 @@ func TestRuntimeTransactionWithArguments(t *testing.T) { Fields: []cadence.Field{ { Identifier: "y", - Type: cadence.StringType{}, + Type: cadence.StringType, }, }, }), @@ -1368,7 +1368,7 @@ func TestRuntimeTransactionWithArguments(t *testing.T) { Fields: []cadence.Field{ { Identifier: "y", - Type: cadence.StringType{}, + Type: cadence.StringType, }, }, }), @@ -1683,7 +1683,7 @@ func TestRuntimeScriptArguments(t *testing.T) { Fields: []cadence.Field{ { Identifier: "y", - Type: cadence.StringType{}, + Type: cadence.StringType, }, }, }), @@ -1718,7 +1718,7 @@ func TestRuntimeScriptArguments(t *testing.T) { Fields: []cadence.Field{ { Identifier: "y", - Type: cadence.StringType{}, + Type: cadence.StringType, }, }, }), @@ -1863,57 +1863,57 @@ func TestRuntimeStorage(t *testing.T) { tests := map[string]string{ "resource": ` - let r <- signer.load<@R>(from: /storage/r) + let r <- signer.storage.load<@R>(from: /storage/r) log(r == nil) destroy r - signer.save(<-createR(), to: /storage/r) - let r2 <- signer.load<@R>(from: /storage/r) + signer.storage.save(<-createR(), to: /storage/r) + let r2 <- signer.storage.load<@R>(from: /storage/r) log(r2 != nil) destroy r2 `, "struct": ` - let s = signer.load(from: /storage/s) + let s = signer.storage.load(from: /storage/s) log(s == nil) - signer.save(S(), to: /storage/s) - let s2 = signer.load(from: /storage/s) + signer.storage.save(S(), to: /storage/s) + let s2 = signer.storage.load(from: /storage/s) log(s2 != nil) `, "resource array": ` - let rs <- signer.load<@[R]>(from: /storage/rs) + let rs <- signer.storage.load<@[R]>(from: /storage/rs) log(rs == nil) destroy rs - signer.save(<-[<-createR()], to: /storage/rs) - let rs2 <- signer.load<@[R]>(from: /storage/rs) + signer.storage.save(<-[<-createR()], to: /storage/rs) + let rs2 <- signer.storage.load<@[R]>(from: /storage/rs) log(rs2 != nil) destroy rs2 `, "struct array": ` - let s = signer.load<[S]>(from: /storage/s) + let s = signer.storage.load<[S]>(from: /storage/s) log(s == nil) - signer.save([S()], to: /storage/s) - let s2 = signer.load<[S]>(from: /storage/s) + signer.storage.save([S()], to: /storage/s) + let s2 = signer.storage.load<[S]>(from: /storage/s) log(s2 != nil) `, "resource dictionary": ` - let rs <- signer.load<@{String: R}>(from: /storage/rs) + let rs <- signer.storage.load<@{String: R}>(from: /storage/rs) log(rs == nil) destroy rs - signer.save(<-{"r": <-createR()}, to: /storage/rs) - let rs2 <- signer.load<@{String: R}>(from: /storage/rs) + signer.storage.save(<-{"r": <-createR()}, to: /storage/rs) + let rs2 <- signer.storage.load<@{String: R}>(from: /storage/rs) log(rs2 != nil) destroy rs2 `, "struct dictionary": ` - let s = signer.load<{String: S}>(from: /storage/s) + let s = signer.storage.load<{String: S}>(from: /storage/s) log(s == nil) - signer.save({"s": S()}, to: /storage/s) - let rs2 = signer.load<{String: S}>(from: /storage/s) + signer.storage.save({"s": S()}, to: /storage/s) + let rs2 = signer.storage.load<{String: S}>(from: /storage/s) log(rs2 != nil) `, } @@ -1936,7 +1936,7 @@ func TestRuntimeStorage(t *testing.T) { import "imported" transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth (Storage) &Account) { %s } } @@ -2011,8 +2011,8 @@ func TestRuntimeStorageMultipleTransactionsResourceWithArray(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - signer.save(<-createContainer(), to: /storage/container) + prepare(signer: auth (Storage, Capabilities) &Account) { + signer.storage.save(<-createContainer(), to: /storage/container) let cap = signer.capabilities.storage.issue(/storage/container) signer.capabilities.publish(cap, at: /public/container) } @@ -2023,7 +2023,7 @@ func TestRuntimeStorageMultipleTransactionsResourceWithArray(t *testing.T) { import "container" transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { let publicAccount = getAccount(signer.address) let ref = publicAccount.capabilities.borrow(/public/container)! @@ -2038,7 +2038,7 @@ func TestRuntimeStorageMultipleTransactionsResourceWithArray(t *testing.T) { import "container" transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { let publicAccount = getAccount(signer.address) let ref = publicAccount.capabilities.borrow(/public/container)! @@ -2131,8 +2131,8 @@ func TestRuntimeStorageMultipleTransactionsResourceFunction(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - signer.save(<-createDeepThought(), to: /storage/deepThought) + prepare(signer: auth(Storage) &Account) { + signer.storage.save(<-createDeepThought(), to: /storage/deepThought) } } `) @@ -2141,8 +2141,8 @@ func TestRuntimeStorageMultipleTransactionsResourceFunction(t *testing.T) { import "deep-thought" transaction { - prepare(signer: AuthAccount) { - let answer = signer.borrow<&DeepThought>(from: /storage/deepThought)?.answer() + prepare(signer: auth(Storage) &Account) { + let answer = signer.storage.borrow<&DeepThought>(from: /storage/deepThought)?.answer() log(answer ?? 0) } } @@ -2222,8 +2222,8 @@ func TestRuntimeStorageMultipleTransactionsResourceField(t *testing.T) { import "imported" transaction { - prepare(signer: AuthAccount) { - signer.save(<-createNumber(42), to: /storage/number) + prepare(signer: auth(Storage) &Account) { + signer.storage.save(<-createNumber(42), to: /storage/number) } } `) @@ -2232,8 +2232,8 @@ func TestRuntimeStorageMultipleTransactionsResourceField(t *testing.T) { import "imported" transaction { - prepare(signer: AuthAccount) { - if let number <- signer.load<@SomeNumber>(from: /storage/number) { + prepare(signer: auth(Storage) &Account) { + if let number <- signer.storage.load<@SomeNumber>(from: /storage/number) { log(number.n) destroy number } @@ -2317,8 +2317,8 @@ func TestRuntimeCompositeFunctionInvocationFromImportingProgram(t *testing.T) { import Y, createY from "imported" transaction { - prepare(signer: AuthAccount) { - signer.save(<-createY(), to: /storage/y) + prepare(signer: auth(Storage) &Account) { + signer.storage.save(<-createY(), to: /storage/y) } } `) @@ -2327,8 +2327,8 @@ func TestRuntimeCompositeFunctionInvocationFromImportingProgram(t *testing.T) { import Y from "imported" transaction { - prepare(signer: AuthAccount) { - let y <- signer.load<@Y>(from: /storage/y) + prepare(signer: auth(Storage) &Account) { + let y <- signer.storage.load<@Y>(from: /storage/y) y?.x() destroy y } @@ -2398,8 +2398,8 @@ func TestRuntimeResourceContractUseThroughReference(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - signer.save(<-createR(), to: /storage/r) + prepare(signer: auth(Storage) &Account) { + signer.storage.save(<-createR(), to: /storage/r) } } `) @@ -2409,8 +2409,8 @@ func TestRuntimeResourceContractUseThroughReference(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - let ref = signer.borrow<&R>(from: /storage/r)! + prepare(signer: auth(Storage) &Account) { + let ref = signer.storage.borrow<&R>(from: /storage/r)! ref.x() } } @@ -2486,8 +2486,8 @@ func TestRuntimeResourceContractUseThroughLink(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - signer.save(<-createR(), to: /storage/r) + prepare(signer: auth(Storage, Capabilities) &Account) { + signer.storage.save(<-createR(), to: /storage/r) let cap = signer.capabilities.storage.issue<&R>(/storage/r) signer.capabilities.publish(cap, at: /public/r) } @@ -2498,7 +2498,7 @@ func TestRuntimeResourceContractUseThroughLink(t *testing.T) { import R from "imported" transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { let publicAccount = getAccount(signer.address) let ref = publicAccount.capabilities.borrow<&R>(/public/r)! ref.x() @@ -2584,10 +2584,10 @@ func TestRuntimeResourceContractWithInterface(t *testing.T) { import R, createR from "imported2" transaction { - prepare(signer: AuthAccount) { - signer.save(<-createR(), to: /storage/r) + prepare(signer: auth(Storage, Capabilities) &Account) { + signer.storage.save(<-createR(), to: /storage/r) let cap = signer.capabilities.storage.issue<&{RI}>(/storage/r) - signer.capabilities.publish(cap, at: /public/r) + signer.capabilities.publish(cap, at: /public/r) } } `) @@ -2601,7 +2601,7 @@ func TestRuntimeResourceContractWithInterface(t *testing.T) { import R from "imported2" transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { let ref = signer.capabilities.borrow<&{RI}>(/public/r)! ref.x() } @@ -2776,7 +2776,7 @@ func TestRuntimeScriptReturnSpecial(t *testing.T) { expected: cadence.Function{ FunctionType: cadence.TypeWithCachedTypeID( &cadence.FunctionType{ - ReturnType: cadence.IntType{}, + ReturnType: cadence.IntType, }, ).(*cadence.FunctionType), }, @@ -2803,10 +2803,10 @@ func TestRuntimeScriptReturnSpecial(t *testing.T) { { Label: sema.ArgumentLabelNotRequired, Identifier: "message", - Type: cadence.StringType{}, + Type: cadence.StringType, }, }, - ReturnType: cadence.NeverType{}, + ReturnType: cadence.NeverType, }, ).(*cadence.FunctionType), }, @@ -2833,7 +2833,7 @@ func TestRuntimeScriptReturnSpecial(t *testing.T) { expected: cadence.Function{ FunctionType: cadence.TypeWithCachedTypeID( &cadence.FunctionType{ - ReturnType: cadence.VoidType{}, + ReturnType: cadence.VoidType, }, ).(*cadence.FunctionType), }, @@ -2876,13 +2876,13 @@ func TestRuntimeScriptReturnSpecial(t *testing.T) { nil, }).WithType(&cadence.VariableSizedArrayType{ ElementType: &cadence.ReferenceType{ - Type: cadence.AnyStructType{}, + Type: cadence.AnyStructType, Authorization: cadence.UnauthorizedAccess, }, }), }).WithType(&cadence.VariableSizedArrayType{ ElementType: &cadence.ReferenceType{ - Type: cadence.AnyStructType{}, + Type: cadence.AnyStructType, Authorization: cadence.UnauthorizedAccess, }, }), @@ -2985,10 +2985,10 @@ func TestRuntimeStorageChanges(t *testing.T) { import X, createX from "imported" transaction { - prepare(signer: AuthAccount) { - signer.save(<-createX(), to: /storage/x) + prepare(signer: auth(Storage) &Account) { + signer.storage.save(<-createX(), to: /storage/x) - let ref = signer.borrow<&X>(from: /storage/x)! + let ref = signer.storage.borrow<&X>(from: /storage/x)! ref.setX(1) } } @@ -2998,8 +2998,8 @@ func TestRuntimeStorageChanges(t *testing.T) { import X from "imported" transaction { - prepare(signer: AuthAccount) { - let ref = signer.borrow<&X>(from: /storage/x)! + prepare(signer: auth(Storage) &Account) { + let ref = signer.storage.borrow<&X>(from: /storage/x)! log(ref.x) } } @@ -3060,7 +3060,7 @@ func TestRuntimeAccountAddress(t *testing.T) { script := []byte(` transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { log(signer.address) } } @@ -3165,8 +3165,8 @@ func TestRuntimeAccountPublishAndAccess(t *testing.T) { import "imported" transaction { - prepare(signer: AuthAccount) { - signer.save(<-createR(), to: /storage/r) + prepare(signer: auth(Storage, Capabilities) &Account) { + signer.storage.save(<-createR(), to: /storage/r) let cap = signer.capabilities.storage.issue<&R>(/storage/r) signer.capabilities.publish(cap, at: /public/r) } @@ -3182,7 +3182,7 @@ func TestRuntimeAccountPublishAndAccess(t *testing.T) { transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { log(getAccount(0x%s).capabilities.borrow<&R>(/public/r)!.test()) } } @@ -3246,8 +3246,8 @@ func TestRuntimeTransaction_CreateAccount(t *testing.T) { script := []byte(` transaction { - prepare(signer: AuthAccount) { - AuthAccount(payer: signer) + prepare(signer: auth(Storage) &Account) { + Account(payer: signer) } } `) @@ -3430,10 +3430,10 @@ func TestRuntimeInvokeContractFunction(t *testing.T) { log("Hello return!") return arg } - access(all) fun helloAuthAcc(account: AuthAccount) { + access(all) fun helloAuthAcc(account: &Account) { log("Hello ".concat(account.address.toString())) } - access(all) fun helloPublicAcc(account: PublicAccount) { + access(all) fun helloPublicAcc(account: &Account) { log("Hello access(all) ".concat(account.address.toString())) } } @@ -3638,7 +3638,7 @@ func TestRuntimeInvokeContractFunction(t *testing.T) { cadence.NewCapability( 1, cadence.Address{}, - cadence.AddressType{}, // this will error during `importValue` + cadence.AddressType, // this will error during `importValue` ), }, []sema.Type{ @@ -3665,7 +3665,7 @@ func TestRuntimeInvokeContractFunction(t *testing.T) { cadence.NewCapability( 42, cadence.Address{}, - cadence.AddressType{}, // this will error during `importValue` + cadence.AddressType, // this will error during `importValue` ), }, []sema.Type{ @@ -3692,7 +3692,7 @@ func TestRuntimeInvokeContractFunction(t *testing.T) { cadence.BytesToAddress(addressValue.Bytes()), }, []sema.Type{ - sema.AuthAccountType, + sema.FullyEntitledAccountReferenceType, }, Context{ Interface: runtimeInterface, @@ -3714,7 +3714,7 @@ func TestRuntimeInvokeContractFunction(t *testing.T) { cadence.BytesToAddress(addressValue.Bytes()), }, []sema.Type{ - sema.PublicAccountType, + sema.AccountReferenceType, }, Context{ Interface: runtimeInterface, @@ -3749,7 +3749,7 @@ func TestRuntimeContractNestedResource(t *testing.T) { init() { // store nested resource in account on deployment - self.account.save(<-create R(), to: /storage/r) + self.account.storage.save(<-create R(), to: /storage/r) } } `) @@ -3759,8 +3759,8 @@ func TestRuntimeContractNestedResource(t *testing.T) { transaction { - prepare(acct: AuthAccount) { - log(acct.borrow<&Test.R>(from: /storage/r)?.hello()) + prepare(acct: auth(Storage) &Account) { + log(acct.storage.borrow<&Test.R>(from: /storage/r)?.hello()) } } `) @@ -3835,6 +3835,7 @@ func TestRuntimeStorageLoadedDestructionConcreteType(t *testing.T) { contract := []byte(` access(all) contract Test { + access(all) resource R { // test that the destructor is linked back into the nested resource // after being loaded from storage @@ -3845,7 +3846,7 @@ func TestRuntimeStorageLoadedDestructionConcreteType(t *testing.T) { init() { // store nested resource in account on deployment - self.account.save(<-create R(), to: /storage/r) + self.account.storage.save(<-create R(), to: /storage/r) } } `) @@ -3855,8 +3856,8 @@ func TestRuntimeStorageLoadedDestructionConcreteType(t *testing.T) { transaction { - prepare(acct: AuthAccount) { - let r <- acct.load<@Test.R>(from: /storage/r) + prepare(acct: auth(Storage) &Account) { + let r <- acct.storage.load<@Test.R>(from: /storage/r) destroy r } } @@ -3939,7 +3940,7 @@ func TestRuntimeStorageLoadedDestructionAnyResource(t *testing.T) { init() { // store nested resource in account on deployment - self.account.save(<-create R(), to: /storage/r) + self.account.storage.save(<-create R(), to: /storage/r) } } `) @@ -3950,8 +3951,8 @@ func TestRuntimeStorageLoadedDestructionAnyResource(t *testing.T) { transaction { - prepare(acct: AuthAccount) { - let r <- acct.load<@AnyResource>(from: /storage/r) + prepare(acct: auth(Storage) &Account) { + let r <- acct.storage.load<@AnyResource>(from: /storage/r) destroy r } } @@ -4035,7 +4036,7 @@ func TestRuntimeStorageLoadedDestructionAfterRemoval(t *testing.T) { init() { // store nested resource in account on deployment - self.account.save(<-create R(), to: /storage/r) + self.account.storage.save(<-create R(), to: /storage/r) } } `) @@ -4046,8 +4047,8 @@ func TestRuntimeStorageLoadedDestructionAfterRemoval(t *testing.T) { transaction { - prepare(acct: AuthAccount) { - let r <- acct.load<@AnyResource>(from: /storage/r) + prepare(acct: auth(Storage) &Account) { + let r <- acct.storage.load<@AnyResource>(from: /storage/r) destroy r } } @@ -4226,8 +4227,8 @@ access(all) contract FungibleToken { } init() { - self.account.save(<-create Vault(balance: 30), to: /storage/vault) - self.account.save(<-create VaultMinter(), to: /storage/minter) + self.account.storage.save(<-create Vault(balance: 30), to: /storage/vault) + self.account.storage.save(<-create VaultMinter(), to: /storage/minter) } } ` @@ -4253,7 +4254,7 @@ func TestRuntimeFungibleTokenUpdateAccountCode(t *testing.T) { transaction { - prepare(acct: AuthAccount) { + prepare(acct: auth(Capabilities) &Account) { let receiverCap = acct.capabilities.storage .issue<&{FungibleToken.Receiver}>(/storage/vault) @@ -4271,10 +4272,10 @@ func TestRuntimeFungibleTokenUpdateAccountCode(t *testing.T) { transaction { - prepare(acct: AuthAccount) { + prepare(acct: auth(Storage, Capabilities) &Account) { let vault <- FungibleToken.createEmptyVault() - acct.save(<-vault, to: /storage/vault) + acct.storage.save(<-vault, to: /storage/vault) let receiverCap = acct.capabilities.storage .issue<&{FungibleToken.Receiver}>(/storage/vault) @@ -4368,8 +4369,8 @@ func TestRuntimeFungibleTokenCreateAccount(t *testing.T) { deploy := []byte(fmt.Sprintf( ` transaction { - prepare(signer: AuthAccount) { - let acct = AuthAccount(payer: signer) + prepare(signer: auth(Storage) &Account) { + let acct = Account(payer: signer) acct.contracts.add(name: "FungibleToken", code: "%s".decodeHex()) } } @@ -4382,7 +4383,7 @@ func TestRuntimeFungibleTokenCreateAccount(t *testing.T) { transaction { - prepare(acct: AuthAccount) { + prepare(acct: auth(Capabilities) &Account) { let receiverCap = acct.capabilities.storage .issue<&{FungibleToken.Receiver}>(/storage/vault) acct.capabilities.publish(receiverCap, at: /public/receiver1) @@ -4399,10 +4400,10 @@ func TestRuntimeFungibleTokenCreateAccount(t *testing.T) { transaction { - prepare(acct: AuthAccount) { + prepare(acct: auth(Storage, Capabilities) &Account) { let vault <- FungibleToken.createEmptyVault() - acct.save(<-vault, to: /storage/vault) + acct.storage.save(<-vault, to: /storage/vault) let receiverCap = acct.capabilities.storage .issue<&{FungibleToken.Receiver}>(/storage/vault) @@ -4490,8 +4491,8 @@ func TestRuntimeInvokeStoredInterfaceFunction(t *testing.T) { return []byte(fmt.Sprintf( ` transaction { - prepare(signer: AuthAccount) { - let acct = AuthAccount(payer: signer) + prepare(signer: auth(Storage) &Account) { + let acct = Account(payer: signer) acct.contracts.add(name: "%s", code: "%s".decodeHex()) } } @@ -4538,8 +4539,8 @@ func TestRuntimeInvokeStoredInterfaceFunction(t *testing.T) { import TestContract from 0x3 transaction { - prepare(signer: AuthAccount) { - signer.save(<-TestContract.createR(), to: /storage/r) + prepare(signer: auth(Storage) &Account) { + signer.storage.save(<-TestContract.createR(), to: /storage/r) } } `) @@ -4556,8 +4557,9 @@ func TestRuntimeInvokeStoredInterfaceFunction(t *testing.T) { // import TestContract from 0x3 transaction { - prepare(signer: AuthAccount) { - signer.borrow<&{TestContractInterface.RInterface}>(from: /storage/r)?.check(a: %d, b: %d) + prepare(signer: auth(Storage) &Account) { + signer.storage.borrow<&{TestContractInterface.RInterface}>(from: /storage/r) + ?.check(a: %d, b: %d) } } `, @@ -4964,17 +4966,17 @@ func TestRuntimeResourceOwnerFieldUseComposite(t *testing.T) { transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Storage, Capabilities) &Account) { let r <- Test.createR() log(r.owner?.address) r.logOwnerAddress() - signer.save(<-r, to: /storage/r) + signer.storage.save(<-r, to: /storage/r) let cap = signer.capabilities.storage.issue<&Test.R>(/storage/r) signer.capabilities.publish(cap, at: /public/r) - let ref1 = signer.borrow<&Test.R>(from: /storage/r)! + let ref1 = signer.storage.borrow<&Test.R>(from: /storage/r)! log(ref1.owner?.address) ref1.logOwnerAddress() @@ -4991,13 +4993,13 @@ func TestRuntimeResourceOwnerFieldUseComposite(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - let ref1 = signer.borrow<&Test.R>(from: /storage/r)! + prepare(signer: auth(Storage) &Account) { + let ref1 = signer.storage.borrow<&Test.R>(from: /storage/r)! log(ref1.owner?.address) log(ref1.owner?.balance) log(ref1.owner?.availableBalance) - log(ref1.owner?.storageUsed) - log(ref1.owner?.storageCapacity) + log(ref1.owner?.storage?.used) + log(ref1.owner?.storage?.capacity) ref1.logOwnerAddress() let publicAccount = getAccount(0x01) @@ -5005,8 +5007,8 @@ func TestRuntimeResourceOwnerFieldUseComposite(t *testing.T) { log(ref2.owner?.address) log(ref2.owner?.balance) log(ref2.owner?.availableBalance) - log(ref2.owner?.storageUsed) - log(ref2.owner?.storageCapacity) + log(ref2.owner?.storage?.used) + log(ref2.owner?.storage?.capacity) ref2.logOwnerAddress() } } @@ -5109,16 +5111,16 @@ func TestRuntimeResourceOwnerFieldUseComposite(t *testing.T) { "0x0000000000000001", // ref1.owner?.address "123.00000000", // ref2.owner?.balance "1523.00000000", // ref2.owner?.availableBalance - "120", // ref1.owner?.storageUsed - "1245", // ref1.owner?.storageCapacity + "120", // ref1.owner?.storage.used + "1245", // ref1.owner?.storage.capacity "0x0000000000000001", "0x0000000000000001", // ref2.owner?.address "123.00000000", // ref2.owner?.balance "1523.00000000", // ref2.owner?.availableBalance - "120", // ref2.owner?.storageUsed - "1245", // ref2.owner?.storageCapacity + "120", // ref2.owner?.storage.used + "1245", // ref2.owner?.storage.capacity "0x0000000000000001", }, @@ -5159,7 +5161,7 @@ func TestRuntimeResourceOwnerFieldUseArray(t *testing.T) { transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Storage, Capabilities) &Account) { let rs <- [ <-Test.createR(), @@ -5170,11 +5172,11 @@ func TestRuntimeResourceOwnerFieldUseArray(t *testing.T) { rs[0].logOwnerAddress() rs[1].logOwnerAddress() - signer.save(<-rs, to: /storage/rs) + signer.storage.save(<-rs, to: /storage/rs) let cap = signer.capabilities.storage.issue<&[Test.R]>(/storage/rs) signer.capabilities.publish(cap, at: /public/rs) - let ref1 = signer.borrow<&[Test.R]>(from: /storage/rs)! + let ref1 = signer.storage.borrow<&[Test.R]>(from: /storage/rs)! log(ref1[0].owner?.address) log(ref1[1].owner?.address) ref1[0].logOwnerAddress() @@ -5195,8 +5197,8 @@ func TestRuntimeResourceOwnerFieldUseArray(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - let ref1 = signer.borrow<&[Test.R]>(from: /storage/rs)! + prepare(signer: auth(Storage) &Account) { + let ref1 = signer.storage.borrow<&[Test.R]>(from: /storage/rs)! log(ref1[0].owner?.address) log(ref1[1].owner?.address) ref1[0].logOwnerAddress() @@ -5333,7 +5335,7 @@ func TestRuntimeResourceOwnerFieldUseDictionary(t *testing.T) { transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Storage, Capabilities) &Account) { let rs <- { "a": <-Test.createR(), @@ -5344,11 +5346,11 @@ func TestRuntimeResourceOwnerFieldUseDictionary(t *testing.T) { rs["a"]?.logOwnerAddress() rs["b"]?.logOwnerAddress() - signer.save(<-rs, to: /storage/rs) + signer.storage.save(<-rs, to: /storage/rs) let cap = signer.capabilities.storage.issue<&{String: Test.R}>(/storage/rs) signer.capabilities.publish(cap, at: /public/rs) - let ref1 = signer.borrow<&{String: Test.R}>(from: /storage/rs)! + let ref1 = signer.storage.borrow<&{String: Test.R}>(from: /storage/rs)! log(ref1["a"]?.owner?.address) log(ref1["b"]?.owner?.address) ref1["a"]?.logOwnerAddress() @@ -5369,8 +5371,8 @@ func TestRuntimeResourceOwnerFieldUseDictionary(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - let ref1 = signer.borrow<&{String: Test.R}>(from: /storage/rs)! + prepare(signer: auth(Storage) &Account) { + let ref1 = signer.storage.borrow<&{String: Test.R}>(from: /storage/rs)! log(ref1["a"]?.owner?.address) log(ref1["b"]?.owner?.address) ref1["a"]?.logOwnerAddress() @@ -5500,8 +5502,8 @@ func TestRuntimeMetrics(t *testing.T) { import "imported1" transaction { - prepare(signer: AuthAccount) { - signer.save(generate(), to: /storage/foo) + prepare(signer: auth(Storage) &Account) { + signer.storage.save(generate(), to: /storage/foo) } execute {} } @@ -5511,8 +5513,8 @@ func TestRuntimeMetrics(t *testing.T) { import "imported2" transaction { - prepare(signer: AuthAccount) { - signer.load<[Int]>(from: getPath()) + prepare(signer: auth(Storage) &Account) { + signer.storage.load<[Int]>(from: getPath()) } execute {} } @@ -5661,7 +5663,7 @@ func TestRuntimeContractWriteback(t *testing.T) { init() { self.test = 1 } - + access(all) fun setTest(_ test: Int) { self.test = test } @@ -5675,7 +5677,7 @@ func TestRuntimeContractWriteback(t *testing.T) { transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { log(Test.test) } } @@ -5686,7 +5688,7 @@ func TestRuntimeContractWriteback(t *testing.T) { transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { Test.setTest(2) } } @@ -5920,8 +5922,8 @@ func TestRuntimeStorageWriteback(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - signer.save(<-Test.createR(), to: /storage/r) + prepare(signer: auth(Storage) &Account) { + signer.storage.save(<-Test.createR(), to: /storage/r) } } `), @@ -5959,8 +5961,8 @@ func TestRuntimeStorageWriteback(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - log(signer.borrow<&Test.R>(from: /storage/r)!.test) + prepare(signer: auth(Storage) &Account) { + log(signer.storage.borrow<&Test.R>(from: /storage/r)!.test) } } `) @@ -5985,8 +5987,8 @@ func TestRuntimeStorageWriteback(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - let r = signer.borrow<&Test.R>(from: /storage/r)! + prepare(signer: auth(Storage) &Account) { + let r = signer.storage.borrow<&Test.R>(from: /storage/r)! r.setTest(2) } } @@ -6134,7 +6136,7 @@ func TestRuntimeDeployCodeCaching(t *testing.T) { import HelloWorld from 0x%s transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { assert(HelloWorld.hello() == "Hello, World!") } } @@ -6142,8 +6144,8 @@ func TestRuntimeDeployCodeCaching(t *testing.T) { createAccountTx := []byte(` transaction { - prepare(signer: AuthAccount) { - AuthAccount(payer: signer) + prepare(signer: auth(BorrowValue) &Account) { + Account(payer: signer) } } `) @@ -6267,7 +6269,7 @@ func TestRuntimeUpdateCodeCaching(t *testing.T) { import HelloWorld from 0x%s transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { log(HelloWorld.hello()) } } @@ -6275,8 +6277,8 @@ func TestRuntimeUpdateCodeCaching(t *testing.T) { createAccountTx := []byte(` transaction { - prepare(signer: AuthAccount) { - AuthAccount(payer: signer) + prepare(signer: auth(BorrowValue) &Account) { + Account(payer: signer) } } `) @@ -6478,7 +6480,7 @@ func TestRuntimeProgramsHitForToplevelPrograms(t *testing.T) { import HelloWorld from 0x%s transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { assert(HelloWorld.hello() == "Hello, World!") } } @@ -6486,8 +6488,8 @@ func TestRuntimeProgramsHitForToplevelPrograms(t *testing.T) { createAccountTx := []byte(` transaction { - prepare(signer: AuthAccount) { - AuthAccount(payer: signer) + prepare(signer: auth(BorrowValue) &Account) { + Account(payer: signer) } } `) @@ -7019,20 +7021,20 @@ func TestRuntimePanics(t *testing.T) { } -func TestRuntimeInvalidContainerTypeConfusion(t *testing.T) { +func TestRuntimeAccountsInDictionary(t *testing.T) { t.Parallel() - t.Run("invalid: auth account used as public account", func(t *testing.T) { + t.Run("store auth account reference", func(t *testing.T) { t.Parallel() runtime := newTestInterpreterRuntime() script := []byte(` access(all) fun main() { - let dict: {Int: PublicAccount} = {} + let dict: {Int: &Account} = {} let ref = &dict as auth(Mutate) &{Int: AnyStruct} - ref[0] = getAuthAccount(0x01) as AnyStruct + ref[0] = getAuthAccount(0x01) as AnyStruct } `) @@ -7048,15 +7050,10 @@ func TestRuntimeInvalidContainerTypeConfusion(t *testing.T) { }, ) - RequireError(t, err) - - assertRuntimeErrorIsUserError(t, err) - - var typeErr interpreter.ContainerMutationError - require.ErrorAs(t, err, &typeErr) + require.NoError(t, err) }) - t.Run("invalid: public account used as auth account", func(t *testing.T) { + t.Run("invalid: public account reference stored as auth account reference", func(t *testing.T) { t.Parallel() @@ -7064,7 +7061,7 @@ func TestRuntimeInvalidContainerTypeConfusion(t *testing.T) { script := []byte(` access(all) fun main() { - let dict: {Int: AuthAccount} = {} + let dict: {Int: auth(Storage) &Account} = {} let ref = &dict as auth(Mutate) &{Int: AnyStruct} ref[0] = getAccount(0x01) as AnyStruct } @@ -7090,7 +7087,7 @@ func TestRuntimeInvalidContainerTypeConfusion(t *testing.T) { require.ErrorAs(t, err, &typeErr) }) - t.Run("valid: public account used as public account", func(t *testing.T) { + t.Run("public account reference storage as public account reference", func(t *testing.T) { t.Parallel() @@ -7098,7 +7095,7 @@ func TestRuntimeInvalidContainerTypeConfusion(t *testing.T) { script := []byte(` access(all) fun main() { - let dict: {Int: PublicAccount} = {} + let dict: {Int: &Account} = {} let ref = &dict as auth(Mutate) &{Int: AnyStruct} ref[0] = getAccount(0x01) as AnyStruct } @@ -7576,7 +7573,7 @@ func TestRuntimeComputationMetring(t *testing.T) { { name: "statement + functionInvocation + encoding", code: ` - acc.save("A quick brown fox jumps over the lazy dog", to:/storage/some_path) + acc.storage.save("A quick brown fox jumps over the lazy dog", to:/storage/some_path) `, ok: true, hits: 3, @@ -7592,7 +7589,7 @@ func TestRuntimeComputationMetring(t *testing.T) { fmt.Sprintf( ` transaction { - prepare(acc: AuthAccount) { + prepare(acc: auth(Storage) &Account) { %s } } @@ -7683,7 +7680,7 @@ func TestRuntimeImportAnyStruct(t *testing.T) { Script{ Source: []byte(` transaction(args: [AnyStruct]) { - prepare(signer: AuthAccount) {} + prepare(signer: &Account) {} } `), Arguments: [][]byte{ @@ -7895,8 +7892,8 @@ func TestRuntimeTypeMismatchErrorMessage(t *testing.T) { transaction { - prepare(acct: AuthAccount) { - acct.save(Foo.Bar(), to: /storage/bar) + prepare(acct: auth(Storage) &Account) { + acct.storage.save(Foo.Bar(), to: /storage/bar) } } `) @@ -7920,7 +7917,8 @@ func TestRuntimeTypeMismatchErrorMessage(t *testing.T) { import Foo from 0x2 access(all) fun main() { - getAuthAccount(0x1).borrow<&Foo.Bar>(from: /storage/bar) + getAuthAccount(0x1) + .storage.borrow<&Foo.Bar>(from: /storage/bar) } `) @@ -7948,8 +7946,8 @@ func TestRuntimeErrorExcerpts(t *testing.T) { script := []byte(` access(all) fun main(): Int { // fill lines so the error occurs on lines 9 and 10 - // - // + // + // // // let a = [1,2,3,4] @@ -7999,8 +7997,8 @@ func TestRuntimeErrorExcerptsMultiline(t *testing.T) { script := []byte(` access(all) fun main(): String { // fill lines so the error occurs on lines 9 and 10 - // - // + // + // // // let a = [1,2,3,4] @@ -8052,15 +8050,15 @@ func TestRuntimeAccountTypeEquality(t *testing.T) { script := []byte(` access(all) fun main(address: Address): AnyStruct { - let acct = getAuthAccount(address) + let acct = getAuthAccount(address) let path = /public/tmp - let cap = acct.capabilities.account.issue<&AuthAccount>() + let cap = acct.capabilities.account.issue<&Account>() acct.capabilities.publish(cap, at: path) - let capType = acct.capabilities.borrow<&AuthAccount>(path)!.getType() + let capType = acct.capabilities.borrow<&Account>(path)!.getType() - return Type() == capType + return Type() == capType } `) @@ -8249,7 +8247,7 @@ func TestRuntimeFlowEventTypes(t *testing.T) { ) } -func TestInvalidatedResourceUse(t *testing.T) { +func TestRuntimeInvalidatedResourceUse(t *testing.T) { t.Parallel() @@ -8440,7 +8438,7 @@ func TestInvalidatedResourceUse(t *testing.T) { } -func TestInvalidatedResourceUse2(t *testing.T) { +func TestRuntimeInvalidatedResourceUse2(t *testing.T) { t.Parallel() @@ -8674,7 +8672,7 @@ func TestRuntimeInvalidRecursiveTransferViaVariableDeclaration(t *testing.T) { destroy() { var t <- self.vaults[0] <- self.vaults // here is the problem destroy t - Test.account.save(<- self.x(), to: /storage/x42) + Test.account.storage.save(<- self.x(), to: /storage/x42) } } @@ -8695,7 +8693,7 @@ func TestRuntimeInvalidRecursiveTransferViaVariableDeclaration(t *testing.T) { transaction { - prepare(acct: AuthAccount) { + prepare(acct: &Account) { var holder <- Test.createHolder(<-[<-Test.dummy(), <-Test.dummy()]) destroy holder } @@ -8802,7 +8800,7 @@ func TestRuntimeInvalidRecursiveTransferViaFunctionArgument(t *testing.T) { transaction { - prepare(acct: AuthAccount) { + prepare(acct: &Account) { var holder <- Test.createHolder(<-[<-Test.dummy(), <-Test.dummy()]) destroy holder } @@ -9213,8 +9211,8 @@ func TestRuntimeWrappedErrorHandling(t *testing.T) { import Foo from 0x1 transaction { - prepare(signer: AuthAccount) { - signer.save(<- Foo.createR(), to: /storage/r) + prepare(signer: auth (Storage, Capabilities) &Account) { + signer.storage.save(<- Foo.createR(), to: /storage/r) let cap = signer.capabilities.storage.issue<&Foo.R>(/storage/r) signer.capabilities.publish(cap, at: /public/r) } @@ -9223,7 +9221,7 @@ func TestRuntimeWrappedErrorHandling(t *testing.T) { tx2 := []byte(` transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { let cap = signer.capabilities.get<&AnyStruct>(/public/r)! cap.check() } @@ -9399,8 +9397,8 @@ func BenchmarkRuntimeResourceTracking(b *testing.B) { import Foo from 0x1 transaction { - prepare(signer: AuthAccount) { - signer.save(<- Foo.getResourceArray(), to: /storage/r) + prepare(signer: &Account) { + signer.storage.save(<- Foo.getResourceArray(), to: /storage/r) } } `), @@ -9422,11 +9420,11 @@ func BenchmarkRuntimeResourceTracking(b *testing.B) { import Foo from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { // When the array is loaded from storage, all elements are also loaded. // So all moves of this resource will check for tracking of all elements aas well. - var array1 <- signer.load<@[Foo.R]>(from: /storage/r)! + var array1 <- signer.storage.load<@[Foo.R]>(from: /storage/r)! var array2 <- array1 var array3 <- array2 var array4 <- array3 @@ -9444,3 +9442,181 @@ func BenchmarkRuntimeResourceTracking(b *testing.B) { ) require.NoError(b, err) } + +func TestRuntimeTypesAndConversions(t *testing.T) { + t.Parallel() + + test := func(name string, semaType sema.Type) { + t.Run(name, func(t *testing.T) { + + t.Parallel() + + var staticType interpreter.StaticType + + t.Run("sema -> static", func(t *testing.T) { + staticType = interpreter.ConvertSemaToStaticType(nil, semaType) + require.NotNil(t, staticType) + }) + + if staticType != nil { + t.Run("static -> sema", func(t *testing.T) { + + t.Parallel() + + inter, err := interpreter.NewInterpreter(nil, nil, &interpreter.Config{}) + require.NoError(t, err) + + convertedSemaType, err := inter.ConvertStaticToSemaType(staticType) + require.NoError(t, err) + require.True(t, semaType.Equal(convertedSemaType)) + }) + } + + var cadenceType cadence.Type + + t.Run("sema -> cadence", func(t *testing.T) { + + cadenceType = ExportType(semaType, map[sema.TypeID]cadence.Type{}) + require.NotNil(t, cadenceType) + }) + + if cadenceType != nil { + + t.Run("cadence -> static", func(t *testing.T) { + + t.Parallel() + + convertedStaticType := ImportType(nil, cadenceType) + require.True(t, staticType.Equal(convertedStaticType)) + }) + } + }) + } + + for name, ty := range checker.AllBaseSemaTypes() { + test(name, ty) + } +} + +func TestRuntimeEventEmission(t *testing.T) { + + t.Parallel() + + t.Run("primitive", func(t *testing.T) { + t.Parallel() + + runtime := newTestInterpreterRuntime() + + script := []byte(` + access(all) + event TestEvent(ref: Int) + + access(all) + fun main() { + emit TestEvent(ref: 42) + } + `) + + var events []cadence.Event + + runtimeInterface := &testRuntimeInterface{ + storage: newTestLedger(nil, nil), + emitEvent: func(event cadence.Event) error { + events = append(events, event) + return nil + }, + } + + nextScriptLocation := newScriptLocationGenerator() + + location := nextScriptLocation() + + _, err := runtime.ExecuteScript( + Script{ + Source: script, + }, + Context{ + Interface: runtimeInterface, + Location: location, + }, + ) + require.NoError(t, err) + + require.Len(t, events, 1) + event := events[0] + + assert.EqualValues( + t, + location.TypeID(nil, "TestEvent"), + event.Type().ID(), + ) + + assert.Equal( + t, + []cadence.Value{ + cadence.NewInt(42), + }, + event.GetFieldValues(), + ) + + }) + + t.Run("reference", func(t *testing.T) { + t.Parallel() + + runtime := newTestInterpreterRuntime() + + script := []byte(` + access(all) + event TestEvent(ref: &Int) + + access(all) + fun main() { + emit TestEvent(ref: &42) + } + `) + + var events []cadence.Event + + runtimeInterface := &testRuntimeInterface{ + storage: newTestLedger(nil, nil), + emitEvent: func(event cadence.Event) error { + events = append(events, event) + return nil + }, + } + + nextScriptLocation := newScriptLocationGenerator() + + location := nextScriptLocation() + + _, err := runtime.ExecuteScript( + Script{ + Source: script, + }, + Context{ + Interface: runtimeInterface, + Location: location, + }, + ) + require.NoError(t, err) + + require.Len(t, events, 1) + event := events[0] + + assert.EqualValues( + t, + location.TypeID(nil, "TestEvent"), + event.Type().ID(), + ) + + assert.Equal( + t, + []cadence.Value{ + cadence.NewInt(42), + }, + event.GetFieldValues(), + ) + + }) +} diff --git a/runtime/sema/access.go b/runtime/sema/access.go index 553204159d..6f0e60c85c 100644 --- a/runtime/sema/access.go +++ b/runtime/sema/access.go @@ -21,6 +21,7 @@ package sema import ( "fmt" "strings" + "sync" "github.com/onflow/cadence/runtime/ast" "github.com/onflow/cadence/runtime/common" @@ -199,52 +200,54 @@ func (e EntitlementSetAccess) IsLessPermissiveThan(other Access) bool { } type EntitlementMapAccess struct { - Type *EntitlementMapType - domain EntitlementSetAccess - codomain EntitlementSetAccess - images map[*EntitlementType]*EntitlementOrderedSet + Type *EntitlementMapType + domain EntitlementSetAccess + domainOnce sync.Once + codomain EntitlementSetAccess + codomainOnce sync.Once + images sync.Map } -var _ Access = EntitlementMapAccess{} +var _ Access = &EntitlementMapAccess{} -func NewEntitlementMapAccess(mapType *EntitlementMapType) EntitlementMapAccess { - return EntitlementMapAccess{ +func NewEntitlementMapAccess(mapType *EntitlementMapType) *EntitlementMapAccess { + return &EntitlementMapAccess{ Type: mapType, - images: make(map[*EntitlementType]*EntitlementOrderedSet), + images: sync.Map{}, } } -func (EntitlementMapAccess) isAccess() {} +func (*EntitlementMapAccess) isAccess() {} -func (e EntitlementMapAccess) string(typeFormatter func(ty Type) string) string { +func (e *EntitlementMapAccess) string(typeFormatter func(ty Type) string) string { return typeFormatter(e.Type) } -func (a EntitlementMapAccess) Description() string { +func (a *EntitlementMapAccess) Description() string { return a.AccessKeyword() } -func (a EntitlementMapAccess) AccessKeyword() string { +func (a *EntitlementMapAccess) AccessKeyword() string { return a.string(func(ty Type) string { return ty.String() }) } -func (a EntitlementMapAccess) AuthKeyword() string { +func (a *EntitlementMapAccess) AuthKeyword() string { return fmt.Sprintf("auth(%s)", a.AccessKeyword()) } -func (e EntitlementMapAccess) Equal(other Access) bool { +func (e *EntitlementMapAccess) Equal(other Access) bool { switch otherAccess := other.(type) { - case EntitlementMapAccess: + case *EntitlementMapAccess: return e.Type.Equal(otherAccess.Type) } return false } -func (e EntitlementMapAccess) PermitsAccess(other Access) bool { +func (e *EntitlementMapAccess) PermitsAccess(other Access) bool { switch otherAccess := other.(type) { case PrimitiveAccess: return otherAccess == PrimitiveAccess(ast.AccessSelf) - case EntitlementMapAccess: + case *EntitlementMapAccess: return e.Type.Equal(otherAccess.Type) // if we are initializing a field that was declared with an entitlement-mapped reference type, // the type we are using to initialize that member must be fully authorized for the entire codomain @@ -277,11 +280,11 @@ func (e EntitlementMapAccess) PermitsAccess(other Access) bool { } } -func (e EntitlementMapAccess) IsLessPermissiveThan(other Access) bool { +func (e *EntitlementMapAccess) IsLessPermissiveThan(other Access) bool { switch otherAccess := other.(type) { case PrimitiveAccess: return ast.PrimitiveAccess(otherAccess) != ast.AccessSelf - case EntitlementMapAccess: + case *EntitlementMapAccess: // this should be false on equality return !e.Type.Equal(otherAccess.Type) default: @@ -289,62 +292,59 @@ func (e EntitlementMapAccess) IsLessPermissiveThan(other Access) bool { } } -func (e EntitlementMapAccess) Domain() EntitlementSetAccess { - if e.domain.Entitlements != nil { - return e.domain - } - - domain := common.MappedSliceWithNoDuplicates( - e.Type.Relations, - func(r EntitlementRelation) *EntitlementType { - return r.Input - }, - ) - e.domain = NewEntitlementSetAccess(domain, Conjunction) +func (e *EntitlementMapAccess) Domain() EntitlementSetAccess { + e.domainOnce.Do(func() { + domain := common.MappedSliceWithNoDuplicates( + e.Type.Relations, + func(r EntitlementRelation) *EntitlementType { + return r.Input + }, + ) + e.domain = NewEntitlementSetAccess(domain, Conjunction) + }) return e.domain } -func (e EntitlementMapAccess) Codomain() EntitlementSetAccess { - if e.codomain.Entitlements != nil { - return e.codomain - } - - codomain := common.MappedSliceWithNoDuplicates( - e.Type.Relations, - func(r EntitlementRelation) *EntitlementType { - return r.Output - }, - ) - e.codomain = NewEntitlementSetAccess(codomain, Conjunction) +func (e *EntitlementMapAccess) Codomain() EntitlementSetAccess { + e.codomainOnce.Do(func() { + codomain := common.MappedSliceWithNoDuplicates( + e.Type.Relations, + func(r EntitlementRelation) *EntitlementType { + return r.Output + }, + ) + e.codomain = NewEntitlementSetAccess(codomain, Conjunction) + }) return e.codomain } // produces the image set of a single entitlement through a map // the image set of one element is always a conjunction -func (e EntitlementMapAccess) entitlementImage(entitlement *EntitlementType) (output *EntitlementOrderedSet) { - image := e.images[entitlement] - if image != nil { - return image +func (e *EntitlementMapAccess) entitlementImage(entitlement *EntitlementType) *EntitlementOrderedSet { + image, ok := e.images.Load(entitlement) + + if ok { + return image.(*EntitlementOrderedSet) } - output = orderedmap.New[EntitlementOrderedSet](0) + imageMap := orderedmap.New[EntitlementOrderedSet](0) for _, relation := range e.Type.Relations { if relation.Input.Equal(entitlement) { - output.Set(relation.Output, struct{}{}) + imageMap.Set(relation.Output, struct{}{}) } } if e.Type.IncludesIdentity { - output.Set(entitlement, struct{}{}) + imageMap.Set(entitlement, struct{}{}) } - e.images[entitlement] = output - return + e.images.Store(entitlement, imageMap) + return imageMap } // Image applies all the entitlements in the `argumentAccess` to the function // defined by the map in `e`, producing a new entitlement set of the image of the // arguments. -func (e EntitlementMapAccess) Image(inputs Access, astRange func() ast.Range) (Access, error) { +func (e *EntitlementMapAccess) Image(inputs Access, astRange func() ast.Range) (Access, error) { switch inputs := inputs.(type) { // primitive access always passes trivially through the map @@ -427,3 +427,47 @@ func (a PrimitiveAccess) PermitsAccess(otherAccess Access) bool { // only access(self) access is guaranteed to be less permissive than entitlement-based access, but cannot appear in interfaces return ast.PrimitiveAccess(a) != ast.AccessSelf } + +func newEntitlementAccess( + entitlements []Type, + setKind EntitlementSetKind, +) Access { + + var setEntitlements []*EntitlementType + var mapEntitlement *EntitlementMapType + + for _, entitlement := range entitlements { + switch entitlement := entitlement.(type) { + case *EntitlementType: + if mapEntitlement != nil { + panic(errors.NewDefaultUserError("mixed entitlement types")) + } + + setEntitlements = append(setEntitlements, entitlement) + + case *EntitlementMapType: + if len(setEntitlements) > 0 { + panic(errors.NewDefaultUserError("mixed entitlement types")) + } + + if mapEntitlement != nil { + panic(errors.NewDefaultUserError("extra entitlement map type")) + } + + mapEntitlement = entitlement + + default: + panic(errors.NewDefaultUserError("invalid entitlement type: %s", entitlement)) + } + } + + if len(setEntitlements) > 0 { + return NewEntitlementSetAccess(setEntitlements, setKind) + } + + if mapEntitlement != nil { + return NewEntitlementMapAccess(mapEntitlement) + } + + panic(errors.NewDefaultUserError("neither map entitlement nor set entitlements given")) +} diff --git a/runtime/sema/access_test.go b/runtime/sema/access_test.go new file mode 100644 index 0000000000..c75611e3cc --- /dev/null +++ b/runtime/sema/access_test.go @@ -0,0 +1,180 @@ +/* + * Cadence - The resource-oriented smart contract programming language + * + * Copyright Dapper Labs, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package sema + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestNewEntitlementAccess(t *testing.T) { + + t.Parallel() + + t.Run("empty", func(t *testing.T) { + t.Parallel() + + assert.PanicsWithError(t, + "neither map entitlement nor set entitlements given", + func() { + newEntitlementAccess(nil, Conjunction) + }, + ) + }) + + t.Run("invalid", func(t *testing.T) { + t.Parallel() + + assert.PanicsWithError(t, + "invalid entitlement type: Void", + func() { + newEntitlementAccess([]Type{VoidType}, Conjunction) + }, + ) + }) + + t.Run("map + entitlement", func(t *testing.T) { + t.Parallel() + + assert.PanicsWithError(t, + "mixed entitlement types", + func() { + newEntitlementAccess( + []Type{ + IdentityType, + MutateType, + }, + Conjunction, + ) + }, + ) + }) + + t.Run("entitlement + map", func(t *testing.T) { + t.Parallel() + + assert.PanicsWithError(t, + "mixed entitlement types", + func() { + newEntitlementAccess( + []Type{ + MutateType, + IdentityType, + }, + Conjunction, + ) + }, + ) + }) + + t.Run("single entitlement", func(t *testing.T) { + t.Parallel() + + assert.Equal(t, + NewEntitlementSetAccess( + []*EntitlementType{ + MutateType, + }, + Conjunction, + ), + newEntitlementAccess( + []Type{ + MutateType, + }, + Conjunction, + ), + ) + }) + + t.Run("two entitlements, conjunction", func(t *testing.T) { + t.Parallel() + + assert.Equal(t, + NewEntitlementSetAccess( + []*EntitlementType{ + MutateType, + InsertType, + }, + Conjunction, + ), + newEntitlementAccess( + []Type{ + MutateType, + InsertType, + }, + Conjunction, + ), + ) + }) + + t.Run("two entitlements, disjunction", func(t *testing.T) { + t.Parallel() + + assert.Equal(t, + NewEntitlementSetAccess( + []*EntitlementType{ + MutateType, + InsertType, + }, + Disjunction, + ), + newEntitlementAccess( + []Type{ + MutateType, + InsertType, + }, + Disjunction, + ), + ) + }) + + t.Run("single map", func(t *testing.T) { + t.Parallel() + + assert.Equal(t, + NewEntitlementMapAccess( + IdentityType, + ), + newEntitlementAccess( + []Type{ + IdentityType, + }, + Conjunction, + ), + ) + }) + + t.Run("two maps", func(t *testing.T) { + t.Parallel() + + assert.PanicsWithError(t, + "extra entitlement map type", + func() { + newEntitlementAccess( + []Type{ + IdentityType, + AccountMappingType, + }, + Conjunction, + ) + }, + ) + }) +} diff --git a/runtime/sema/account.cdc b/runtime/sema/account.cdc new file mode 100644 index 0000000000..d7e9aa83d1 --- /dev/null +++ b/runtime/sema/account.cdc @@ -0,0 +1,521 @@ +access(all) +struct Account { + + /// The address of the account. + access(all) + let address: Address + + /// The FLOW balance of the default vault of this account. + access(all) + let balance: UFix64 + + /// The FLOW balance of the default vault of this account that is available to be moved. + access(all) + let availableBalance: UFix64 + + /// The storage of the account. + access(AccountMapping) + let storage: Account.Storage + + /// The contracts deployed to the account. + access(AccountMapping) + let contracts: Account.Contracts + + /// The keys assigned to the account. + access(AccountMapping) + let keys: Account.Keys + + /// The inbox allows bootstrapping (sending and receiving) capabilities. + access(AccountMapping) + let inbox: Account.Inbox + + /// The capabilities of the account. + access(AccountMapping) + let capabilities: Account.Capabilities + + access(all) + struct Storage { + /// The current amount of storage used by the account in bytes. + access(all) + let used: UInt64 + + /// The storage capacity of the account in bytes. + access(all) + let capacity: UInt64 + + /// All public paths of this account. + access(all) + let publicPaths: [PublicPath] + + /// All storage paths of this account. + access(all) + let storagePaths: [StoragePath] + + /// Saves the given object into the account's storage at the given path. + /// + /// Resources are moved into storage, and structures are copied. + /// + /// If there is already an object stored under the given path, the program aborts. + /// + /// The path must be a storage path, i.e., only the domain `storage` is allowed. + access(Storage | SaveValue) + fun save(_ value: T, to: StoragePath) + + /// Reads the type of an object from the account's storage which is stored under the given path, + /// or nil if no object is stored under the given path. + /// + /// If there is an object stored, the type of the object is returned without modifying the stored object. + /// + /// The path must be a storage path, i.e., only the domain `storage` is allowed. + access(all) + view fun type(at path: StoragePath): Type? + + /// Loads an object from the account's storage which is stored under the given path, + /// or nil if no object is stored under the given path. + /// + /// If there is an object stored, + /// the stored resource or structure is moved out of storage and returned as an optional. + /// + /// When the function returns, the storage no longer contains an object under the given path. + /// + /// The given type must be a supertype of the type of the loaded object. + /// If it is not, the function panics. + /// + /// The given type must not necessarily be exactly the same as the type of the loaded object. + /// + /// The path must be a storage path, i.e., only the domain `storage` is allowed. + access(Storage | LoadValue) + fun load(from: StoragePath): T? + + /// Returns a copy of a structure stored in account storage under the given path, + /// without removing it from storage, + /// or nil if no object is stored under the given path. + /// + /// If there is a structure stored, it is copied. + /// The structure stays stored in storage after the function returns. + /// + /// The given type must be a supertype of the type of the copied structure. + /// If it is not, the function panics. + /// + /// The given type must not necessarily be exactly the same as the type of the copied structure. + /// + /// The path must be a storage path, i.e., only the domain `storage` is allowed. + access(all) + view fun copy(from: StoragePath): T? + + /// Returns true if the object in account storage under the given path satisfies the given type, + /// i.e. could be borrowed using the given type. + /// + /// The given type must not necessarily be exactly the same as the type of the borrowed object. + /// + /// The path must be a storage path, i.e., only the domain `storage` is allowed. + access(all) + view fun check(from: StoragePath): Bool + + /// Returns a reference to an object in storage without removing it from storage. + /// + /// If no object is stored under the given path, the function returns nil. + /// If there is an object stored, a reference is returned as an optional, + /// provided it can be borrowed using the given type. + /// If the stored object cannot be borrowed using the given type, the function panics. + /// + /// The given type must not necessarily be exactly the same as the type of the borrowed object. + /// + /// The path must be a storage path, i.e., only the domain `storage` is allowed + access(Storage | BorrowValue) + view fun borrow(from: StoragePath): T? + + /// Iterate over all the public paths of an account, + /// passing each path and type in turn to the provided callback function. + /// + /// The callback function takes two arguments: + /// 1. The path of the stored object + /// 2. The runtime type of that object + /// + /// Iteration is stopped early if the callback function returns `false`. + /// + /// The order of iteration is undefined. + /// + /// If an object is stored under a new public path, + /// or an existing object is removed from a public path, + /// then the callback must stop iteration by returning false. + /// Otherwise, iteration aborts. + /// + access(all) + fun forEachPublic(_ function: fun(PublicPath, Type): Bool) + + /// Iterate over all the stored paths of an account, + /// passing each path and type in turn to the provided callback function. + /// + /// The callback function takes two arguments: + /// 1. The path of the stored object + /// 2. The runtime type of that object + /// + /// Iteration is stopped early if the callback function returns `false`. + /// + /// If an object is stored under a new storage path, + /// or an existing object is removed from a storage path, + /// then the callback must stop iteration by returning false. + /// Otherwise, iteration aborts. + access(all) + fun forEachStored(_ function: fun (StoragePath, Type): Bool) + } + + access(all) + struct Contracts { + + /// The names of all contracts deployed in the account. + access(all) + let names: [String] + + /// Adds the given contract to the account. + /// + /// The `code` parameter is the UTF-8 encoded representation of the source code. + /// The code must contain exactly one contract or contract interface, + /// which must have the same name as the `name` parameter. + /// + /// All additional arguments that are given are passed further to the initializer + /// of the contract that is being deployed. + /// + /// The function fails if a contract/contract interface with the given name already exists in the account, + /// if the given code does not declare exactly one contract or contract interface, + /// or if the given name does not match the name of the contract/contract interface declaration in the code. + /// + /// Returns the deployed contract. + access(Contracts | AddContract) + fun add( + name: String, + code: [UInt8] + ): DeployedContract + + /// Updates the code for the contract/contract interface in the account. + /// + /// The `code` parameter is the UTF-8 encoded representation of the source code. + /// The code must contain exactly one contract or contract interface, + /// which must have the same name as the `name` parameter. + /// + /// Does **not** run the initializer of the contract/contract interface again. + /// The contract instance in the world state stays as is. + /// + /// Fails if no contract/contract interface with the given name exists in the account, + /// if the given code does not declare exactly one contract or contract interface, + /// or if the given name does not match the name of the contract/contract interface declaration in the code. + /// + /// Returns the deployed contract for the updated contract. + access(Contracts | UpdateContract) + fun update(name: String, code: [UInt8]): DeployedContract + + /// Returns the deployed contract for the contract/contract interface with the given name in the account, if any. + /// + /// Returns nil if no contract/contract interface with the given name exists in the account. + access(all) + view fun get(name: String): DeployedContract? + + /// Removes the contract/contract interface from the account which has the given name, if any. + /// + /// Returns the removed deployed contract, if any. + /// + /// Returns nil if no contract/contract interface with the given name exists in the account. + access(Contracts | RemoveContract) + fun remove(name: String): DeployedContract? + + /// Returns a reference of the given type to the contract with the given name in the account, if any. + /// + /// Returns nil if no contract with the given name exists in the account, + /// or if the contract does not conform to the given type. + access(all) + view fun borrow(name: String): T? + } + + access(all) + struct Keys { + + /// Adds a new key with the given hashing algorithm and a weight. + /// + /// Returns the added key. + access(Keys | AddKey) + fun add( + publicKey: PublicKey, + hashAlgorithm: HashAlgorithm, + weight: UFix64 + ): AccountKey + + /// Returns the key at the given index, if it exists, or nil otherwise. + /// + /// Revoked keys are always returned, but they have `isRevoked` field set to true. + access(all) + view fun get(keyIndex: Int): AccountKey? + + /// Marks the key at the given index revoked, but does not delete it. + /// + /// Returns the revoked key if it exists, or nil otherwise. + access(Keys | RevokeKey) + fun revoke(keyIndex: Int): AccountKey? + + /// Iterate over all unrevoked keys in this account, + /// passing each key in turn to the provided function. + /// + /// Iteration is stopped early if the function returns `false`. + /// + /// The order of iteration is undefined. + access(all) + fun forEach(_ function: fun(AccountKey): Bool) + + /// The total number of unrevoked keys in this account. + access(all) + let count: UInt64 + } + + access(all) + struct Inbox { + + /// Publishes a new Capability under the given name, + /// to be claimed by the specified recipient. + access(Inbox | PublishInboxCapability) + fun publish(_ value: Capability, name: String, recipient: Address) + + /// Unpublishes a Capability previously published by this account. + /// + /// Returns `nil` if no Capability is published under the given name. + /// + /// Errors if the Capability under that name does not match the provided type. + access(Inbox | UnpublishInboxCapability) + fun unpublish(_ name: String): Capability? + + /// Claims a Capability previously published by the specified provider. + /// + /// Returns `nil` if no Capability is published under the given name, + /// or if this account is not its intended recipient. + /// + /// Errors if the Capability under that name does not match the provided type. + access(Inbox | ClaimInboxCapability) + fun claim(_ name: String, provider: Address): Capability? + } + + access(all) + struct Capabilities { + + /// The storage capabilities of the account. + access(CapabilitiesMapping) + let storage: Account.StorageCapabilities + + /// The account capabilities of the account. + access(CapabilitiesMapping) + let account: Account.AccountCapabilities + + /// Returns the capability at the given public path. + /// Returns nil if the capability does not exist, + /// or if the given type is not a supertype of the capability's borrow type. + access(all) + view fun get(_ path: PublicPath): Capability? + + /// Borrows the capability at the given public path. + /// Returns nil if the capability does not exist, or cannot be borrowed using the given type. + /// The function is equivalent to `get(path)?.borrow()`. + access(all) + view fun borrow(_ path: PublicPath): T? + + /// Publish the capability at the given public path. + /// + /// If there is already a capability published under the given path, the program aborts. + /// + /// The path must be a public path, i.e., only the domain `public` is allowed. + access(Capabilities | PublishCapability) + fun publish(_ capability: Capability, at: PublicPath) + + /// Unpublish the capability published at the given path. + /// + /// Returns the capability if one was published at the path. + /// Returns nil if no capability was published at the path. + access(Capabilities | UnpublishCapability) + fun unpublish(_ path: PublicPath): Capability? + } + + access(all) + struct StorageCapabilities { + + /// Get the storage capability controller for the capability with the specified ID. + /// + /// Returns nil if the ID does not reference an existing storage capability. + access(Capabilities | StorageCapabilities | GetStorageCapabilityController) + view fun getController(byCapabilityID: UInt64): &StorageCapabilityController? + + /// Get all storage capability controllers for capabilities that target this storage path + access(Capabilities | StorageCapabilities | GetStorageCapabilityController) + view fun getControllers(forPath: StoragePath): [&StorageCapabilityController] + + /// Iterate over all storage capability controllers for capabilities that target this storage path, + /// passing a reference to each controller to the provided callback function. + /// + /// Iteration is stopped early if the callback function returns `false`. + /// + /// If a new storage capability controller is issued for the path, + /// an existing storage capability controller for the path is deleted, + /// or a storage capability controller is retargeted from or to the path, + /// then the callback must stop iteration by returning false. + /// Otherwise, iteration aborts. + access(Capabilities | StorageCapabilities | GetStorageCapabilityController) + fun forEachController( + forPath: StoragePath, + _ function: fun(&StorageCapabilityController): Bool + ) + + /// Issue/create a new storage capability. + access(Capabilities | StorageCapabilities | IssueStorageCapabilityController) + fun issue(_ path: StoragePath): Capability + } + + access(all) + struct AccountCapabilities { + /// Get capability controller for capability with the specified ID. + /// + /// Returns nil if the ID does not reference an existing account capability. + access(Capabilities | AccountCapabilities | GetAccountCapabilityController) + view fun getController(byCapabilityID: UInt64): &AccountCapabilityController? + + /// Get all capability controllers for all account capabilities. + access(Capabilities | AccountCapabilities | GetAccountCapabilityController) + view fun getControllers(): [&AccountCapabilityController] + + /// Iterate over all account capability controllers for all account capabilities, + /// passing a reference to each controller to the provided callback function. + /// + /// Iteration is stopped early if the callback function returns `false`. + /// + /// If a new account capability controller is issued for the account, + /// or an existing account capability controller for the account is deleted, + /// then the callback must stop iteration by returning false. + /// Otherwise, iteration aborts. + access(Capabilities | AccountCapabilities | GetAccountCapabilityController) + fun forEachController(_ function: fun(&AccountCapabilityController): Bool) + + /// Issue/create a new account capability. + access(Capabilities | AccountCapabilities | IssueAccountCapabilityController) + fun issue(): Capability + } +} + +/* Storage entitlements */ + +entitlement Storage + +entitlement SaveValue +entitlement LoadValue +entitlement BorrowValue + +/* Contract entitlements */ + +entitlement Contracts + +entitlement AddContract +entitlement UpdateContract +entitlement RemoveContract + +/* Key entitlements */ + +entitlement Keys + +entitlement AddKey +entitlement RevokeKey + +/* Inbox entitlements */ + +entitlement Inbox + +entitlement PublishInboxCapability +entitlement UnpublishInboxCapability +entitlement ClaimInboxCapability + +/* Capability entitlements */ + +entitlement Capabilities + +entitlement StorageCapabilities +entitlement AccountCapabilities + +entitlement PublishCapability +entitlement UnpublishCapability + +entitlement GetStorageCapabilityController +entitlement IssueStorageCapabilityController + +entitlement GetAccountCapabilityController +entitlement IssueAccountCapabilityController + +/* Entitlement mappings */ + +entitlement mapping AccountMapping { + // TODO: include Identity + + Storage -> Storage + Contracts -> Contracts + Keys -> Keys + Inbox -> Inbox + Capabilities -> Capabilities + + SaveValue -> SaveValue + LoadValue -> LoadValue + BorrowValue -> BorrowValue + + AddContract -> AddContract + UpdateContract -> UpdateContract + RemoveContract -> RemoveContract + + AddKey -> AddKey + RevokeKey -> RevokeKey + + PublishInboxCapability -> PublishInboxCapability + UnpublishInboxCapability -> UnpublishInboxCapability + + StorageCapabilities -> StorageCapabilities + AccountCapabilities -> AccountCapabilities + + GetStorageCapabilityController -> GetStorageCapabilityController + IssueStorageCapabilityController -> IssueStorageCapabilityController + + GetAccountCapabilityController -> GetAccountCapabilityController + IssueAccountCapabilityController -> IssueAccountCapabilityController + + // --- + + Storage -> SaveValue + Storage -> LoadValue + Storage -> BorrowValue + + Contracts -> AddContract + Contracts -> UpdateContract + Contracts -> RemoveContract + + Keys -> AddKey + Keys -> RevokeKey + + Inbox -> PublishInboxCapability + Inbox -> UnpublishInboxCapability + Inbox -> ClaimInboxCapability + + Capabilities -> StorageCapabilities + Capabilities -> AccountCapabilities +} + +entitlement mapping CapabilitiesMapping { + // TODO: include Identity + + Capabilities -> Capabilities + + StorageCapabilities -> StorageCapabilities + AccountCapabilities -> AccountCapabilities + + GetStorageCapabilityController -> GetStorageCapabilityController + IssueStorageCapabilityController -> IssueStorageCapabilityController + + GetAccountCapabilityController -> GetAccountCapabilityController + IssueAccountCapabilityController -> IssueAccountCapabilityController + + // --- + + StorageCapabilities -> GetStorageCapabilityController + StorageCapabilities -> IssueStorageCapabilityController + + AccountCapabilities -> GetAccountCapabilityController + AccountCapabilities -> IssueAccountCapabilityController +} diff --git a/runtime/sema/account.gen.go b/runtime/sema/account.gen.go new file mode 100644 index 0000000000..f67d7e18a8 --- /dev/null +++ b/runtime/sema/account.gen.go @@ -0,0 +1,2175 @@ +// Code generated from account.cdc. DO NOT EDIT. +/* + * Cadence - The resource-oriented smart contract programming language + * + * Copyright Dapper Labs, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package sema + +import ( + "github.com/onflow/cadence/runtime/ast" + "github.com/onflow/cadence/runtime/common" +) + +const AccountTypeAddressFieldName = "address" + +var AccountTypeAddressFieldType = TheAddressType + +const AccountTypeAddressFieldDocString = ` +The address of the account. +` + +const AccountTypeBalanceFieldName = "balance" + +var AccountTypeBalanceFieldType = UFix64Type + +const AccountTypeBalanceFieldDocString = ` +The FLOW balance of the default vault of this account. +` + +const AccountTypeAvailableBalanceFieldName = "availableBalance" + +var AccountTypeAvailableBalanceFieldType = UFix64Type + +const AccountTypeAvailableBalanceFieldDocString = ` +The FLOW balance of the default vault of this account that is available to be moved. +` + +const AccountTypeStorageFieldName = "storage" + +var AccountTypeStorageFieldType = Account_StorageType + +const AccountTypeStorageFieldDocString = ` +The storage of the account. +` + +const AccountTypeContractsFieldName = "contracts" + +var AccountTypeContractsFieldType = Account_ContractsType + +const AccountTypeContractsFieldDocString = ` +The contracts deployed to the account. +` + +const AccountTypeKeysFieldName = "keys" + +var AccountTypeKeysFieldType = Account_KeysType + +const AccountTypeKeysFieldDocString = ` +The keys assigned to the account. +` + +const AccountTypeInboxFieldName = "inbox" + +var AccountTypeInboxFieldType = Account_InboxType + +const AccountTypeInboxFieldDocString = ` +The inbox allows bootstrapping (sending and receiving) capabilities. +` + +const AccountTypeCapabilitiesFieldName = "capabilities" + +var AccountTypeCapabilitiesFieldType = Account_CapabilitiesType + +const AccountTypeCapabilitiesFieldDocString = ` +The capabilities of the account. +` + +const Account_StorageTypeUsedFieldName = "used" + +var Account_StorageTypeUsedFieldType = UInt64Type + +const Account_StorageTypeUsedFieldDocString = ` +The current amount of storage used by the account in bytes. +` + +const Account_StorageTypeCapacityFieldName = "capacity" + +var Account_StorageTypeCapacityFieldType = UInt64Type + +const Account_StorageTypeCapacityFieldDocString = ` +The storage capacity of the account in bytes. +` + +const Account_StorageTypePublicPathsFieldName = "publicPaths" + +var Account_StorageTypePublicPathsFieldType = &VariableSizedType{ + Type: PublicPathType, +} + +const Account_StorageTypePublicPathsFieldDocString = ` +All public paths of this account. +` + +const Account_StorageTypeStoragePathsFieldName = "storagePaths" + +var Account_StorageTypeStoragePathsFieldType = &VariableSizedType{ + Type: StoragePathType, +} + +const Account_StorageTypeStoragePathsFieldDocString = ` +All storage paths of this account. +` + +const Account_StorageTypeSaveFunctionName = "save" + +var Account_StorageTypeSaveFunctionTypeParameterT = &TypeParameter{ + Name: "T", + TypeBound: StorableType, +} + +var Account_StorageTypeSaveFunctionType = &FunctionType{ + TypeParameters: []*TypeParameter{ + Account_StorageTypeSaveFunctionTypeParameterT, + }, + Parameters: []Parameter{ + { + Label: ArgumentLabelNotRequired, + Identifier: "value", + TypeAnnotation: NewTypeAnnotation(&GenericType{ + TypeParameter: Account_StorageTypeSaveFunctionTypeParameterT, + }), + }, + { + Identifier: "to", + TypeAnnotation: NewTypeAnnotation(StoragePathType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + VoidType, + ), +} + +const Account_StorageTypeSaveFunctionDocString = ` +Saves the given object into the account's storage at the given path. + +Resources are moved into storage, and structures are copied. + +If there is already an object stored under the given path, the program aborts. + +The path must be a storage path, i.e., only the domain ` + "`storage`" + ` is allowed. +` + +const Account_StorageTypeTypeFunctionName = "type" + +var Account_StorageTypeTypeFunctionType = &FunctionType{ + Purity: FunctionPurityView, + Parameters: []Parameter{ + { + Label: "at", + Identifier: "path", + TypeAnnotation: NewTypeAnnotation(StoragePathType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + &OptionalType{ + Type: MetaType, + }, + ), +} + +const Account_StorageTypeTypeFunctionDocString = ` +Reads the type of an object from the account's storage which is stored under the given path, +or nil if no object is stored under the given path. + +If there is an object stored, the type of the object is returned without modifying the stored object. + +The path must be a storage path, i.e., only the domain ` + "`storage`" + ` is allowed. +` + +const Account_StorageTypeLoadFunctionName = "load" + +var Account_StorageTypeLoadFunctionTypeParameterT = &TypeParameter{ + Name: "T", + TypeBound: StorableType, +} + +var Account_StorageTypeLoadFunctionType = &FunctionType{ + TypeParameters: []*TypeParameter{ + Account_StorageTypeLoadFunctionTypeParameterT, + }, + Parameters: []Parameter{ + { + Identifier: "from", + TypeAnnotation: NewTypeAnnotation(StoragePathType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + &OptionalType{ + Type: &GenericType{ + TypeParameter: Account_StorageTypeLoadFunctionTypeParameterT, + }, + }, + ), +} + +const Account_StorageTypeLoadFunctionDocString = ` +Loads an object from the account's storage which is stored under the given path, +or nil if no object is stored under the given path. + +If there is an object stored, +the stored resource or structure is moved out of storage and returned as an optional. + +When the function returns, the storage no longer contains an object under the given path. + +The given type must be a supertype of the type of the loaded object. +If it is not, the function panics. + +The given type must not necessarily be exactly the same as the type of the loaded object. + +The path must be a storage path, i.e., only the domain ` + "`storage`" + ` is allowed. +` + +const Account_StorageTypeCopyFunctionName = "copy" + +var Account_StorageTypeCopyFunctionTypeParameterT = &TypeParameter{ + Name: "T", + TypeBound: AnyStructType, +} + +var Account_StorageTypeCopyFunctionType = &FunctionType{ + Purity: FunctionPurityView, + TypeParameters: []*TypeParameter{ + Account_StorageTypeCopyFunctionTypeParameterT, + }, + Parameters: []Parameter{ + { + Identifier: "from", + TypeAnnotation: NewTypeAnnotation(StoragePathType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + &OptionalType{ + Type: &GenericType{ + TypeParameter: Account_StorageTypeCopyFunctionTypeParameterT, + }, + }, + ), +} + +const Account_StorageTypeCopyFunctionDocString = ` +Returns a copy of a structure stored in account storage under the given path, +without removing it from storage, +or nil if no object is stored under the given path. + +If there is a structure stored, it is copied. +The structure stays stored in storage after the function returns. + +The given type must be a supertype of the type of the copied structure. +If it is not, the function panics. + +The given type must not necessarily be exactly the same as the type of the copied structure. + +The path must be a storage path, i.e., only the domain ` + "`storage`" + ` is allowed. +` + +const Account_StorageTypeCheckFunctionName = "check" + +var Account_StorageTypeCheckFunctionTypeParameterT = &TypeParameter{ + Name: "T", + TypeBound: AnyType, +} + +var Account_StorageTypeCheckFunctionType = &FunctionType{ + Purity: FunctionPurityView, + TypeParameters: []*TypeParameter{ + Account_StorageTypeCheckFunctionTypeParameterT, + }, + Parameters: []Parameter{ + { + Identifier: "from", + TypeAnnotation: NewTypeAnnotation(StoragePathType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + BoolType, + ), +} + +const Account_StorageTypeCheckFunctionDocString = ` +Returns true if the object in account storage under the given path satisfies the given type, +i.e. could be borrowed using the given type. + +The given type must not necessarily be exactly the same as the type of the borrowed object. + +The path must be a storage path, i.e., only the domain ` + "`storage`" + ` is allowed. +` + +const Account_StorageTypeBorrowFunctionName = "borrow" + +var Account_StorageTypeBorrowFunctionTypeParameterT = &TypeParameter{ + Name: "T", + TypeBound: &ReferenceType{ + Type: AnyType, + Authorization: UnauthorizedAccess, + }, +} + +var Account_StorageTypeBorrowFunctionType = &FunctionType{ + Purity: FunctionPurityView, + TypeParameters: []*TypeParameter{ + Account_StorageTypeBorrowFunctionTypeParameterT, + }, + Parameters: []Parameter{ + { + Identifier: "from", + TypeAnnotation: NewTypeAnnotation(StoragePathType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + &OptionalType{ + Type: &GenericType{ + TypeParameter: Account_StorageTypeBorrowFunctionTypeParameterT, + }, + }, + ), +} + +const Account_StorageTypeBorrowFunctionDocString = ` +Returns a reference to an object in storage without removing it from storage. + +If no object is stored under the given path, the function returns nil. +If there is an object stored, a reference is returned as an optional, +provided it can be borrowed using the given type. +If the stored object cannot be borrowed using the given type, the function panics. + +The given type must not necessarily be exactly the same as the type of the borrowed object. + +The path must be a storage path, i.e., only the domain ` + "`storage`" + ` is allowed +` + +const Account_StorageTypeForEachPublicFunctionName = "forEachPublic" + +var Account_StorageTypeForEachPublicFunctionType = &FunctionType{ + Parameters: []Parameter{ + { + Label: ArgumentLabelNotRequired, + Identifier: "function", + TypeAnnotation: NewTypeAnnotation(&FunctionType{ + Parameters: []Parameter{ + { + TypeAnnotation: NewTypeAnnotation(PublicPathType), + }, + { + TypeAnnotation: NewTypeAnnotation(MetaType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + BoolType, + ), + }), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + VoidType, + ), +} + +const Account_StorageTypeForEachPublicFunctionDocString = ` +Iterate over all the public paths of an account, +passing each path and type in turn to the provided callback function. + +The callback function takes two arguments: +1. The path of the stored object +2. The runtime type of that object + +Iteration is stopped early if the callback function returns ` + "`false`" + `. + +The order of iteration is undefined. + +If an object is stored under a new public path, +or an existing object is removed from a public path, +then the callback must stop iteration by returning false. +Otherwise, iteration aborts. +` + +const Account_StorageTypeForEachStoredFunctionName = "forEachStored" + +var Account_StorageTypeForEachStoredFunctionType = &FunctionType{ + Parameters: []Parameter{ + { + Label: ArgumentLabelNotRequired, + Identifier: "function", + TypeAnnotation: NewTypeAnnotation(&FunctionType{ + Parameters: []Parameter{ + { + TypeAnnotation: NewTypeAnnotation(StoragePathType), + }, + { + TypeAnnotation: NewTypeAnnotation(MetaType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + BoolType, + ), + }), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + VoidType, + ), +} + +const Account_StorageTypeForEachStoredFunctionDocString = ` +Iterate over all the stored paths of an account, +passing each path and type in turn to the provided callback function. + +The callback function takes two arguments: +1. The path of the stored object +2. The runtime type of that object + +Iteration is stopped early if the callback function returns ` + "`false`" + `. + +If an object is stored under a new storage path, +or an existing object is removed from a storage path, +then the callback must stop iteration by returning false. +Otherwise, iteration aborts. +` + +const Account_StorageTypeName = "Storage" + +var Account_StorageType = func() *CompositeType { + var t = &CompositeType{ + Identifier: Account_StorageTypeName, + Kind: common.CompositeKindStructure, + importable: false, + hasComputedMembers: true, + } + + return t +}() + +func init() { + var members = []*Member{ + NewUnmeteredFieldMember( + Account_StorageType, + PrimitiveAccess(ast.AccessAll), + ast.VariableKindConstant, + Account_StorageTypeUsedFieldName, + Account_StorageTypeUsedFieldType, + Account_StorageTypeUsedFieldDocString, + ), + NewUnmeteredFieldMember( + Account_StorageType, + PrimitiveAccess(ast.AccessAll), + ast.VariableKindConstant, + Account_StorageTypeCapacityFieldName, + Account_StorageTypeCapacityFieldType, + Account_StorageTypeCapacityFieldDocString, + ), + NewUnmeteredFieldMember( + Account_StorageType, + PrimitiveAccess(ast.AccessAll), + ast.VariableKindConstant, + Account_StorageTypePublicPathsFieldName, + Account_StorageTypePublicPathsFieldType, + Account_StorageTypePublicPathsFieldDocString, + ), + NewUnmeteredFieldMember( + Account_StorageType, + PrimitiveAccess(ast.AccessAll), + ast.VariableKindConstant, + Account_StorageTypeStoragePathsFieldName, + Account_StorageTypeStoragePathsFieldType, + Account_StorageTypeStoragePathsFieldDocString, + ), + NewUnmeteredFunctionMember( + Account_StorageType, + newEntitlementAccess( + []Type{StorageType, SaveValueType}, + Disjunction, + ), + Account_StorageTypeSaveFunctionName, + Account_StorageTypeSaveFunctionType, + Account_StorageTypeSaveFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_StorageType, + PrimitiveAccess(ast.AccessAll), + Account_StorageTypeTypeFunctionName, + Account_StorageTypeTypeFunctionType, + Account_StorageTypeTypeFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_StorageType, + newEntitlementAccess( + []Type{StorageType, LoadValueType}, + Disjunction, + ), + Account_StorageTypeLoadFunctionName, + Account_StorageTypeLoadFunctionType, + Account_StorageTypeLoadFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_StorageType, + PrimitiveAccess(ast.AccessAll), + Account_StorageTypeCopyFunctionName, + Account_StorageTypeCopyFunctionType, + Account_StorageTypeCopyFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_StorageType, + PrimitiveAccess(ast.AccessAll), + Account_StorageTypeCheckFunctionName, + Account_StorageTypeCheckFunctionType, + Account_StorageTypeCheckFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_StorageType, + newEntitlementAccess( + []Type{StorageType, BorrowValueType}, + Disjunction, + ), + Account_StorageTypeBorrowFunctionName, + Account_StorageTypeBorrowFunctionType, + Account_StorageTypeBorrowFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_StorageType, + PrimitiveAccess(ast.AccessAll), + Account_StorageTypeForEachPublicFunctionName, + Account_StorageTypeForEachPublicFunctionType, + Account_StorageTypeForEachPublicFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_StorageType, + PrimitiveAccess(ast.AccessAll), + Account_StorageTypeForEachStoredFunctionName, + Account_StorageTypeForEachStoredFunctionType, + Account_StorageTypeForEachStoredFunctionDocString, + ), + } + + Account_StorageType.Members = MembersAsMap(members) + Account_StorageType.Fields = MembersFieldNames(members) +} + +const Account_ContractsTypeNamesFieldName = "names" + +var Account_ContractsTypeNamesFieldType = &VariableSizedType{ + Type: StringType, +} + +const Account_ContractsTypeNamesFieldDocString = ` +The names of all contracts deployed in the account. +` + +const Account_ContractsTypeAddFunctionName = "add" + +var Account_ContractsTypeAddFunctionType = &FunctionType{ + Parameters: []Parameter{ + { + Identifier: "name", + TypeAnnotation: NewTypeAnnotation(StringType), + }, + { + Identifier: "code", + TypeAnnotation: NewTypeAnnotation(&VariableSizedType{ + Type: UInt8Type, + }), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + DeployedContractType, + ), +} + +const Account_ContractsTypeAddFunctionDocString = ` +Adds the given contract to the account. + +The ` + "`code`" + ` parameter is the UTF-8 encoded representation of the source code. +The code must contain exactly one contract or contract interface, +which must have the same name as the ` + "`name`" + ` parameter. + +All additional arguments that are given are passed further to the initializer +of the contract that is being deployed. + +The function fails if a contract/contract interface with the given name already exists in the account, +if the given code does not declare exactly one contract or contract interface, +or if the given name does not match the name of the contract/contract interface declaration in the code. + +Returns the deployed contract. +` + +const Account_ContractsTypeUpdateFunctionName = "update" + +var Account_ContractsTypeUpdateFunctionType = &FunctionType{ + Parameters: []Parameter{ + { + Identifier: "name", + TypeAnnotation: NewTypeAnnotation(StringType), + }, + { + Identifier: "code", + TypeAnnotation: NewTypeAnnotation(&VariableSizedType{ + Type: UInt8Type, + }), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + DeployedContractType, + ), +} + +const Account_ContractsTypeUpdateFunctionDocString = ` +Updates the code for the contract/contract interface in the account. + +The ` + "`code`" + ` parameter is the UTF-8 encoded representation of the source code. +The code must contain exactly one contract or contract interface, +which must have the same name as the ` + "`name`" + ` parameter. + +Does **not** run the initializer of the contract/contract interface again. +The contract instance in the world state stays as is. + +Fails if no contract/contract interface with the given name exists in the account, +if the given code does not declare exactly one contract or contract interface, +or if the given name does not match the name of the contract/contract interface declaration in the code. + +Returns the deployed contract for the updated contract. +` + +const Account_ContractsTypeGetFunctionName = "get" + +var Account_ContractsTypeGetFunctionType = &FunctionType{ + Purity: FunctionPurityView, + Parameters: []Parameter{ + { + Identifier: "name", + TypeAnnotation: NewTypeAnnotation(StringType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + &OptionalType{ + Type: DeployedContractType, + }, + ), +} + +const Account_ContractsTypeGetFunctionDocString = ` +Returns the deployed contract for the contract/contract interface with the given name in the account, if any. + +Returns nil if no contract/contract interface with the given name exists in the account. +` + +const Account_ContractsTypeRemoveFunctionName = "remove" + +var Account_ContractsTypeRemoveFunctionType = &FunctionType{ + Parameters: []Parameter{ + { + Identifier: "name", + TypeAnnotation: NewTypeAnnotation(StringType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + &OptionalType{ + Type: DeployedContractType, + }, + ), +} + +const Account_ContractsTypeRemoveFunctionDocString = ` +Removes the contract/contract interface from the account which has the given name, if any. + +Returns the removed deployed contract, if any. + +Returns nil if no contract/contract interface with the given name exists in the account. +` + +const Account_ContractsTypeBorrowFunctionName = "borrow" + +var Account_ContractsTypeBorrowFunctionTypeParameterT = &TypeParameter{ + Name: "T", + TypeBound: &ReferenceType{ + Type: AnyType, + Authorization: UnauthorizedAccess, + }, +} + +var Account_ContractsTypeBorrowFunctionType = &FunctionType{ + Purity: FunctionPurityView, + TypeParameters: []*TypeParameter{ + Account_ContractsTypeBorrowFunctionTypeParameterT, + }, + Parameters: []Parameter{ + { + Identifier: "name", + TypeAnnotation: NewTypeAnnotation(StringType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + &OptionalType{ + Type: &GenericType{ + TypeParameter: Account_ContractsTypeBorrowFunctionTypeParameterT, + }, + }, + ), +} + +const Account_ContractsTypeBorrowFunctionDocString = ` +Returns a reference of the given type to the contract with the given name in the account, if any. + +Returns nil if no contract with the given name exists in the account, +or if the contract does not conform to the given type. +` + +const Account_ContractsTypeName = "Contracts" + +var Account_ContractsType = func() *CompositeType { + var t = &CompositeType{ + Identifier: Account_ContractsTypeName, + Kind: common.CompositeKindStructure, + importable: false, + hasComputedMembers: true, + } + + return t +}() + +func init() { + var members = []*Member{ + NewUnmeteredFieldMember( + Account_ContractsType, + PrimitiveAccess(ast.AccessAll), + ast.VariableKindConstant, + Account_ContractsTypeNamesFieldName, + Account_ContractsTypeNamesFieldType, + Account_ContractsTypeNamesFieldDocString, + ), + NewUnmeteredFunctionMember( + Account_ContractsType, + newEntitlementAccess( + []Type{ContractsType, AddContractType}, + Disjunction, + ), + Account_ContractsTypeAddFunctionName, + Account_ContractsTypeAddFunctionType, + Account_ContractsTypeAddFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_ContractsType, + newEntitlementAccess( + []Type{ContractsType, UpdateContractType}, + Disjunction, + ), + Account_ContractsTypeUpdateFunctionName, + Account_ContractsTypeUpdateFunctionType, + Account_ContractsTypeUpdateFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_ContractsType, + PrimitiveAccess(ast.AccessAll), + Account_ContractsTypeGetFunctionName, + Account_ContractsTypeGetFunctionType, + Account_ContractsTypeGetFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_ContractsType, + newEntitlementAccess( + []Type{ContractsType, RemoveContractType}, + Disjunction, + ), + Account_ContractsTypeRemoveFunctionName, + Account_ContractsTypeRemoveFunctionType, + Account_ContractsTypeRemoveFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_ContractsType, + PrimitiveAccess(ast.AccessAll), + Account_ContractsTypeBorrowFunctionName, + Account_ContractsTypeBorrowFunctionType, + Account_ContractsTypeBorrowFunctionDocString, + ), + } + + Account_ContractsType.Members = MembersAsMap(members) + Account_ContractsType.Fields = MembersFieldNames(members) +} + +const Account_KeysTypeAddFunctionName = "add" + +var Account_KeysTypeAddFunctionType = &FunctionType{ + Parameters: []Parameter{ + { + Identifier: "publicKey", + TypeAnnotation: NewTypeAnnotation(PublicKeyType), + }, + { + Identifier: "hashAlgorithm", + TypeAnnotation: NewTypeAnnotation(HashAlgorithmType), + }, + { + Identifier: "weight", + TypeAnnotation: NewTypeAnnotation(UFix64Type), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + AccountKeyType, + ), +} + +const Account_KeysTypeAddFunctionDocString = ` +Adds a new key with the given hashing algorithm and a weight. + +Returns the added key. +` + +const Account_KeysTypeGetFunctionName = "get" + +var Account_KeysTypeGetFunctionType = &FunctionType{ + Purity: FunctionPurityView, + Parameters: []Parameter{ + { + Identifier: "keyIndex", + TypeAnnotation: NewTypeAnnotation(IntType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + &OptionalType{ + Type: AccountKeyType, + }, + ), +} + +const Account_KeysTypeGetFunctionDocString = ` +Returns the key at the given index, if it exists, or nil otherwise. + +Revoked keys are always returned, but they have ` + "`isRevoked`" + ` field set to true. +` + +const Account_KeysTypeRevokeFunctionName = "revoke" + +var Account_KeysTypeRevokeFunctionType = &FunctionType{ + Parameters: []Parameter{ + { + Identifier: "keyIndex", + TypeAnnotation: NewTypeAnnotation(IntType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + &OptionalType{ + Type: AccountKeyType, + }, + ), +} + +const Account_KeysTypeRevokeFunctionDocString = ` +Marks the key at the given index revoked, but does not delete it. + +Returns the revoked key if it exists, or nil otherwise. +` + +const Account_KeysTypeForEachFunctionName = "forEach" + +var Account_KeysTypeForEachFunctionType = &FunctionType{ + Parameters: []Parameter{ + { + Label: ArgumentLabelNotRequired, + Identifier: "function", + TypeAnnotation: NewTypeAnnotation(&FunctionType{ + Parameters: []Parameter{ + { + TypeAnnotation: NewTypeAnnotation(AccountKeyType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + BoolType, + ), + }), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + VoidType, + ), +} + +const Account_KeysTypeForEachFunctionDocString = ` +Iterate over all unrevoked keys in this account, +passing each key in turn to the provided function. + +Iteration is stopped early if the function returns ` + "`false`" + `. + +The order of iteration is undefined. +` + +const Account_KeysTypeCountFieldName = "count" + +var Account_KeysTypeCountFieldType = UInt64Type + +const Account_KeysTypeCountFieldDocString = ` +The total number of unrevoked keys in this account. +` + +const Account_KeysTypeName = "Keys" + +var Account_KeysType = func() *CompositeType { + var t = &CompositeType{ + Identifier: Account_KeysTypeName, + Kind: common.CompositeKindStructure, + importable: false, + hasComputedMembers: true, + } + + return t +}() + +func init() { + var members = []*Member{ + NewUnmeteredFunctionMember( + Account_KeysType, + newEntitlementAccess( + []Type{KeysType, AddKeyType}, + Disjunction, + ), + Account_KeysTypeAddFunctionName, + Account_KeysTypeAddFunctionType, + Account_KeysTypeAddFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_KeysType, + PrimitiveAccess(ast.AccessAll), + Account_KeysTypeGetFunctionName, + Account_KeysTypeGetFunctionType, + Account_KeysTypeGetFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_KeysType, + newEntitlementAccess( + []Type{KeysType, RevokeKeyType}, + Disjunction, + ), + Account_KeysTypeRevokeFunctionName, + Account_KeysTypeRevokeFunctionType, + Account_KeysTypeRevokeFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_KeysType, + PrimitiveAccess(ast.AccessAll), + Account_KeysTypeForEachFunctionName, + Account_KeysTypeForEachFunctionType, + Account_KeysTypeForEachFunctionDocString, + ), + NewUnmeteredFieldMember( + Account_KeysType, + PrimitiveAccess(ast.AccessAll), + ast.VariableKindConstant, + Account_KeysTypeCountFieldName, + Account_KeysTypeCountFieldType, + Account_KeysTypeCountFieldDocString, + ), + } + + Account_KeysType.Members = MembersAsMap(members) + Account_KeysType.Fields = MembersFieldNames(members) +} + +const Account_InboxTypePublishFunctionName = "publish" + +var Account_InboxTypePublishFunctionType = &FunctionType{ + Parameters: []Parameter{ + { + Label: ArgumentLabelNotRequired, + Identifier: "value", + TypeAnnotation: NewTypeAnnotation(&CapabilityType{}), + }, + { + Identifier: "name", + TypeAnnotation: NewTypeAnnotation(StringType), + }, + { + Identifier: "recipient", + TypeAnnotation: NewTypeAnnotation(TheAddressType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + VoidType, + ), +} + +const Account_InboxTypePublishFunctionDocString = ` +Publishes a new Capability under the given name, +to be claimed by the specified recipient. +` + +const Account_InboxTypeUnpublishFunctionName = "unpublish" + +var Account_InboxTypeUnpublishFunctionTypeParameterT = &TypeParameter{ + Name: "T", + TypeBound: &ReferenceType{ + Type: AnyType, + Authorization: UnauthorizedAccess, + }, +} + +var Account_InboxTypeUnpublishFunctionType = &FunctionType{ + TypeParameters: []*TypeParameter{ + Account_InboxTypeUnpublishFunctionTypeParameterT, + }, + Parameters: []Parameter{ + { + Label: ArgumentLabelNotRequired, + Identifier: "name", + TypeAnnotation: NewTypeAnnotation(StringType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + &OptionalType{ + Type: MustInstantiate( + &CapabilityType{}, + &GenericType{ + TypeParameter: Account_InboxTypeUnpublishFunctionTypeParameterT, + }, + ), + }, + ), +} + +const Account_InboxTypeUnpublishFunctionDocString = ` +Unpublishes a Capability previously published by this account. + +Returns ` + "`nil`" + ` if no Capability is published under the given name. + +Errors if the Capability under that name does not match the provided type. +` + +const Account_InboxTypeClaimFunctionName = "claim" + +var Account_InboxTypeClaimFunctionTypeParameterT = &TypeParameter{ + Name: "T", + TypeBound: &ReferenceType{ + Type: AnyType, + Authorization: UnauthorizedAccess, + }, +} + +var Account_InboxTypeClaimFunctionType = &FunctionType{ + TypeParameters: []*TypeParameter{ + Account_InboxTypeClaimFunctionTypeParameterT, + }, + Parameters: []Parameter{ + { + Label: ArgumentLabelNotRequired, + Identifier: "name", + TypeAnnotation: NewTypeAnnotation(StringType), + }, + { + Identifier: "provider", + TypeAnnotation: NewTypeAnnotation(TheAddressType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + &OptionalType{ + Type: MustInstantiate( + &CapabilityType{}, + &GenericType{ + TypeParameter: Account_InboxTypeClaimFunctionTypeParameterT, + }, + ), + }, + ), +} + +const Account_InboxTypeClaimFunctionDocString = ` +Claims a Capability previously published by the specified provider. + +Returns ` + "`nil`" + ` if no Capability is published under the given name, +or if this account is not its intended recipient. + +Errors if the Capability under that name does not match the provided type. +` + +const Account_InboxTypeName = "Inbox" + +var Account_InboxType = func() *CompositeType { + var t = &CompositeType{ + Identifier: Account_InboxTypeName, + Kind: common.CompositeKindStructure, + importable: false, + hasComputedMembers: true, + } + + return t +}() + +func init() { + var members = []*Member{ + NewUnmeteredFunctionMember( + Account_InboxType, + newEntitlementAccess( + []Type{InboxType, PublishInboxCapabilityType}, + Disjunction, + ), + Account_InboxTypePublishFunctionName, + Account_InboxTypePublishFunctionType, + Account_InboxTypePublishFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_InboxType, + newEntitlementAccess( + []Type{InboxType, UnpublishInboxCapabilityType}, + Disjunction, + ), + Account_InboxTypeUnpublishFunctionName, + Account_InboxTypeUnpublishFunctionType, + Account_InboxTypeUnpublishFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_InboxType, + newEntitlementAccess( + []Type{InboxType, ClaimInboxCapabilityType}, + Disjunction, + ), + Account_InboxTypeClaimFunctionName, + Account_InboxTypeClaimFunctionType, + Account_InboxTypeClaimFunctionDocString, + ), + } + + Account_InboxType.Members = MembersAsMap(members) + Account_InboxType.Fields = MembersFieldNames(members) +} + +const Account_CapabilitiesTypeStorageFieldName = "storage" + +var Account_CapabilitiesTypeStorageFieldType = Account_StorageCapabilitiesType + +const Account_CapabilitiesTypeStorageFieldDocString = ` +The storage capabilities of the account. +` + +const Account_CapabilitiesTypeAccountFieldName = "account" + +var Account_CapabilitiesTypeAccountFieldType = Account_AccountCapabilitiesType + +const Account_CapabilitiesTypeAccountFieldDocString = ` +The account capabilities of the account. +` + +const Account_CapabilitiesTypeGetFunctionName = "get" + +var Account_CapabilitiesTypeGetFunctionTypeParameterT = &TypeParameter{ + Name: "T", + TypeBound: &ReferenceType{ + Type: AnyType, + Authorization: UnauthorizedAccess, + }, +} + +var Account_CapabilitiesTypeGetFunctionType = &FunctionType{ + Purity: FunctionPurityView, + TypeParameters: []*TypeParameter{ + Account_CapabilitiesTypeGetFunctionTypeParameterT, + }, + Parameters: []Parameter{ + { + Label: ArgumentLabelNotRequired, + Identifier: "path", + TypeAnnotation: NewTypeAnnotation(PublicPathType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + &OptionalType{ + Type: MustInstantiate( + &CapabilityType{}, + &GenericType{ + TypeParameter: Account_CapabilitiesTypeGetFunctionTypeParameterT, + }, + ), + }, + ), +} + +const Account_CapabilitiesTypeGetFunctionDocString = ` +Returns the capability at the given public path. +Returns nil if the capability does not exist, +or if the given type is not a supertype of the capability's borrow type. +` + +const Account_CapabilitiesTypeBorrowFunctionName = "borrow" + +var Account_CapabilitiesTypeBorrowFunctionTypeParameterT = &TypeParameter{ + Name: "T", + TypeBound: &ReferenceType{ + Type: AnyType, + Authorization: UnauthorizedAccess, + }, +} + +var Account_CapabilitiesTypeBorrowFunctionType = &FunctionType{ + Purity: FunctionPurityView, + TypeParameters: []*TypeParameter{ + Account_CapabilitiesTypeBorrowFunctionTypeParameterT, + }, + Parameters: []Parameter{ + { + Label: ArgumentLabelNotRequired, + Identifier: "path", + TypeAnnotation: NewTypeAnnotation(PublicPathType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + &OptionalType{ + Type: &GenericType{ + TypeParameter: Account_CapabilitiesTypeBorrowFunctionTypeParameterT, + }, + }, + ), +} + +const Account_CapabilitiesTypeBorrowFunctionDocString = ` +Borrows the capability at the given public path. +Returns nil if the capability does not exist, or cannot be borrowed using the given type. +The function is equivalent to ` + "`get(path)?.borrow()`" + `. +` + +const Account_CapabilitiesTypePublishFunctionName = "publish" + +var Account_CapabilitiesTypePublishFunctionType = &FunctionType{ + Parameters: []Parameter{ + { + Label: ArgumentLabelNotRequired, + Identifier: "capability", + TypeAnnotation: NewTypeAnnotation(&CapabilityType{}), + }, + { + Identifier: "at", + TypeAnnotation: NewTypeAnnotation(PublicPathType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + VoidType, + ), +} + +const Account_CapabilitiesTypePublishFunctionDocString = ` +Publish the capability at the given public path. + +If there is already a capability published under the given path, the program aborts. + +The path must be a public path, i.e., only the domain ` + "`public`" + ` is allowed. +` + +const Account_CapabilitiesTypeUnpublishFunctionName = "unpublish" + +var Account_CapabilitiesTypeUnpublishFunctionType = &FunctionType{ + Parameters: []Parameter{ + { + Label: ArgumentLabelNotRequired, + Identifier: "path", + TypeAnnotation: NewTypeAnnotation(PublicPathType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + &OptionalType{ + Type: &CapabilityType{}, + }, + ), +} + +const Account_CapabilitiesTypeUnpublishFunctionDocString = ` +Unpublish the capability published at the given path. + +Returns the capability if one was published at the path. +Returns nil if no capability was published at the path. +` + +const Account_CapabilitiesTypeName = "Capabilities" + +var Account_CapabilitiesType = func() *CompositeType { + var t = &CompositeType{ + Identifier: Account_CapabilitiesTypeName, + Kind: common.CompositeKindStructure, + importable: false, + hasComputedMembers: true, + } + + return t +}() + +func init() { + var members = []*Member{ + NewUnmeteredFieldMember( + Account_CapabilitiesType, + newEntitlementAccess( + []Type{CapabilitiesMappingType}, + Conjunction, + ), + ast.VariableKindConstant, + Account_CapabilitiesTypeStorageFieldName, + Account_CapabilitiesTypeStorageFieldType, + Account_CapabilitiesTypeStorageFieldDocString, + ), + NewUnmeteredFieldMember( + Account_CapabilitiesType, + newEntitlementAccess( + []Type{CapabilitiesMappingType}, + Conjunction, + ), + ast.VariableKindConstant, + Account_CapabilitiesTypeAccountFieldName, + Account_CapabilitiesTypeAccountFieldType, + Account_CapabilitiesTypeAccountFieldDocString, + ), + NewUnmeteredFunctionMember( + Account_CapabilitiesType, + PrimitiveAccess(ast.AccessAll), + Account_CapabilitiesTypeGetFunctionName, + Account_CapabilitiesTypeGetFunctionType, + Account_CapabilitiesTypeGetFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_CapabilitiesType, + PrimitiveAccess(ast.AccessAll), + Account_CapabilitiesTypeBorrowFunctionName, + Account_CapabilitiesTypeBorrowFunctionType, + Account_CapabilitiesTypeBorrowFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_CapabilitiesType, + newEntitlementAccess( + []Type{CapabilitiesType, PublishCapabilityType}, + Disjunction, + ), + Account_CapabilitiesTypePublishFunctionName, + Account_CapabilitiesTypePublishFunctionType, + Account_CapabilitiesTypePublishFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_CapabilitiesType, + newEntitlementAccess( + []Type{CapabilitiesType, UnpublishCapabilityType}, + Disjunction, + ), + Account_CapabilitiesTypeUnpublishFunctionName, + Account_CapabilitiesTypeUnpublishFunctionType, + Account_CapabilitiesTypeUnpublishFunctionDocString, + ), + } + + Account_CapabilitiesType.Members = MembersAsMap(members) + Account_CapabilitiesType.Fields = MembersFieldNames(members) +} + +const Account_StorageCapabilitiesTypeGetControllerFunctionName = "getController" + +var Account_StorageCapabilitiesTypeGetControllerFunctionType = &FunctionType{ + Purity: FunctionPurityView, + Parameters: []Parameter{ + { + Identifier: "byCapabilityID", + TypeAnnotation: NewTypeAnnotation(UInt64Type), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + &OptionalType{ + Type: &ReferenceType{ + Type: StorageCapabilityControllerType, + Authorization: UnauthorizedAccess, + }, + }, + ), +} + +const Account_StorageCapabilitiesTypeGetControllerFunctionDocString = ` +Get the storage capability controller for the capability with the specified ID. + +Returns nil if the ID does not reference an existing storage capability. +` + +const Account_StorageCapabilitiesTypeGetControllersFunctionName = "getControllers" + +var Account_StorageCapabilitiesTypeGetControllersFunctionType = &FunctionType{ + Purity: FunctionPurityView, + Parameters: []Parameter{ + { + Identifier: "forPath", + TypeAnnotation: NewTypeAnnotation(StoragePathType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + &VariableSizedType{ + Type: &ReferenceType{ + Type: StorageCapabilityControllerType, + Authorization: UnauthorizedAccess, + }, + }, + ), +} + +const Account_StorageCapabilitiesTypeGetControllersFunctionDocString = ` +Get all storage capability controllers for capabilities that target this storage path +` + +const Account_StorageCapabilitiesTypeForEachControllerFunctionName = "forEachController" + +var Account_StorageCapabilitiesTypeForEachControllerFunctionType = &FunctionType{ + Parameters: []Parameter{ + { + Identifier: "forPath", + TypeAnnotation: NewTypeAnnotation(StoragePathType), + }, + { + Label: ArgumentLabelNotRequired, + Identifier: "function", + TypeAnnotation: NewTypeAnnotation(&FunctionType{ + Parameters: []Parameter{ + { + TypeAnnotation: NewTypeAnnotation(&ReferenceType{ + Type: StorageCapabilityControllerType, + Authorization: UnauthorizedAccess, + }), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + BoolType, + ), + }), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + VoidType, + ), +} + +const Account_StorageCapabilitiesTypeForEachControllerFunctionDocString = ` +Iterate over all storage capability controllers for capabilities that target this storage path, +passing a reference to each controller to the provided callback function. + +Iteration is stopped early if the callback function returns ` + "`false`" + `. + +If a new storage capability controller is issued for the path, +an existing storage capability controller for the path is deleted, +or a storage capability controller is retargeted from or to the path, +then the callback must stop iteration by returning false. +Otherwise, iteration aborts. +` + +const Account_StorageCapabilitiesTypeIssueFunctionName = "issue" + +var Account_StorageCapabilitiesTypeIssueFunctionTypeParameterT = &TypeParameter{ + Name: "T", + TypeBound: &ReferenceType{ + Type: AnyType, + Authorization: UnauthorizedAccess, + }, +} + +var Account_StorageCapabilitiesTypeIssueFunctionType = &FunctionType{ + TypeParameters: []*TypeParameter{ + Account_StorageCapabilitiesTypeIssueFunctionTypeParameterT, + }, + Parameters: []Parameter{ + { + Label: ArgumentLabelNotRequired, + Identifier: "path", + TypeAnnotation: NewTypeAnnotation(StoragePathType), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + MustInstantiate( + &CapabilityType{}, + &GenericType{ + TypeParameter: Account_StorageCapabilitiesTypeIssueFunctionTypeParameterT, + }, + ), + ), +} + +const Account_StorageCapabilitiesTypeIssueFunctionDocString = ` +Issue/create a new storage capability. +` + +const Account_StorageCapabilitiesTypeName = "StorageCapabilities" + +var Account_StorageCapabilitiesType = func() *CompositeType { + var t = &CompositeType{ + Identifier: Account_StorageCapabilitiesTypeName, + Kind: common.CompositeKindStructure, + importable: false, + hasComputedMembers: true, + } + + return t +}() + +func init() { + var members = []*Member{ + NewUnmeteredFunctionMember( + Account_StorageCapabilitiesType, + newEntitlementAccess( + []Type{CapabilitiesType, StorageCapabilitiesType, GetStorageCapabilityControllerType}, + Disjunction, + ), + Account_StorageCapabilitiesTypeGetControllerFunctionName, + Account_StorageCapabilitiesTypeGetControllerFunctionType, + Account_StorageCapabilitiesTypeGetControllerFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_StorageCapabilitiesType, + newEntitlementAccess( + []Type{CapabilitiesType, StorageCapabilitiesType, GetStorageCapabilityControllerType}, + Disjunction, + ), + Account_StorageCapabilitiesTypeGetControllersFunctionName, + Account_StorageCapabilitiesTypeGetControllersFunctionType, + Account_StorageCapabilitiesTypeGetControllersFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_StorageCapabilitiesType, + newEntitlementAccess( + []Type{CapabilitiesType, StorageCapabilitiesType, GetStorageCapabilityControllerType}, + Disjunction, + ), + Account_StorageCapabilitiesTypeForEachControllerFunctionName, + Account_StorageCapabilitiesTypeForEachControllerFunctionType, + Account_StorageCapabilitiesTypeForEachControllerFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_StorageCapabilitiesType, + newEntitlementAccess( + []Type{CapabilitiesType, StorageCapabilitiesType, IssueStorageCapabilityControllerType}, + Disjunction, + ), + Account_StorageCapabilitiesTypeIssueFunctionName, + Account_StorageCapabilitiesTypeIssueFunctionType, + Account_StorageCapabilitiesTypeIssueFunctionDocString, + ), + } + + Account_StorageCapabilitiesType.Members = MembersAsMap(members) + Account_StorageCapabilitiesType.Fields = MembersFieldNames(members) +} + +const Account_AccountCapabilitiesTypeGetControllerFunctionName = "getController" + +var Account_AccountCapabilitiesTypeGetControllerFunctionType = &FunctionType{ + Purity: FunctionPurityView, + Parameters: []Parameter{ + { + Identifier: "byCapabilityID", + TypeAnnotation: NewTypeAnnotation(UInt64Type), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + &OptionalType{ + Type: &ReferenceType{ + Type: AccountCapabilityControllerType, + Authorization: UnauthorizedAccess, + }, + }, + ), +} + +const Account_AccountCapabilitiesTypeGetControllerFunctionDocString = ` +Get capability controller for capability with the specified ID. + +Returns nil if the ID does not reference an existing account capability. +` + +const Account_AccountCapabilitiesTypeGetControllersFunctionName = "getControllers" + +var Account_AccountCapabilitiesTypeGetControllersFunctionType = &FunctionType{ + Purity: FunctionPurityView, + ReturnTypeAnnotation: NewTypeAnnotation( + &VariableSizedType{ + Type: &ReferenceType{ + Type: AccountCapabilityControllerType, + Authorization: UnauthorizedAccess, + }, + }, + ), +} + +const Account_AccountCapabilitiesTypeGetControllersFunctionDocString = ` +Get all capability controllers for all account capabilities. +` + +const Account_AccountCapabilitiesTypeForEachControllerFunctionName = "forEachController" + +var Account_AccountCapabilitiesTypeForEachControllerFunctionType = &FunctionType{ + Parameters: []Parameter{ + { + Label: ArgumentLabelNotRequired, + Identifier: "function", + TypeAnnotation: NewTypeAnnotation(&FunctionType{ + Parameters: []Parameter{ + { + TypeAnnotation: NewTypeAnnotation(&ReferenceType{ + Type: AccountCapabilityControllerType, + Authorization: UnauthorizedAccess, + }), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + BoolType, + ), + }), + }, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + VoidType, + ), +} + +const Account_AccountCapabilitiesTypeForEachControllerFunctionDocString = ` +Iterate over all account capability controllers for all account capabilities, +passing a reference to each controller to the provided callback function. + +Iteration is stopped early if the callback function returns ` + "`false`" + `. + +If a new account capability controller is issued for the account, +or an existing account capability controller for the account is deleted, +then the callback must stop iteration by returning false. +Otherwise, iteration aborts. +` + +const Account_AccountCapabilitiesTypeIssueFunctionName = "issue" + +var Account_AccountCapabilitiesTypeIssueFunctionTypeParameterT = &TypeParameter{ + Name: "T", + TypeBound: &ReferenceType{ + Type: AccountType, + Authorization: UnauthorizedAccess, + }, +} + +var Account_AccountCapabilitiesTypeIssueFunctionType = &FunctionType{ + TypeParameters: []*TypeParameter{ + Account_AccountCapabilitiesTypeIssueFunctionTypeParameterT, + }, + ReturnTypeAnnotation: NewTypeAnnotation( + MustInstantiate( + &CapabilityType{}, + &GenericType{ + TypeParameter: Account_AccountCapabilitiesTypeIssueFunctionTypeParameterT, + }, + ), + ), +} + +const Account_AccountCapabilitiesTypeIssueFunctionDocString = ` +Issue/create a new account capability. +` + +const Account_AccountCapabilitiesTypeName = "AccountCapabilities" + +var Account_AccountCapabilitiesType = func() *CompositeType { + var t = &CompositeType{ + Identifier: Account_AccountCapabilitiesTypeName, + Kind: common.CompositeKindStructure, + importable: false, + hasComputedMembers: true, + } + + return t +}() + +func init() { + var members = []*Member{ + NewUnmeteredFunctionMember( + Account_AccountCapabilitiesType, + newEntitlementAccess( + []Type{CapabilitiesType, AccountCapabilitiesType, GetAccountCapabilityControllerType}, + Disjunction, + ), + Account_AccountCapabilitiesTypeGetControllerFunctionName, + Account_AccountCapabilitiesTypeGetControllerFunctionType, + Account_AccountCapabilitiesTypeGetControllerFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_AccountCapabilitiesType, + newEntitlementAccess( + []Type{CapabilitiesType, AccountCapabilitiesType, GetAccountCapabilityControllerType}, + Disjunction, + ), + Account_AccountCapabilitiesTypeGetControllersFunctionName, + Account_AccountCapabilitiesTypeGetControllersFunctionType, + Account_AccountCapabilitiesTypeGetControllersFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_AccountCapabilitiesType, + newEntitlementAccess( + []Type{CapabilitiesType, AccountCapabilitiesType, GetAccountCapabilityControllerType}, + Disjunction, + ), + Account_AccountCapabilitiesTypeForEachControllerFunctionName, + Account_AccountCapabilitiesTypeForEachControllerFunctionType, + Account_AccountCapabilitiesTypeForEachControllerFunctionDocString, + ), + NewUnmeteredFunctionMember( + Account_AccountCapabilitiesType, + newEntitlementAccess( + []Type{CapabilitiesType, AccountCapabilitiesType, IssueAccountCapabilityControllerType}, + Disjunction, + ), + Account_AccountCapabilitiesTypeIssueFunctionName, + Account_AccountCapabilitiesTypeIssueFunctionType, + Account_AccountCapabilitiesTypeIssueFunctionDocString, + ), + } + + Account_AccountCapabilitiesType.Members = MembersAsMap(members) + Account_AccountCapabilitiesType.Fields = MembersFieldNames(members) +} + +const AccountTypeName = "Account" + +var AccountType = func() *CompositeType { + var t = &CompositeType{ + Identifier: AccountTypeName, + Kind: common.CompositeKindStructure, + importable: false, + hasComputedMembers: true, + } + + t.SetNestedType(Account_StorageTypeName, Account_StorageType) + t.SetNestedType(Account_ContractsTypeName, Account_ContractsType) + t.SetNestedType(Account_KeysTypeName, Account_KeysType) + t.SetNestedType(Account_InboxTypeName, Account_InboxType) + t.SetNestedType(Account_CapabilitiesTypeName, Account_CapabilitiesType) + t.SetNestedType(Account_StorageCapabilitiesTypeName, Account_StorageCapabilitiesType) + t.SetNestedType(Account_AccountCapabilitiesTypeName, Account_AccountCapabilitiesType) + return t +}() + +func init() { + var members = []*Member{ + NewUnmeteredFieldMember( + AccountType, + PrimitiveAccess(ast.AccessAll), + ast.VariableKindConstant, + AccountTypeAddressFieldName, + AccountTypeAddressFieldType, + AccountTypeAddressFieldDocString, + ), + NewUnmeteredFieldMember( + AccountType, + PrimitiveAccess(ast.AccessAll), + ast.VariableKindConstant, + AccountTypeBalanceFieldName, + AccountTypeBalanceFieldType, + AccountTypeBalanceFieldDocString, + ), + NewUnmeteredFieldMember( + AccountType, + PrimitiveAccess(ast.AccessAll), + ast.VariableKindConstant, + AccountTypeAvailableBalanceFieldName, + AccountTypeAvailableBalanceFieldType, + AccountTypeAvailableBalanceFieldDocString, + ), + NewUnmeteredFieldMember( + AccountType, + newEntitlementAccess( + []Type{AccountMappingType}, + Conjunction, + ), + ast.VariableKindConstant, + AccountTypeStorageFieldName, + AccountTypeStorageFieldType, + AccountTypeStorageFieldDocString, + ), + NewUnmeteredFieldMember( + AccountType, + newEntitlementAccess( + []Type{AccountMappingType}, + Conjunction, + ), + ast.VariableKindConstant, + AccountTypeContractsFieldName, + AccountTypeContractsFieldType, + AccountTypeContractsFieldDocString, + ), + NewUnmeteredFieldMember( + AccountType, + newEntitlementAccess( + []Type{AccountMappingType}, + Conjunction, + ), + ast.VariableKindConstant, + AccountTypeKeysFieldName, + AccountTypeKeysFieldType, + AccountTypeKeysFieldDocString, + ), + NewUnmeteredFieldMember( + AccountType, + newEntitlementAccess( + []Type{AccountMappingType}, + Conjunction, + ), + ast.VariableKindConstant, + AccountTypeInboxFieldName, + AccountTypeInboxFieldType, + AccountTypeInboxFieldDocString, + ), + NewUnmeteredFieldMember( + AccountType, + newEntitlementAccess( + []Type{AccountMappingType}, + Conjunction, + ), + ast.VariableKindConstant, + AccountTypeCapabilitiesFieldName, + AccountTypeCapabilitiesFieldType, + AccountTypeCapabilitiesFieldDocString, + ), + } + + AccountType.Members = MembersAsMap(members) + AccountType.Fields = MembersFieldNames(members) +} + +var StorageType = &EntitlementType{ + Identifier: "Storage", +} + +var SaveValueType = &EntitlementType{ + Identifier: "SaveValue", +} + +var LoadValueType = &EntitlementType{ + Identifier: "LoadValue", +} + +var BorrowValueType = &EntitlementType{ + Identifier: "BorrowValue", +} + +var ContractsType = &EntitlementType{ + Identifier: "Contracts", +} + +var AddContractType = &EntitlementType{ + Identifier: "AddContract", +} + +var UpdateContractType = &EntitlementType{ + Identifier: "UpdateContract", +} + +var RemoveContractType = &EntitlementType{ + Identifier: "RemoveContract", +} + +var KeysType = &EntitlementType{ + Identifier: "Keys", +} + +var AddKeyType = &EntitlementType{ + Identifier: "AddKey", +} + +var RevokeKeyType = &EntitlementType{ + Identifier: "RevokeKey", +} + +var InboxType = &EntitlementType{ + Identifier: "Inbox", +} + +var PublishInboxCapabilityType = &EntitlementType{ + Identifier: "PublishInboxCapability", +} + +var UnpublishInboxCapabilityType = &EntitlementType{ + Identifier: "UnpublishInboxCapability", +} + +var ClaimInboxCapabilityType = &EntitlementType{ + Identifier: "ClaimInboxCapability", +} + +var CapabilitiesType = &EntitlementType{ + Identifier: "Capabilities", +} + +var StorageCapabilitiesType = &EntitlementType{ + Identifier: "StorageCapabilities", +} + +var AccountCapabilitiesType = &EntitlementType{ + Identifier: "AccountCapabilities", +} + +var PublishCapabilityType = &EntitlementType{ + Identifier: "PublishCapability", +} + +var UnpublishCapabilityType = &EntitlementType{ + Identifier: "UnpublishCapability", +} + +var GetStorageCapabilityControllerType = &EntitlementType{ + Identifier: "GetStorageCapabilityController", +} + +var IssueStorageCapabilityControllerType = &EntitlementType{ + Identifier: "IssueStorageCapabilityController", +} + +var GetAccountCapabilityControllerType = &EntitlementType{ + Identifier: "GetAccountCapabilityController", +} + +var IssueAccountCapabilityControllerType = &EntitlementType{ + Identifier: "IssueAccountCapabilityController", +} + +var AccountMappingType = &EntitlementMapType{ + Identifier: "AccountMapping", + Relations: []EntitlementRelation{ + EntitlementRelation{ + Input: StorageType, + Output: StorageType, + }, + EntitlementRelation{ + Input: ContractsType, + Output: ContractsType, + }, + EntitlementRelation{ + Input: KeysType, + Output: KeysType, + }, + EntitlementRelation{ + Input: InboxType, + Output: InboxType, + }, + EntitlementRelation{ + Input: CapabilitiesType, + Output: CapabilitiesType, + }, + EntitlementRelation{ + Input: SaveValueType, + Output: SaveValueType, + }, + EntitlementRelation{ + Input: LoadValueType, + Output: LoadValueType, + }, + EntitlementRelation{ + Input: BorrowValueType, + Output: BorrowValueType, + }, + EntitlementRelation{ + Input: AddContractType, + Output: AddContractType, + }, + EntitlementRelation{ + Input: UpdateContractType, + Output: UpdateContractType, + }, + EntitlementRelation{ + Input: RemoveContractType, + Output: RemoveContractType, + }, + EntitlementRelation{ + Input: AddKeyType, + Output: AddKeyType, + }, + EntitlementRelation{ + Input: RevokeKeyType, + Output: RevokeKeyType, + }, + EntitlementRelation{ + Input: PublishInboxCapabilityType, + Output: PublishInboxCapabilityType, + }, + EntitlementRelation{ + Input: UnpublishInboxCapabilityType, + Output: UnpublishInboxCapabilityType, + }, + EntitlementRelation{ + Input: StorageCapabilitiesType, + Output: StorageCapabilitiesType, + }, + EntitlementRelation{ + Input: AccountCapabilitiesType, + Output: AccountCapabilitiesType, + }, + EntitlementRelation{ + Input: GetStorageCapabilityControllerType, + Output: GetStorageCapabilityControllerType, + }, + EntitlementRelation{ + Input: IssueStorageCapabilityControllerType, + Output: IssueStorageCapabilityControllerType, + }, + EntitlementRelation{ + Input: GetAccountCapabilityControllerType, + Output: GetAccountCapabilityControllerType, + }, + EntitlementRelation{ + Input: IssueAccountCapabilityControllerType, + Output: IssueAccountCapabilityControllerType, + }, + EntitlementRelation{ + Input: StorageType, + Output: SaveValueType, + }, + EntitlementRelation{ + Input: StorageType, + Output: LoadValueType, + }, + EntitlementRelation{ + Input: StorageType, + Output: BorrowValueType, + }, + EntitlementRelation{ + Input: ContractsType, + Output: AddContractType, + }, + EntitlementRelation{ + Input: ContractsType, + Output: UpdateContractType, + }, + EntitlementRelation{ + Input: ContractsType, + Output: RemoveContractType, + }, + EntitlementRelation{ + Input: KeysType, + Output: AddKeyType, + }, + EntitlementRelation{ + Input: KeysType, + Output: RevokeKeyType, + }, + EntitlementRelation{ + Input: InboxType, + Output: PublishInboxCapabilityType, + }, + EntitlementRelation{ + Input: InboxType, + Output: UnpublishInboxCapabilityType, + }, + EntitlementRelation{ + Input: InboxType, + Output: ClaimInboxCapabilityType, + }, + EntitlementRelation{ + Input: CapabilitiesType, + Output: StorageCapabilitiesType, + }, + EntitlementRelation{ + Input: CapabilitiesType, + Output: AccountCapabilitiesType, + }, + }, +} + +var CapabilitiesMappingType = &EntitlementMapType{ + Identifier: "CapabilitiesMapping", + Relations: []EntitlementRelation{ + EntitlementRelation{ + Input: CapabilitiesType, + Output: CapabilitiesType, + }, + EntitlementRelation{ + Input: StorageCapabilitiesType, + Output: StorageCapabilitiesType, + }, + EntitlementRelation{ + Input: AccountCapabilitiesType, + Output: AccountCapabilitiesType, + }, + EntitlementRelation{ + Input: GetStorageCapabilityControllerType, + Output: GetStorageCapabilityControllerType, + }, + EntitlementRelation{ + Input: IssueStorageCapabilityControllerType, + Output: IssueStorageCapabilityControllerType, + }, + EntitlementRelation{ + Input: GetAccountCapabilityControllerType, + Output: GetAccountCapabilityControllerType, + }, + EntitlementRelation{ + Input: IssueAccountCapabilityControllerType, + Output: IssueAccountCapabilityControllerType, + }, + EntitlementRelation{ + Input: StorageCapabilitiesType, + Output: GetStorageCapabilityControllerType, + }, + EntitlementRelation{ + Input: StorageCapabilitiesType, + Output: IssueStorageCapabilityControllerType, + }, + EntitlementRelation{ + Input: AccountCapabilitiesType, + Output: GetAccountCapabilityControllerType, + }, + EntitlementRelation{ + Input: AccountCapabilitiesType, + Output: IssueAccountCapabilityControllerType, + }, + }, +} + +func init() { + BuiltinEntitlementMappings[AccountMappingType.Identifier] = AccountMappingType + addToBaseActivation(AccountMappingType) + BuiltinEntitlementMappings[CapabilitiesMappingType.Identifier] = CapabilitiesMappingType + addToBaseActivation(CapabilitiesMappingType) + BuiltinEntitlements[StorageType.Identifier] = StorageType + addToBaseActivation(StorageType) + BuiltinEntitlements[SaveValueType.Identifier] = SaveValueType + addToBaseActivation(SaveValueType) + BuiltinEntitlements[LoadValueType.Identifier] = LoadValueType + addToBaseActivation(LoadValueType) + BuiltinEntitlements[BorrowValueType.Identifier] = BorrowValueType + addToBaseActivation(BorrowValueType) + BuiltinEntitlements[ContractsType.Identifier] = ContractsType + addToBaseActivation(ContractsType) + BuiltinEntitlements[AddContractType.Identifier] = AddContractType + addToBaseActivation(AddContractType) + BuiltinEntitlements[UpdateContractType.Identifier] = UpdateContractType + addToBaseActivation(UpdateContractType) + BuiltinEntitlements[RemoveContractType.Identifier] = RemoveContractType + addToBaseActivation(RemoveContractType) + BuiltinEntitlements[KeysType.Identifier] = KeysType + addToBaseActivation(KeysType) + BuiltinEntitlements[AddKeyType.Identifier] = AddKeyType + addToBaseActivation(AddKeyType) + BuiltinEntitlements[RevokeKeyType.Identifier] = RevokeKeyType + addToBaseActivation(RevokeKeyType) + BuiltinEntitlements[InboxType.Identifier] = InboxType + addToBaseActivation(InboxType) + BuiltinEntitlements[PublishInboxCapabilityType.Identifier] = PublishInboxCapabilityType + addToBaseActivation(PublishInboxCapabilityType) + BuiltinEntitlements[UnpublishInboxCapabilityType.Identifier] = UnpublishInboxCapabilityType + addToBaseActivation(UnpublishInboxCapabilityType) + BuiltinEntitlements[ClaimInboxCapabilityType.Identifier] = ClaimInboxCapabilityType + addToBaseActivation(ClaimInboxCapabilityType) + BuiltinEntitlements[CapabilitiesType.Identifier] = CapabilitiesType + addToBaseActivation(CapabilitiesType) + BuiltinEntitlements[StorageCapabilitiesType.Identifier] = StorageCapabilitiesType + addToBaseActivation(StorageCapabilitiesType) + BuiltinEntitlements[AccountCapabilitiesType.Identifier] = AccountCapabilitiesType + addToBaseActivation(AccountCapabilitiesType) + BuiltinEntitlements[PublishCapabilityType.Identifier] = PublishCapabilityType + addToBaseActivation(PublishCapabilityType) + BuiltinEntitlements[UnpublishCapabilityType.Identifier] = UnpublishCapabilityType + addToBaseActivation(UnpublishCapabilityType) + BuiltinEntitlements[GetStorageCapabilityControllerType.Identifier] = GetStorageCapabilityControllerType + addToBaseActivation(GetStorageCapabilityControllerType) + BuiltinEntitlements[IssueStorageCapabilityControllerType.Identifier] = IssueStorageCapabilityControllerType + addToBaseActivation(IssueStorageCapabilityControllerType) + BuiltinEntitlements[GetAccountCapabilityControllerType.Identifier] = GetAccountCapabilityControllerType + addToBaseActivation(GetAccountCapabilityControllerType) + BuiltinEntitlements[IssueAccountCapabilityControllerType.Identifier] = IssueAccountCapabilityControllerType + addToBaseActivation(IssueAccountCapabilityControllerType) +} diff --git a/runtime/sema/account.go b/runtime/sema/account.go new file mode 100644 index 0000000000..ad7d988c1a --- /dev/null +++ b/runtime/sema/account.go @@ -0,0 +1,59 @@ +/* + * Cadence - The resource-oriented smart contract programming language + * + * Copyright Dapper Labs, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package sema + +//go:generate go run ./gen account.cdc account.gen.go + +var AccountTypeAnnotation = NewTypeAnnotation(AccountType) + +var AccountReferenceType = &ReferenceType{ + Authorization: UnauthorizedAccess, + Type: AccountType, +} + +var AccountReferenceTypeAnnotation = NewTypeAnnotation(AccountReferenceType) + +// FullyEntitledAccountAccess represents +// +// auth(Storage, Contracts, Keys, Inbox, Capabilities) +var FullyEntitledAccountAccess = NewEntitlementSetAccess( + []*EntitlementType{ + StorageType, + ContractsType, + KeysType, + InboxType, + CapabilitiesType, + }, + Conjunction, +) + +// FullyEntitledAccountReferenceType represents the type +// +// auth(Storage, Contracts, Keys, Inbox, Capabilities) &Account +var FullyEntitledAccountReferenceType = &ReferenceType{ + Authorization: FullyEntitledAccountAccess, + Type: AccountType, +} + +var FullyEntitledAccountReferenceTypeAnnotation = NewTypeAnnotation(FullyEntitledAccountReferenceType) + +func init() { + Account_ContractsTypeAddFunctionType.Arity = &Arity{Min: 2} + +} diff --git a/runtime/sema/account_capability_controller.gen.go b/runtime/sema/account_capability_controller.gen.go index 336e479b19..c91e435e17 100644 --- a/runtime/sema/account_capability_controller.gen.go +++ b/runtime/sema/account_capability_controller.gen.go @@ -117,7 +117,7 @@ func init() { return MembersAsResolvers([]*Member{ NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, AccountCapabilityControllerTypeCapabilityFieldName, AccountCapabilityControllerTypeCapabilityFieldType, @@ -125,7 +125,7 @@ func init() { ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindVariable, AccountCapabilityControllerTypeTagFieldName, AccountCapabilityControllerTypeTagFieldType, @@ -133,14 +133,14 @@ func init() { ), NewUnmeteredFunctionMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), AccountCapabilityControllerTypeSetTagFunctionName, AccountCapabilityControllerTypeSetTagFunctionType, AccountCapabilityControllerTypeSetTagFunctionDocString, ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, AccountCapabilityControllerTypeBorrowTypeFieldName, AccountCapabilityControllerTypeBorrowTypeFieldType, @@ -148,7 +148,7 @@ func init() { ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, AccountCapabilityControllerTypeCapabilityIDFieldName, AccountCapabilityControllerTypeCapabilityIDFieldType, @@ -156,7 +156,7 @@ func init() { ), NewUnmeteredFunctionMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), AccountCapabilityControllerTypeDeleteFunctionName, AccountCapabilityControllerTypeDeleteFunctionType, AccountCapabilityControllerTypeDeleteFunctionDocString, diff --git a/runtime/sema/authaccount.cdc b/runtime/sema/authaccount.cdc deleted file mode 100644 index 14bf6f0f5b..0000000000 --- a/runtime/sema/authaccount.cdc +++ /dev/null @@ -1,416 +0,0 @@ - -access(all) -struct AuthAccount { - - /// The address of the account. - access(all) - let address: Address - - /// The FLOW balance of the default vault of this account. - access(all) - let balance: UFix64 - - /// The FLOW balance of the default vault of this account that is available to be moved. - access(all) - let availableBalance: UFix64 - - /// The current amount of storage used by the account in bytes. - access(all) - let storageUsed: UInt64 - - /// The storage capacity of the account in bytes. - access(all) - let storageCapacity: UInt64 - - /// The contracts deployed to the account. - access(all) - let contracts: AuthAccount.Contracts - - /// The keys assigned to the account. - access(all) - let keys: AuthAccount.Keys - - /// The inbox allows bootstrapping (sending and receiving) capabilities. - access(all) - let inbox: AuthAccount.Inbox - - /// The capabilities of the account. - access(all) - let capabilities: AuthAccount.Capabilities - - /// All public paths of this account. - access(all) - let publicPaths: [PublicPath] - - /// All private paths of this account. - access(all) - let privatePaths: [PrivatePath] - - /// All storage paths of this account. - access(all) - let storagePaths: [StoragePath] - - /// Saves the given object into the account's storage at the given path. - /// - /// Resources are moved into storage, and structures are copied. - /// - /// If there is already an object stored under the given path, the program aborts. - /// - /// The path must be a storage path, i.e., only the domain `storage` is allowed. - access(all) - fun save(_ value: T, to: StoragePath) - - /// Reads the type of an object from the account's storage which is stored under the given path, - /// or nil if no object is stored under the given path. - /// - /// If there is an object stored, the type of the object is returned without modifying the stored object. - /// - /// The path must be a storage path, i.e., only the domain `storage` is allowed. - access(all) - view fun type(at path: StoragePath): Type? - - /// Loads an object from the account's storage which is stored under the given path, - /// or nil if no object is stored under the given path. - /// - /// If there is an object stored, - /// the stored resource or structure is moved out of storage and returned as an optional. - /// - /// When the function returns, the storage no longer contains an object under the given path. - /// - /// The given type must be a supertype of the type of the loaded object. - /// If it is not, the function panics. - /// - /// The given type must not necessarily be exactly the same as the type of the loaded object. - /// - /// The path must be a storage path, i.e., only the domain `storage` is allowed. - access(all) - fun load(from: StoragePath): T? - - /// Returns a copy of a structure stored in account storage under the given path, - /// without removing it from storage, - /// or nil if no object is stored under the given path. - /// - /// If there is a structure stored, it is copied. - /// The structure stays stored in storage after the function returns. - /// - /// The given type must be a supertype of the type of the copied structure. - /// If it is not, the function panics. - /// - /// The given type must not necessarily be exactly the same as the type of the copied structure. - /// - /// The path must be a storage path, i.e., only the domain `storage` is allowed. - access(all) - view fun copy(from: StoragePath): T? - - /// Returns a reference to an object in storage without removing it from storage. - /// - /// If no object is stored under the given path, the function returns nil. - /// If there is an object stored, a reference is returned as an optional, - /// provided it can be borrowed using the given type. - /// If the stored object cannot be borrowed using the given type, the function panics. - /// - /// The given type must not necessarily be exactly the same as the type of the borrowed object. - /// - /// The path must be a storage path, i.e., only the domain `storage` is allowed - access(all) - view fun borrow(from: StoragePath): T? - - /// Returns true if the object in account storage under the given path satisfies the given type, - /// i.e. could be borrowed using the given type. - /// - /// The given type must not necessarily be exactly the same as the type of the borrowed object. - /// - /// The path must be a storage path, i.e., only the domain `storage` is allowed. - access(all) - view fun check(from: StoragePath): Bool - - /// Iterate over all the public paths of an account, - /// passing each path and type in turn to the provided callback function. - /// - /// The callback function takes two arguments: - /// 1. The path of the stored object - /// 2. The runtime type of that object - /// - /// Iteration is stopped early if the callback function returns `false`. - /// - /// The order of iteration is undefined. - /// - /// If an object is stored under a new public path, - /// or an existing object is removed from a public path, - /// then the callback must stop iteration by returning false. - /// Otherwise, iteration aborts. - /// - access(all) - fun forEachPublic(_ function: fun(PublicPath, Type): Bool) - - /// Iterate over all the private paths of an account, - /// passing each path and type in turn to the provided callback function. - /// - /// The callback function takes two arguments: - /// 1. The path of the stored object - /// 2. The runtime type of that object - /// - /// Iteration is stopped early if the callback function returns `false`. - /// - - /// The order of iteration is undefined. - /// - /// If an object is stored under a new private path, - /// or an existing object is removed from a private path, - /// then the callback must stop iteration by returning false. - /// Otherwise, iteration aborts. - access(all) - fun forEachPrivate(_ function: fun(PrivatePath, Type): Bool) - - /// Iterate over all the stored paths of an account, - /// passing each path and type in turn to the provided callback function. - /// - /// The callback function takes two arguments: - /// 1. The path of the stored object - /// 2. The runtime type of that object - /// - /// Iteration is stopped early if the callback function returns `false`. - /// - - /// If an object is stored under a new storage path, - /// or an existing object is removed from a storage path, - /// then the callback must stop iteration by returning false. - /// Otherwise, iteration aborts. - access(all) - fun forEachStored(_ function: fun(StoragePath, Type): Bool) - - access(all) - struct Contracts { - - /// The names of all contracts deployed in the account. - access(all) - let names: [String] - - /// Adds the given contract to the account. - /// - /// The `code` parameter is the UTF-8 encoded representation of the source code. - /// The code must contain exactly one contract or contract interface, - /// which must have the same name as the `name` parameter. - /// - /// All additional arguments that are given are passed further to the initializer - /// of the contract that is being deployed. - /// - /// The function fails if a contract/contract interface with the given name already exists in the account, - /// if the given code does not declare exactly one contract or contract interface, - /// or if the given name does not match the name of the contract/contract interface declaration in the code. - /// - /// Returns the deployed contract. - access(all) - fun add( - name: String, - code: [UInt8] - ): DeployedContract - - /// **Experimental** - /// - /// Updates the code for the contract/contract interface in the account. - /// - /// The `code` parameter is the UTF-8 encoded representation of the source code. - /// The code must contain exactly one contract or contract interface, - /// which must have the same name as the `name` parameter. - /// - /// Does **not** run the initializer of the contract/contract interface again. - /// The contract instance in the world state stays as is. - /// - /// Fails if no contract/contract interface with the given name exists in the account, - /// if the given code does not declare exactly one contract or contract interface, - /// or if the given name does not match the name of the contract/contract interface declaration in the code. - /// - /// Returns the deployed contract for the updated contract. - access(all) - fun update__experimental(name: String, code: [UInt8]): DeployedContract - - /// Returns the deployed contract for the contract/contract interface with the given name in the account, if any. - /// - /// Returns nil if no contract/contract interface with the given name exists in the account. - access(all) - view fun get(name: String): DeployedContract? - - /// Removes the contract/contract interface from the account which has the given name, if any. - /// - /// Returns the removed deployed contract, if any. - /// - /// Returns nil if no contract/contract interface with the given name exists in the account. - access(all) - fun remove(name: String): DeployedContract? - - /// Returns a reference of the given type to the contract with the given name in the account, if any. - /// - /// Returns nil if no contract with the given name exists in the account, - /// or if the contract does not conform to the given type. - access(all) - view fun borrow(name: String): T? - } - - access(all) - struct Keys { - - /// Adds a new key with the given hashing algorithm and a weight. - /// - /// Returns the added key. - access(all) - fun add( - publicKey: PublicKey, - hashAlgorithm: HashAlgorithm, - weight: UFix64 - ): AccountKey - - /// Returns the key at the given index, if it exists, or nil otherwise. - /// - /// Revoked keys are always returned, but they have `isRevoked` field set to true. - access(all) - view fun get(keyIndex: Int): AccountKey? - - /// Marks the key at the given index revoked, but does not delete it. - /// - /// Returns the revoked key if it exists, or nil otherwise. - access(all) - fun revoke(keyIndex: Int): AccountKey? - - /// Iterate over all unrevoked keys in this account, - /// passing each key in turn to the provided function. - /// - /// Iteration is stopped early if the function returns `false`. - /// - /// The order of iteration is undefined. - access(all) - fun forEach(_ function: fun(AccountKey): Bool) - - /// The total number of unrevoked keys in this account. - access(all) - let count: UInt64 - } - - access(all) - struct Inbox { - - /// Publishes a new Capability under the given name, - /// to be claimed by the specified recipient. - access(all) - fun publish(_ value: Capability, name: String, recipient: Address) - - /// Unpublishes a Capability previously published by this account. - /// - /// Returns `nil` if no Capability is published under the given name. - /// - /// Errors if the Capability under that name does not match the provided type. - access(all) - fun unpublish(_ name: String): Capability? - - /// Claims a Capability previously published by the specified provider. - /// - /// Returns `nil` if no Capability is published under the given name, - /// or if this account is not its intended recipient. - /// - /// Errors if the Capability under that name does not match the provided type. - access(all) - fun claim(_ name: String, provider: Address): Capability? - } - - access(all) - struct Capabilities { - - /// The storage capabilities of the account. - access(all) - let storage: AuthAccount.StorageCapabilities - - /// The account capabilities of the account. - access(all) - let account: AuthAccount.AccountCapabilities - - /// Returns the capability at the given public path. - /// Returns nil if the capability does not exist, - /// or if the given type is not a supertype of the capability's borrow type. - access(all) - view fun get(_ path: PublicPath): Capability? - - /// Borrows the capability at the given public path. - /// Returns nil if the capability does not exist, or cannot be borrowed using the given type. - /// The function is equivalent to `get(path)?.borrow()`. - access(all) - view fun borrow(_ path: PublicPath): T? - - /// Publish the capability at the given public path. - /// - /// If there is already a capability published under the given path, the program aborts. - /// - /// The path must be a public path, i.e., only the domain `public` is allowed. - access(all) - fun publish(_ capability: Capability, at: PublicPath) - - /// Unpublish the capability published at the given path. - /// - /// Returns the capability if one was published at the path. - /// Returns nil if no capability was published at the path. - access(all) - fun unpublish(_ path: PublicPath): Capability? - } - - access(all) - struct StorageCapabilities { - - /// Get the storage capability controller for the capability with the specified ID. - /// - /// Returns nil if the ID does not reference an existing storage capability. - access(all) - view fun getController(byCapabilityID: UInt64): &StorageCapabilityController? - - /// Get all storage capability controllers for capabilities that target this storage path - access(all) - view fun getControllers(forPath: StoragePath): [&StorageCapabilityController] - - /// Iterate over all storage capability controllers for capabilities that target this storage path, - /// passing a reference to each controller to the provided callback function. - /// - /// Iteration is stopped early if the callback function returns `false`. - /// - /// If a new storage capability controller is issued for the path, - /// an existing storage capability controller for the path is deleted, - /// or a storage capability controller is retargeted from or to the path, - /// then the callback must stop iteration by returning false. - /// Otherwise, iteration aborts. - access(all) - fun forEachController( - forPath: StoragePath, - _ function: fun(&StorageCapabilityController): Bool - ) - - /// Issue/create a new storage capability. - access(all) - fun issue(_ path: StoragePath): Capability - } - - access(all) - struct AccountCapabilities { - /// Get capability controller for capability with the specified ID. - /// - /// Returns nil if the ID does not reference an existing account capability. - access(all) - view fun getController(byCapabilityID: UInt64): &AccountCapabilityController? - - /// Get all capability controllers for all account capabilities. - access(all) - view fun getControllers(): [&AccountCapabilityController] - - /// Iterate over all account capability controllers for all account capabilities, - /// passing a reference to each controller to the provided callback function. - /// - /// Iteration is stopped early if the callback function returns `false`. - /// - /// If a new account capability controller is issued for the account, - /// or an existing account capability controller for the account is deleted, - /// then the callback must stop iteration by returning false. - /// Otherwise, iteration aborts. - access(all) - fun forEachController(_ function: fun(&AccountCapabilityController): Bool) - - /// Issue/create a new account capability. - access(all) - fun issue(): Capability - } -} diff --git a/runtime/sema/authaccount.gen.go b/runtime/sema/authaccount.gen.go deleted file mode 100644 index 1314fbcf5d..0000000000 --- a/runtime/sema/authaccount.gen.go +++ /dev/null @@ -1,1782 +0,0 @@ -// Code generated from authaccount.cdc. DO NOT EDIT. -/* - * Cadence - The resource-oriented smart contract programming language - * - * Copyright Dapper Labs, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package sema - -import ( - "github.com/onflow/cadence/runtime/ast" - "github.com/onflow/cadence/runtime/common" -) - -const AuthAccountTypeAddressFieldName = "address" - -var AuthAccountTypeAddressFieldType = TheAddressType - -const AuthAccountTypeAddressFieldDocString = ` -The address of the account. -` - -const AuthAccountTypeBalanceFieldName = "balance" - -var AuthAccountTypeBalanceFieldType = UFix64Type - -const AuthAccountTypeBalanceFieldDocString = ` -The FLOW balance of the default vault of this account. -` - -const AuthAccountTypeAvailableBalanceFieldName = "availableBalance" - -var AuthAccountTypeAvailableBalanceFieldType = UFix64Type - -const AuthAccountTypeAvailableBalanceFieldDocString = ` -The FLOW balance of the default vault of this account that is available to be moved. -` - -const AuthAccountTypeStorageUsedFieldName = "storageUsed" - -var AuthAccountTypeStorageUsedFieldType = UInt64Type - -const AuthAccountTypeStorageUsedFieldDocString = ` -The current amount of storage used by the account in bytes. -` - -const AuthAccountTypeStorageCapacityFieldName = "storageCapacity" - -var AuthAccountTypeStorageCapacityFieldType = UInt64Type - -const AuthAccountTypeStorageCapacityFieldDocString = ` -The storage capacity of the account in bytes. -` - -const AuthAccountTypeContractsFieldName = "contracts" - -var AuthAccountTypeContractsFieldType = AuthAccountContractsType - -const AuthAccountTypeContractsFieldDocString = ` -The contracts deployed to the account. -` - -const AuthAccountTypeKeysFieldName = "keys" - -var AuthAccountTypeKeysFieldType = AuthAccountKeysType - -const AuthAccountTypeKeysFieldDocString = ` -The keys assigned to the account. -` - -const AuthAccountTypeInboxFieldName = "inbox" - -var AuthAccountTypeInboxFieldType = AuthAccountInboxType - -const AuthAccountTypeInboxFieldDocString = ` -The inbox allows bootstrapping (sending and receiving) capabilities. -` - -const AuthAccountTypeCapabilitiesFieldName = "capabilities" - -var AuthAccountTypeCapabilitiesFieldType = AuthAccountCapabilitiesType - -const AuthAccountTypeCapabilitiesFieldDocString = ` -The capabilities of the account. -` - -const AuthAccountTypePublicPathsFieldName = "publicPaths" - -var AuthAccountTypePublicPathsFieldType = &VariableSizedType{ - Type: PublicPathType, -} - -const AuthAccountTypePublicPathsFieldDocString = ` -All public paths of this account. -` - -const AuthAccountTypePrivatePathsFieldName = "privatePaths" - -var AuthAccountTypePrivatePathsFieldType = &VariableSizedType{ - Type: PrivatePathType, -} - -const AuthAccountTypePrivatePathsFieldDocString = ` -All private paths of this account. -` - -const AuthAccountTypeStoragePathsFieldName = "storagePaths" - -var AuthAccountTypeStoragePathsFieldType = &VariableSizedType{ - Type: StoragePathType, -} - -const AuthAccountTypeStoragePathsFieldDocString = ` -All storage paths of this account. -` - -const AuthAccountTypeSaveFunctionName = "save" - -var AuthAccountTypeSaveFunctionTypeParameterT = &TypeParameter{ - Name: "T", - TypeBound: StorableType, -} - -var AuthAccountTypeSaveFunctionType = &FunctionType{ - TypeParameters: []*TypeParameter{ - AuthAccountTypeSaveFunctionTypeParameterT, - }, - Parameters: []Parameter{ - { - Label: ArgumentLabelNotRequired, - Identifier: "value", - TypeAnnotation: NewTypeAnnotation(&GenericType{ - TypeParameter: AuthAccountTypeSaveFunctionTypeParameterT, - }), - }, - { - Identifier: "to", - TypeAnnotation: NewTypeAnnotation(StoragePathType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - VoidType, - ), -} - -const AuthAccountTypeSaveFunctionDocString = ` -Saves the given object into the account's storage at the given path. - -Resources are moved into storage, and structures are copied. - -If there is already an object stored under the given path, the program aborts. - -The path must be a storage path, i.e., only the domain ` + "`storage`" + ` is allowed. -` - -const AuthAccountTypeTypeFunctionName = "type" - -var AuthAccountTypeTypeFunctionType = &FunctionType{ - Purity: FunctionPurityView, - Parameters: []Parameter{ - { - Label: "at", - Identifier: "path", - TypeAnnotation: NewTypeAnnotation(StoragePathType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - &OptionalType{ - Type: MetaType, - }, - ), -} - -const AuthAccountTypeTypeFunctionDocString = ` -Reads the type of an object from the account's storage which is stored under the given path, -or nil if no object is stored under the given path. - -If there is an object stored, the type of the object is returned without modifying the stored object. - -The path must be a storage path, i.e., only the domain ` + "`storage`" + ` is allowed. -` - -const AuthAccountTypeLoadFunctionName = "load" - -var AuthAccountTypeLoadFunctionTypeParameterT = &TypeParameter{ - Name: "T", - TypeBound: StorableType, -} - -var AuthAccountTypeLoadFunctionType = &FunctionType{ - TypeParameters: []*TypeParameter{ - AuthAccountTypeLoadFunctionTypeParameterT, - }, - Parameters: []Parameter{ - { - Identifier: "from", - TypeAnnotation: NewTypeAnnotation(StoragePathType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - &OptionalType{ - Type: &GenericType{ - TypeParameter: AuthAccountTypeLoadFunctionTypeParameterT, - }, - }, - ), -} - -const AuthAccountTypeLoadFunctionDocString = ` -Loads an object from the account's storage which is stored under the given path, -or nil if no object is stored under the given path. - -If there is an object stored, -the stored resource or structure is moved out of storage and returned as an optional. - -When the function returns, the storage no longer contains an object under the given path. - -The given type must be a supertype of the type of the loaded object. -If it is not, the function panics. - -The given type must not necessarily be exactly the same as the type of the loaded object. - -The path must be a storage path, i.e., only the domain ` + "`storage`" + ` is allowed. -` - -const AuthAccountTypeCopyFunctionName = "copy" - -var AuthAccountTypeCopyFunctionTypeParameterT = &TypeParameter{ - Name: "T", - TypeBound: AnyStructType, -} - -var AuthAccountTypeCopyFunctionType = &FunctionType{ - Purity: FunctionPurityView, - TypeParameters: []*TypeParameter{ - AuthAccountTypeCopyFunctionTypeParameterT, - }, - Parameters: []Parameter{ - { - Identifier: "from", - TypeAnnotation: NewTypeAnnotation(StoragePathType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - &OptionalType{ - Type: &GenericType{ - TypeParameter: AuthAccountTypeCopyFunctionTypeParameterT, - }, - }, - ), -} - -const AuthAccountTypeCopyFunctionDocString = ` -Returns a copy of a structure stored in account storage under the given path, -without removing it from storage, -or nil if no object is stored under the given path. - -If there is a structure stored, it is copied. -The structure stays stored in storage after the function returns. - -The given type must be a supertype of the type of the copied structure. -If it is not, the function panics. - -The given type must not necessarily be exactly the same as the type of the copied structure. - -The path must be a storage path, i.e., only the domain ` + "`storage`" + ` is allowed. -` - -const AuthAccountTypeBorrowFunctionName = "borrow" - -var AuthAccountTypeBorrowFunctionTypeParameterT = &TypeParameter{ - Name: "T", - TypeBound: &ReferenceType{ - Type: AnyType, - Authorization: UnauthorizedAccess, - }, -} - -var AuthAccountTypeBorrowFunctionType = &FunctionType{ - Purity: FunctionPurityView, - TypeParameters: []*TypeParameter{ - AuthAccountTypeBorrowFunctionTypeParameterT, - }, - Parameters: []Parameter{ - { - Identifier: "from", - TypeAnnotation: NewTypeAnnotation(StoragePathType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - &OptionalType{ - Type: &GenericType{ - TypeParameter: AuthAccountTypeBorrowFunctionTypeParameterT, - }, - }, - ), -} - -const AuthAccountTypeBorrowFunctionDocString = ` -Returns a reference to an object in storage without removing it from storage. - -If no object is stored under the given path, the function returns nil. -If there is an object stored, a reference is returned as an optional, -provided it can be borrowed using the given type. -If the stored object cannot be borrowed using the given type, the function panics. - -The given type must not necessarily be exactly the same as the type of the borrowed object. - -The path must be a storage path, i.e., only the domain ` + "`storage`" + ` is allowed -` - -const AuthAccountTypeCheckFunctionName = "check" - -var AuthAccountTypeCheckFunctionTypeParameterT = &TypeParameter{ - Name: "T", - TypeBound: AnyType, -} - -var AuthAccountTypeCheckFunctionType = &FunctionType{ - Purity: FunctionPurityView, - TypeParameters: []*TypeParameter{ - AuthAccountTypeCheckFunctionTypeParameterT, - }, - Parameters: []Parameter{ - { - Identifier: "from", - TypeAnnotation: NewTypeAnnotation(StoragePathType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - BoolType, - ), -} - -const AuthAccountTypeCheckFunctionDocString = ` -Returns true if the object in account storage under the given path satisfies the given type, -i.e. could be borrowed using the given type. - -The given type must not necessarily be exactly the same as the type of the borrowed object. - -The path must be a storage path, i.e., only the domain ` + "`storage`" + ` is allowed. -` - -const AuthAccountTypeForEachPublicFunctionName = "forEachPublic" - -var AuthAccountTypeForEachPublicFunctionType = &FunctionType{ - Parameters: []Parameter{ - { - Label: ArgumentLabelNotRequired, - Identifier: "function", - TypeAnnotation: NewTypeAnnotation(&FunctionType{ - Parameters: []Parameter{ - { - TypeAnnotation: NewTypeAnnotation(PublicPathType), - }, - { - TypeAnnotation: NewTypeAnnotation(MetaType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - BoolType, - ), - }), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - VoidType, - ), -} - -const AuthAccountTypeForEachPublicFunctionDocString = ` -Iterate over all the public paths of an account, -passing each path and type in turn to the provided callback function. - -The callback function takes two arguments: -1. The path of the stored object -2. The runtime type of that object - -Iteration is stopped early if the callback function returns ` + "`false`" + `. - -The order of iteration is undefined. - -If an object is stored under a new public path, -or an existing object is removed from a public path, -then the callback must stop iteration by returning false. -Otherwise, iteration aborts. -` - -const AuthAccountTypeForEachPrivateFunctionName = "forEachPrivate" - -var AuthAccountTypeForEachPrivateFunctionType = &FunctionType{ - Parameters: []Parameter{ - { - Label: ArgumentLabelNotRequired, - Identifier: "function", - TypeAnnotation: NewTypeAnnotation(&FunctionType{ - Parameters: []Parameter{ - { - TypeAnnotation: NewTypeAnnotation(PrivatePathType), - }, - { - TypeAnnotation: NewTypeAnnotation(MetaType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - BoolType, - ), - }), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - VoidType, - ), -} - -const AuthAccountTypeForEachPrivateFunctionDocString = ` -Iterate over all the private paths of an account, -passing each path and type in turn to the provided callback function. - -The callback function takes two arguments: -1. The path of the stored object -2. The runtime type of that object - -Iteration is stopped early if the callback function returns ` + "`false`" + `. - -The order of iteration is undefined. - -If an object is stored under a new private path, -or an existing object is removed from a private path, -then the callback must stop iteration by returning false. -Otherwise, iteration aborts. -` - -const AuthAccountTypeForEachStoredFunctionName = "forEachStored" - -var AuthAccountTypeForEachStoredFunctionType = &FunctionType{ - Parameters: []Parameter{ - { - Label: ArgumentLabelNotRequired, - Identifier: "function", - TypeAnnotation: NewTypeAnnotation(&FunctionType{ - Parameters: []Parameter{ - { - TypeAnnotation: NewTypeAnnotation(StoragePathType), - }, - { - TypeAnnotation: NewTypeAnnotation(MetaType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - BoolType, - ), - }), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - VoidType, - ), -} - -const AuthAccountTypeForEachStoredFunctionDocString = ` -Iterate over all the stored paths of an account, -passing each path and type in turn to the provided callback function. - -The callback function takes two arguments: -1. The path of the stored object -2. The runtime type of that object - -Iteration is stopped early if the callback function returns ` + "`false`" + `. - -If an object is stored under a new storage path, -or an existing object is removed from a storage path, -then the callback must stop iteration by returning false. -Otherwise, iteration aborts. -` - -const AuthAccountContractsTypeNamesFieldName = "names" - -var AuthAccountContractsTypeNamesFieldType = &VariableSizedType{ - Type: StringType, -} - -const AuthAccountContractsTypeNamesFieldDocString = ` -The names of all contracts deployed in the account. -` - -const AuthAccountContractsTypeAddFunctionName = "add" - -var AuthAccountContractsTypeAddFunctionType = &FunctionType{ - Parameters: []Parameter{ - { - Identifier: "name", - TypeAnnotation: NewTypeAnnotation(StringType), - }, - { - Identifier: "code", - TypeAnnotation: NewTypeAnnotation(&VariableSizedType{ - Type: UInt8Type, - }), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - DeployedContractType, - ), -} - -const AuthAccountContractsTypeAddFunctionDocString = ` -Adds the given contract to the account. - -The ` + "`code`" + ` parameter is the UTF-8 encoded representation of the source code. -The code must contain exactly one contract or contract interface, -which must have the same name as the ` + "`name`" + ` parameter. - -All additional arguments that are given are passed further to the initializer -of the contract that is being deployed. - -The function fails if a contract/contract interface with the given name already exists in the account, -if the given code does not declare exactly one contract or contract interface, -or if the given name does not match the name of the contract/contract interface declaration in the code. - -Returns the deployed contract. -` - -const AuthAccountContractsTypeUpdate__experimentalFunctionName = "update__experimental" - -var AuthAccountContractsTypeUpdate__experimentalFunctionType = &FunctionType{ - Parameters: []Parameter{ - { - Identifier: "name", - TypeAnnotation: NewTypeAnnotation(StringType), - }, - { - Identifier: "code", - TypeAnnotation: NewTypeAnnotation(&VariableSizedType{ - Type: UInt8Type, - }), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - DeployedContractType, - ), -} - -const AuthAccountContractsTypeUpdate__experimentalFunctionDocString = ` -**Experimental** - -Updates the code for the contract/contract interface in the account. - -The ` + "`code`" + ` parameter is the UTF-8 encoded representation of the source code. -The code must contain exactly one contract or contract interface, -which must have the same name as the ` + "`name`" + ` parameter. - -Does **not** run the initializer of the contract/contract interface again. -The contract instance in the world state stays as is. - -Fails if no contract/contract interface with the given name exists in the account, -if the given code does not declare exactly one contract or contract interface, -or if the given name does not match the name of the contract/contract interface declaration in the code. - -Returns the deployed contract for the updated contract. -` - -const AuthAccountContractsTypeGetFunctionName = "get" - -var AuthAccountContractsTypeGetFunctionType = &FunctionType{ - Purity: FunctionPurityView, - Parameters: []Parameter{ - { - Identifier: "name", - TypeAnnotation: NewTypeAnnotation(StringType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - &OptionalType{ - Type: DeployedContractType, - }, - ), -} - -const AuthAccountContractsTypeGetFunctionDocString = ` -Returns the deployed contract for the contract/contract interface with the given name in the account, if any. - -Returns nil if no contract/contract interface with the given name exists in the account. -` - -const AuthAccountContractsTypeRemoveFunctionName = "remove" - -var AuthAccountContractsTypeRemoveFunctionType = &FunctionType{ - Parameters: []Parameter{ - { - Identifier: "name", - TypeAnnotation: NewTypeAnnotation(StringType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - &OptionalType{ - Type: DeployedContractType, - }, - ), -} - -const AuthAccountContractsTypeRemoveFunctionDocString = ` -Removes the contract/contract interface from the account which has the given name, if any. - -Returns the removed deployed contract, if any. - -Returns nil if no contract/contract interface with the given name exists in the account. -` - -const AuthAccountContractsTypeBorrowFunctionName = "borrow" - -var AuthAccountContractsTypeBorrowFunctionTypeParameterT = &TypeParameter{ - Name: "T", - TypeBound: &ReferenceType{ - Type: AnyType, - Authorization: UnauthorizedAccess, - }, -} - -var AuthAccountContractsTypeBorrowFunctionType = &FunctionType{ - Purity: FunctionPurityView, - TypeParameters: []*TypeParameter{ - AuthAccountContractsTypeBorrowFunctionTypeParameterT, - }, - Parameters: []Parameter{ - { - Identifier: "name", - TypeAnnotation: NewTypeAnnotation(StringType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - &OptionalType{ - Type: &GenericType{ - TypeParameter: AuthAccountContractsTypeBorrowFunctionTypeParameterT, - }, - }, - ), -} - -const AuthAccountContractsTypeBorrowFunctionDocString = ` -Returns a reference of the given type to the contract with the given name in the account, if any. - -Returns nil if no contract with the given name exists in the account, -or if the contract does not conform to the given type. -` - -const AuthAccountContractsTypeName = "Contracts" - -var AuthAccountContractsType = func() *CompositeType { - var t = &CompositeType{ - Identifier: AuthAccountContractsTypeName, - Kind: common.CompositeKindStructure, - importable: false, - hasComputedMembers: true, - } - - return t -}() - -func init() { - var members = []*Member{ - NewUnmeteredFieldMember( - AuthAccountContractsType, - ast.AccessAll, - ast.VariableKindConstant, - AuthAccountContractsTypeNamesFieldName, - AuthAccountContractsTypeNamesFieldType, - AuthAccountContractsTypeNamesFieldDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountContractsType, - ast.AccessAll, - AuthAccountContractsTypeAddFunctionName, - AuthAccountContractsTypeAddFunctionType, - AuthAccountContractsTypeAddFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountContractsType, - ast.AccessAll, - AuthAccountContractsTypeUpdate__experimentalFunctionName, - AuthAccountContractsTypeUpdate__experimentalFunctionType, - AuthAccountContractsTypeUpdate__experimentalFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountContractsType, - ast.AccessAll, - AuthAccountContractsTypeGetFunctionName, - AuthAccountContractsTypeGetFunctionType, - AuthAccountContractsTypeGetFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountContractsType, - ast.AccessAll, - AuthAccountContractsTypeRemoveFunctionName, - AuthAccountContractsTypeRemoveFunctionType, - AuthAccountContractsTypeRemoveFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountContractsType, - ast.AccessAll, - AuthAccountContractsTypeBorrowFunctionName, - AuthAccountContractsTypeBorrowFunctionType, - AuthAccountContractsTypeBorrowFunctionDocString, - ), - } - - AuthAccountContractsType.Members = MembersAsMap(members) - AuthAccountContractsType.Fields = MembersFieldNames(members) -} - -const AuthAccountKeysTypeAddFunctionName = "add" - -var AuthAccountKeysTypeAddFunctionType = &FunctionType{ - Parameters: []Parameter{ - { - Identifier: "publicKey", - TypeAnnotation: NewTypeAnnotation(PublicKeyType), - }, - { - Identifier: "hashAlgorithm", - TypeAnnotation: NewTypeAnnotation(HashAlgorithmType), - }, - { - Identifier: "weight", - TypeAnnotation: NewTypeAnnotation(UFix64Type), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - AccountKeyType, - ), -} - -const AuthAccountKeysTypeAddFunctionDocString = ` -Adds a new key with the given hashing algorithm and a weight. - -Returns the added key. -` - -const AuthAccountKeysTypeGetFunctionName = "get" - -var AuthAccountKeysTypeGetFunctionType = &FunctionType{ - Purity: FunctionPurityView, - Parameters: []Parameter{ - { - Identifier: "keyIndex", - TypeAnnotation: NewTypeAnnotation(IntType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - &OptionalType{ - Type: AccountKeyType, - }, - ), -} - -const AuthAccountKeysTypeGetFunctionDocString = ` -Returns the key at the given index, if it exists, or nil otherwise. - -Revoked keys are always returned, but they have ` + "`isRevoked`" + ` field set to true. -` - -const AuthAccountKeysTypeRevokeFunctionName = "revoke" - -var AuthAccountKeysTypeRevokeFunctionType = &FunctionType{ - Parameters: []Parameter{ - { - Identifier: "keyIndex", - TypeAnnotation: NewTypeAnnotation(IntType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - &OptionalType{ - Type: AccountKeyType, - }, - ), -} - -const AuthAccountKeysTypeRevokeFunctionDocString = ` -Marks the key at the given index revoked, but does not delete it. - -Returns the revoked key if it exists, or nil otherwise. -` - -const AuthAccountKeysTypeForEachFunctionName = "forEach" - -var AuthAccountKeysTypeForEachFunctionType = &FunctionType{ - Parameters: []Parameter{ - { - Label: ArgumentLabelNotRequired, - Identifier: "function", - TypeAnnotation: NewTypeAnnotation(&FunctionType{ - Parameters: []Parameter{ - { - TypeAnnotation: NewTypeAnnotation(AccountKeyType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - BoolType, - ), - }), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - VoidType, - ), -} - -const AuthAccountKeysTypeForEachFunctionDocString = ` -Iterate over all unrevoked keys in this account, -passing each key in turn to the provided function. - -Iteration is stopped early if the function returns ` + "`false`" + `. - -The order of iteration is undefined. -` - -const AuthAccountKeysTypeCountFieldName = "count" - -var AuthAccountKeysTypeCountFieldType = UInt64Type - -const AuthAccountKeysTypeCountFieldDocString = ` -The total number of unrevoked keys in this account. -` - -const AuthAccountKeysTypeName = "Keys" - -var AuthAccountKeysType = func() *CompositeType { - var t = &CompositeType{ - Identifier: AuthAccountKeysTypeName, - Kind: common.CompositeKindStructure, - importable: false, - hasComputedMembers: true, - } - - return t -}() - -func init() { - var members = []*Member{ - NewUnmeteredFunctionMember( - AuthAccountKeysType, - ast.AccessAll, - AuthAccountKeysTypeAddFunctionName, - AuthAccountKeysTypeAddFunctionType, - AuthAccountKeysTypeAddFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountKeysType, - ast.AccessAll, - AuthAccountKeysTypeGetFunctionName, - AuthAccountKeysTypeGetFunctionType, - AuthAccountKeysTypeGetFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountKeysType, - ast.AccessAll, - AuthAccountKeysTypeRevokeFunctionName, - AuthAccountKeysTypeRevokeFunctionType, - AuthAccountKeysTypeRevokeFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountKeysType, - ast.AccessAll, - AuthAccountKeysTypeForEachFunctionName, - AuthAccountKeysTypeForEachFunctionType, - AuthAccountKeysTypeForEachFunctionDocString, - ), - NewUnmeteredFieldMember( - AuthAccountKeysType, - ast.AccessAll, - ast.VariableKindConstant, - AuthAccountKeysTypeCountFieldName, - AuthAccountKeysTypeCountFieldType, - AuthAccountKeysTypeCountFieldDocString, - ), - } - - AuthAccountKeysType.Members = MembersAsMap(members) - AuthAccountKeysType.Fields = MembersFieldNames(members) -} - -const AuthAccountInboxTypePublishFunctionName = "publish" - -var AuthAccountInboxTypePublishFunctionType = &FunctionType{ - Parameters: []Parameter{ - { - Label: ArgumentLabelNotRequired, - Identifier: "value", - TypeAnnotation: NewTypeAnnotation(&CapabilityType{}), - }, - { - Identifier: "name", - TypeAnnotation: NewTypeAnnotation(StringType), - }, - { - Identifier: "recipient", - TypeAnnotation: NewTypeAnnotation(TheAddressType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - VoidType, - ), -} - -const AuthAccountInboxTypePublishFunctionDocString = ` -Publishes a new Capability under the given name, -to be claimed by the specified recipient. -` - -const AuthAccountInboxTypeUnpublishFunctionName = "unpublish" - -var AuthAccountInboxTypeUnpublishFunctionTypeParameterT = &TypeParameter{ - Name: "T", - TypeBound: &ReferenceType{ - Type: AnyType, - Authorization: UnauthorizedAccess, - }, -} - -var AuthAccountInboxTypeUnpublishFunctionType = &FunctionType{ - TypeParameters: []*TypeParameter{ - AuthAccountInboxTypeUnpublishFunctionTypeParameterT, - }, - Parameters: []Parameter{ - { - Label: ArgumentLabelNotRequired, - Identifier: "name", - TypeAnnotation: NewTypeAnnotation(StringType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - &OptionalType{ - Type: MustInstantiate( - &CapabilityType{}, - &GenericType{ - TypeParameter: AuthAccountInboxTypeUnpublishFunctionTypeParameterT, - }, - ), - }, - ), -} - -const AuthAccountInboxTypeUnpublishFunctionDocString = ` -Unpublishes a Capability previously published by this account. - -Returns ` + "`nil`" + ` if no Capability is published under the given name. - -Errors if the Capability under that name does not match the provided type. -` - -const AuthAccountInboxTypeClaimFunctionName = "claim" - -var AuthAccountInboxTypeClaimFunctionTypeParameterT = &TypeParameter{ - Name: "T", - TypeBound: &ReferenceType{ - Type: AnyType, - Authorization: UnauthorizedAccess, - }, -} - -var AuthAccountInboxTypeClaimFunctionType = &FunctionType{ - TypeParameters: []*TypeParameter{ - AuthAccountInboxTypeClaimFunctionTypeParameterT, - }, - Parameters: []Parameter{ - { - Label: ArgumentLabelNotRequired, - Identifier: "name", - TypeAnnotation: NewTypeAnnotation(StringType), - }, - { - Identifier: "provider", - TypeAnnotation: NewTypeAnnotation(TheAddressType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - &OptionalType{ - Type: MustInstantiate( - &CapabilityType{}, - &GenericType{ - TypeParameter: AuthAccountInboxTypeClaimFunctionTypeParameterT, - }, - ), - }, - ), -} - -const AuthAccountInboxTypeClaimFunctionDocString = ` -Claims a Capability previously published by the specified provider. - -Returns ` + "`nil`" + ` if no Capability is published under the given name, -or if this account is not its intended recipient. - -Errors if the Capability under that name does not match the provided type. -` - -const AuthAccountInboxTypeName = "Inbox" - -var AuthAccountInboxType = func() *CompositeType { - var t = &CompositeType{ - Identifier: AuthAccountInboxTypeName, - Kind: common.CompositeKindStructure, - importable: false, - hasComputedMembers: true, - } - - return t -}() - -func init() { - var members = []*Member{ - NewUnmeteredFunctionMember( - AuthAccountInboxType, - ast.AccessAll, - AuthAccountInboxTypePublishFunctionName, - AuthAccountInboxTypePublishFunctionType, - AuthAccountInboxTypePublishFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountInboxType, - ast.AccessAll, - AuthAccountInboxTypeUnpublishFunctionName, - AuthAccountInboxTypeUnpublishFunctionType, - AuthAccountInboxTypeUnpublishFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountInboxType, - ast.AccessAll, - AuthAccountInboxTypeClaimFunctionName, - AuthAccountInboxTypeClaimFunctionType, - AuthAccountInboxTypeClaimFunctionDocString, - ), - } - - AuthAccountInboxType.Members = MembersAsMap(members) - AuthAccountInboxType.Fields = MembersFieldNames(members) -} - -const AuthAccountCapabilitiesTypeStorageFieldName = "storage" - -var AuthAccountCapabilitiesTypeStorageFieldType = AuthAccountStorageCapabilitiesType - -const AuthAccountCapabilitiesTypeStorageFieldDocString = ` -The storage capabilities of the account. -` - -const AuthAccountCapabilitiesTypeAccountFieldName = "account" - -var AuthAccountCapabilitiesTypeAccountFieldType = AuthAccountAccountCapabilitiesType - -const AuthAccountCapabilitiesTypeAccountFieldDocString = ` -The account capabilities of the account. -` - -const AuthAccountCapabilitiesTypeGetFunctionName = "get" - -var AuthAccountCapabilitiesTypeGetFunctionTypeParameterT = &TypeParameter{ - Name: "T", - TypeBound: &ReferenceType{ - Type: AnyType, - Authorization: UnauthorizedAccess, - }, -} - -var AuthAccountCapabilitiesTypeGetFunctionType = &FunctionType{ - Purity: FunctionPurityView, - TypeParameters: []*TypeParameter{ - AuthAccountCapabilitiesTypeGetFunctionTypeParameterT, - }, - Parameters: []Parameter{ - { - Label: ArgumentLabelNotRequired, - Identifier: "path", - TypeAnnotation: NewTypeAnnotation(PublicPathType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - &OptionalType{ - Type: MustInstantiate( - &CapabilityType{}, - &GenericType{ - TypeParameter: AuthAccountCapabilitiesTypeGetFunctionTypeParameterT, - }, - ), - }, - ), -} - -const AuthAccountCapabilitiesTypeGetFunctionDocString = ` -Returns the capability at the given public path. -Returns nil if the capability does not exist, -or if the given type is not a supertype of the capability's borrow type. -` - -const AuthAccountCapabilitiesTypeBorrowFunctionName = "borrow" - -var AuthAccountCapabilitiesTypeBorrowFunctionTypeParameterT = &TypeParameter{ - Name: "T", - TypeBound: &ReferenceType{ - Type: AnyType, - Authorization: UnauthorizedAccess, - }, -} - -var AuthAccountCapabilitiesTypeBorrowFunctionType = &FunctionType{ - Purity: FunctionPurityView, - TypeParameters: []*TypeParameter{ - AuthAccountCapabilitiesTypeBorrowFunctionTypeParameterT, - }, - Parameters: []Parameter{ - { - Label: ArgumentLabelNotRequired, - Identifier: "path", - TypeAnnotation: NewTypeAnnotation(PublicPathType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - &OptionalType{ - Type: &GenericType{ - TypeParameter: AuthAccountCapabilitiesTypeBorrowFunctionTypeParameterT, - }, - }, - ), -} - -const AuthAccountCapabilitiesTypeBorrowFunctionDocString = ` -Borrows the capability at the given public path. -Returns nil if the capability does not exist, or cannot be borrowed using the given type. -The function is equivalent to ` + "`get(path)?.borrow()`" + `. -` - -const AuthAccountCapabilitiesTypePublishFunctionName = "publish" - -var AuthAccountCapabilitiesTypePublishFunctionType = &FunctionType{ - Parameters: []Parameter{ - { - Label: ArgumentLabelNotRequired, - Identifier: "capability", - TypeAnnotation: NewTypeAnnotation(&CapabilityType{}), - }, - { - Identifier: "at", - TypeAnnotation: NewTypeAnnotation(PublicPathType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - VoidType, - ), -} - -const AuthAccountCapabilitiesTypePublishFunctionDocString = ` -Publish the capability at the given public path. - -If there is already a capability published under the given path, the program aborts. - -The path must be a public path, i.e., only the domain ` + "`public`" + ` is allowed. -` - -const AuthAccountCapabilitiesTypeUnpublishFunctionName = "unpublish" - -var AuthAccountCapabilitiesTypeUnpublishFunctionType = &FunctionType{ - Parameters: []Parameter{ - { - Label: ArgumentLabelNotRequired, - Identifier: "path", - TypeAnnotation: NewTypeAnnotation(PublicPathType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - &OptionalType{ - Type: &CapabilityType{}, - }, - ), -} - -const AuthAccountCapabilitiesTypeUnpublishFunctionDocString = ` -Unpublish the capability published at the given path. - -Returns the capability if one was published at the path. -Returns nil if no capability was published at the path. -` - -const AuthAccountCapabilitiesTypeName = "Capabilities" - -var AuthAccountCapabilitiesType = func() *CompositeType { - var t = &CompositeType{ - Identifier: AuthAccountCapabilitiesTypeName, - Kind: common.CompositeKindStructure, - importable: false, - hasComputedMembers: true, - } - - return t -}() - -func init() { - var members = []*Member{ - NewUnmeteredFieldMember( - AuthAccountCapabilitiesType, - ast.AccessAll, - ast.VariableKindConstant, - AuthAccountCapabilitiesTypeStorageFieldName, - AuthAccountCapabilitiesTypeStorageFieldType, - AuthAccountCapabilitiesTypeStorageFieldDocString, - ), - NewUnmeteredFieldMember( - AuthAccountCapabilitiesType, - ast.AccessAll, - ast.VariableKindConstant, - AuthAccountCapabilitiesTypeAccountFieldName, - AuthAccountCapabilitiesTypeAccountFieldType, - AuthAccountCapabilitiesTypeAccountFieldDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountCapabilitiesType, - ast.AccessAll, - AuthAccountCapabilitiesTypeGetFunctionName, - AuthAccountCapabilitiesTypeGetFunctionType, - AuthAccountCapabilitiesTypeGetFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountCapabilitiesType, - ast.AccessAll, - AuthAccountCapabilitiesTypeBorrowFunctionName, - AuthAccountCapabilitiesTypeBorrowFunctionType, - AuthAccountCapabilitiesTypeBorrowFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountCapabilitiesType, - ast.AccessAll, - AuthAccountCapabilitiesTypePublishFunctionName, - AuthAccountCapabilitiesTypePublishFunctionType, - AuthAccountCapabilitiesTypePublishFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountCapabilitiesType, - ast.AccessAll, - AuthAccountCapabilitiesTypeUnpublishFunctionName, - AuthAccountCapabilitiesTypeUnpublishFunctionType, - AuthAccountCapabilitiesTypeUnpublishFunctionDocString, - ), - } - - AuthAccountCapabilitiesType.Members = MembersAsMap(members) - AuthAccountCapabilitiesType.Fields = MembersFieldNames(members) -} - -const AuthAccountStorageCapabilitiesTypeGetControllerFunctionName = "getController" - -var AuthAccountStorageCapabilitiesTypeGetControllerFunctionType = &FunctionType{ - Purity: FunctionPurityView, - Parameters: []Parameter{ - { - Identifier: "byCapabilityID", - TypeAnnotation: NewTypeAnnotation(UInt64Type), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - &OptionalType{ - Type: &ReferenceType{ - Type: StorageCapabilityControllerType, - Authorization: UnauthorizedAccess, - }, - }, - ), -} - -const AuthAccountStorageCapabilitiesTypeGetControllerFunctionDocString = ` -Get the storage capability controller for the capability with the specified ID. - -Returns nil if the ID does not reference an existing storage capability. -` - -const AuthAccountStorageCapabilitiesTypeGetControllersFunctionName = "getControllers" - -var AuthAccountStorageCapabilitiesTypeGetControllersFunctionType = &FunctionType{ - Purity: FunctionPurityView, - Parameters: []Parameter{ - { - Identifier: "forPath", - TypeAnnotation: NewTypeAnnotation(StoragePathType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - &VariableSizedType{ - Type: &ReferenceType{ - Type: StorageCapabilityControllerType, - Authorization: UnauthorizedAccess, - }, - }, - ), -} - -const AuthAccountStorageCapabilitiesTypeGetControllersFunctionDocString = ` -Get all storage capability controllers for capabilities that target this storage path -` - -const AuthAccountStorageCapabilitiesTypeForEachControllerFunctionName = "forEachController" - -var AuthAccountStorageCapabilitiesTypeForEachControllerFunctionType = &FunctionType{ - Parameters: []Parameter{ - { - Identifier: "forPath", - TypeAnnotation: NewTypeAnnotation(StoragePathType), - }, - { - Label: ArgumentLabelNotRequired, - Identifier: "function", - TypeAnnotation: NewTypeAnnotation(&FunctionType{ - Parameters: []Parameter{ - { - TypeAnnotation: NewTypeAnnotation(&ReferenceType{ - Type: StorageCapabilityControllerType, - Authorization: UnauthorizedAccess, - }), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - BoolType, - ), - }), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - VoidType, - ), -} - -const AuthAccountStorageCapabilitiesTypeForEachControllerFunctionDocString = ` -Iterate over all storage capability controllers for capabilities that target this storage path, -passing a reference to each controller to the provided callback function. - -Iteration is stopped early if the callback function returns ` + "`false`" + `. - -If a new storage capability controller is issued for the path, -an existing storage capability controller for the path is deleted, -or a storage capability controller is retargeted from or to the path, -then the callback must stop iteration by returning false. -Otherwise, iteration aborts. -` - -const AuthAccountStorageCapabilitiesTypeIssueFunctionName = "issue" - -var AuthAccountStorageCapabilitiesTypeIssueFunctionTypeParameterT = &TypeParameter{ - Name: "T", - TypeBound: &ReferenceType{ - Type: AnyType, - Authorization: UnauthorizedAccess, - }, -} - -var AuthAccountStorageCapabilitiesTypeIssueFunctionType = &FunctionType{ - TypeParameters: []*TypeParameter{ - AuthAccountStorageCapabilitiesTypeIssueFunctionTypeParameterT, - }, - Parameters: []Parameter{ - { - Label: ArgumentLabelNotRequired, - Identifier: "path", - TypeAnnotation: NewTypeAnnotation(StoragePathType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - MustInstantiate( - &CapabilityType{}, - &GenericType{ - TypeParameter: AuthAccountStorageCapabilitiesTypeIssueFunctionTypeParameterT, - }, - ), - ), -} - -const AuthAccountStorageCapabilitiesTypeIssueFunctionDocString = ` -Issue/create a new storage capability. -` - -const AuthAccountStorageCapabilitiesTypeName = "StorageCapabilities" - -var AuthAccountStorageCapabilitiesType = func() *CompositeType { - var t = &CompositeType{ - Identifier: AuthAccountStorageCapabilitiesTypeName, - Kind: common.CompositeKindStructure, - importable: false, - hasComputedMembers: true, - } - - return t -}() - -func init() { - var members = []*Member{ - NewUnmeteredFunctionMember( - AuthAccountStorageCapabilitiesType, - ast.AccessAll, - AuthAccountStorageCapabilitiesTypeGetControllerFunctionName, - AuthAccountStorageCapabilitiesTypeGetControllerFunctionType, - AuthAccountStorageCapabilitiesTypeGetControllerFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountStorageCapabilitiesType, - ast.AccessAll, - AuthAccountStorageCapabilitiesTypeGetControllersFunctionName, - AuthAccountStorageCapabilitiesTypeGetControllersFunctionType, - AuthAccountStorageCapabilitiesTypeGetControllersFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountStorageCapabilitiesType, - ast.AccessAll, - AuthAccountStorageCapabilitiesTypeForEachControllerFunctionName, - AuthAccountStorageCapabilitiesTypeForEachControllerFunctionType, - AuthAccountStorageCapabilitiesTypeForEachControllerFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountStorageCapabilitiesType, - ast.AccessAll, - AuthAccountStorageCapabilitiesTypeIssueFunctionName, - AuthAccountStorageCapabilitiesTypeIssueFunctionType, - AuthAccountStorageCapabilitiesTypeIssueFunctionDocString, - ), - } - - AuthAccountStorageCapabilitiesType.Members = MembersAsMap(members) - AuthAccountStorageCapabilitiesType.Fields = MembersFieldNames(members) -} - -const AuthAccountAccountCapabilitiesTypeGetControllerFunctionName = "getController" - -var AuthAccountAccountCapabilitiesTypeGetControllerFunctionType = &FunctionType{ - Purity: FunctionPurityView, - Parameters: []Parameter{ - { - Identifier: "byCapabilityID", - TypeAnnotation: NewTypeAnnotation(UInt64Type), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - &OptionalType{ - Type: &ReferenceType{ - Type: AccountCapabilityControllerType, - Authorization: UnauthorizedAccess, - }, - }, - ), -} - -const AuthAccountAccountCapabilitiesTypeGetControllerFunctionDocString = ` -Get capability controller for capability with the specified ID. - -Returns nil if the ID does not reference an existing account capability. -` - -const AuthAccountAccountCapabilitiesTypeGetControllersFunctionName = "getControllers" - -var AuthAccountAccountCapabilitiesTypeGetControllersFunctionType = &FunctionType{ - Purity: FunctionPurityView, - ReturnTypeAnnotation: NewTypeAnnotation( - &VariableSizedType{ - Type: &ReferenceType{ - Type: AccountCapabilityControllerType, - Authorization: UnauthorizedAccess, - }, - }, - ), -} - -const AuthAccountAccountCapabilitiesTypeGetControllersFunctionDocString = ` -Get all capability controllers for all account capabilities. -` - -const AuthAccountAccountCapabilitiesTypeForEachControllerFunctionName = "forEachController" - -var AuthAccountAccountCapabilitiesTypeForEachControllerFunctionType = &FunctionType{ - Parameters: []Parameter{ - { - Label: ArgumentLabelNotRequired, - Identifier: "function", - TypeAnnotation: NewTypeAnnotation(&FunctionType{ - Parameters: []Parameter{ - { - TypeAnnotation: NewTypeAnnotation(&ReferenceType{ - Type: AccountCapabilityControllerType, - Authorization: UnauthorizedAccess, - }), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - BoolType, - ), - }), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - VoidType, - ), -} - -const AuthAccountAccountCapabilitiesTypeForEachControllerFunctionDocString = ` -Iterate over all account capability controllers for all account capabilities, -passing a reference to each controller to the provided callback function. - -Iteration is stopped early if the callback function returns ` + "`false`" + `. - -If a new account capability controller is issued for the account, -or an existing account capability controller for the account is deleted, -then the callback must stop iteration by returning false. -Otherwise, iteration aborts. -` - -const AuthAccountAccountCapabilitiesTypeIssueFunctionName = "issue" - -var AuthAccountAccountCapabilitiesTypeIssueFunctionTypeParameterT = &TypeParameter{ - Name: "T", - TypeBound: &ReferenceType{ - Type: AuthAccountType, - Authorization: UnauthorizedAccess, - }, -} - -var AuthAccountAccountCapabilitiesTypeIssueFunctionType = &FunctionType{ - TypeParameters: []*TypeParameter{ - AuthAccountAccountCapabilitiesTypeIssueFunctionTypeParameterT, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - MustInstantiate( - &CapabilityType{}, - &GenericType{ - TypeParameter: AuthAccountAccountCapabilitiesTypeIssueFunctionTypeParameterT, - }, - ), - ), -} - -const AuthAccountAccountCapabilitiesTypeIssueFunctionDocString = ` -Issue/create a new account capability. -` - -const AuthAccountAccountCapabilitiesTypeName = "AccountCapabilities" - -var AuthAccountAccountCapabilitiesType = func() *CompositeType { - var t = &CompositeType{ - Identifier: AuthAccountAccountCapabilitiesTypeName, - Kind: common.CompositeKindStructure, - importable: false, - hasComputedMembers: true, - } - - return t -}() - -func init() { - var members = []*Member{ - NewUnmeteredFunctionMember( - AuthAccountAccountCapabilitiesType, - ast.AccessAll, - AuthAccountAccountCapabilitiesTypeGetControllerFunctionName, - AuthAccountAccountCapabilitiesTypeGetControllerFunctionType, - AuthAccountAccountCapabilitiesTypeGetControllerFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountAccountCapabilitiesType, - ast.AccessAll, - AuthAccountAccountCapabilitiesTypeGetControllersFunctionName, - AuthAccountAccountCapabilitiesTypeGetControllersFunctionType, - AuthAccountAccountCapabilitiesTypeGetControllersFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountAccountCapabilitiesType, - ast.AccessAll, - AuthAccountAccountCapabilitiesTypeForEachControllerFunctionName, - AuthAccountAccountCapabilitiesTypeForEachControllerFunctionType, - AuthAccountAccountCapabilitiesTypeForEachControllerFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountAccountCapabilitiesType, - ast.AccessAll, - AuthAccountAccountCapabilitiesTypeIssueFunctionName, - AuthAccountAccountCapabilitiesTypeIssueFunctionType, - AuthAccountAccountCapabilitiesTypeIssueFunctionDocString, - ), - } - - AuthAccountAccountCapabilitiesType.Members = MembersAsMap(members) - AuthAccountAccountCapabilitiesType.Fields = MembersFieldNames(members) -} - -const AuthAccountTypeName = "AuthAccount" - -var AuthAccountType = func() *CompositeType { - var t = &CompositeType{ - Identifier: AuthAccountTypeName, - Kind: common.CompositeKindStructure, - importable: false, - hasComputedMembers: true, - } - - t.SetNestedType(AuthAccountContractsTypeName, AuthAccountContractsType) - t.SetNestedType(AuthAccountKeysTypeName, AuthAccountKeysType) - t.SetNestedType(AuthAccountInboxTypeName, AuthAccountInboxType) - t.SetNestedType(AuthAccountCapabilitiesTypeName, AuthAccountCapabilitiesType) - t.SetNestedType(AuthAccountStorageCapabilitiesTypeName, AuthAccountStorageCapabilitiesType) - t.SetNestedType(AuthAccountAccountCapabilitiesTypeName, AuthAccountAccountCapabilitiesType) - return t -}() - -func init() { - var members = []*Member{ - NewUnmeteredFieldMember( - AuthAccountType, - ast.AccessAll, - ast.VariableKindConstant, - AuthAccountTypeAddressFieldName, - AuthAccountTypeAddressFieldType, - AuthAccountTypeAddressFieldDocString, - ), - NewUnmeteredFieldMember( - AuthAccountType, - ast.AccessAll, - ast.VariableKindConstant, - AuthAccountTypeBalanceFieldName, - AuthAccountTypeBalanceFieldType, - AuthAccountTypeBalanceFieldDocString, - ), - NewUnmeteredFieldMember( - AuthAccountType, - ast.AccessAll, - ast.VariableKindConstant, - AuthAccountTypeAvailableBalanceFieldName, - AuthAccountTypeAvailableBalanceFieldType, - AuthAccountTypeAvailableBalanceFieldDocString, - ), - NewUnmeteredFieldMember( - AuthAccountType, - ast.AccessAll, - ast.VariableKindConstant, - AuthAccountTypeStorageUsedFieldName, - AuthAccountTypeStorageUsedFieldType, - AuthAccountTypeStorageUsedFieldDocString, - ), - NewUnmeteredFieldMember( - AuthAccountType, - ast.AccessAll, - ast.VariableKindConstant, - AuthAccountTypeStorageCapacityFieldName, - AuthAccountTypeStorageCapacityFieldType, - AuthAccountTypeStorageCapacityFieldDocString, - ), - NewUnmeteredFieldMember( - AuthAccountType, - ast.AccessAll, - ast.VariableKindConstant, - AuthAccountTypeContractsFieldName, - AuthAccountTypeContractsFieldType, - AuthAccountTypeContractsFieldDocString, - ), - NewUnmeteredFieldMember( - AuthAccountType, - ast.AccessAll, - ast.VariableKindConstant, - AuthAccountTypeKeysFieldName, - AuthAccountTypeKeysFieldType, - AuthAccountTypeKeysFieldDocString, - ), - NewUnmeteredFieldMember( - AuthAccountType, - ast.AccessAll, - ast.VariableKindConstant, - AuthAccountTypeInboxFieldName, - AuthAccountTypeInboxFieldType, - AuthAccountTypeInboxFieldDocString, - ), - NewUnmeteredFieldMember( - AuthAccountType, - ast.AccessAll, - ast.VariableKindConstant, - AuthAccountTypeCapabilitiesFieldName, - AuthAccountTypeCapabilitiesFieldType, - AuthAccountTypeCapabilitiesFieldDocString, - ), - NewUnmeteredFieldMember( - AuthAccountType, - ast.AccessAll, - ast.VariableKindConstant, - AuthAccountTypePublicPathsFieldName, - AuthAccountTypePublicPathsFieldType, - AuthAccountTypePublicPathsFieldDocString, - ), - NewUnmeteredFieldMember( - AuthAccountType, - ast.AccessAll, - ast.VariableKindConstant, - AuthAccountTypePrivatePathsFieldName, - AuthAccountTypePrivatePathsFieldType, - AuthAccountTypePrivatePathsFieldDocString, - ), - NewUnmeteredFieldMember( - AuthAccountType, - ast.AccessAll, - ast.VariableKindConstant, - AuthAccountTypeStoragePathsFieldName, - AuthAccountTypeStoragePathsFieldType, - AuthAccountTypeStoragePathsFieldDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountType, - ast.AccessAll, - AuthAccountTypeSaveFunctionName, - AuthAccountTypeSaveFunctionType, - AuthAccountTypeSaveFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountType, - ast.AccessAll, - AuthAccountTypeTypeFunctionName, - AuthAccountTypeTypeFunctionType, - AuthAccountTypeTypeFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountType, - ast.AccessAll, - AuthAccountTypeLoadFunctionName, - AuthAccountTypeLoadFunctionType, - AuthAccountTypeLoadFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountType, - ast.AccessAll, - AuthAccountTypeCopyFunctionName, - AuthAccountTypeCopyFunctionType, - AuthAccountTypeCopyFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountType, - ast.AccessAll, - AuthAccountTypeBorrowFunctionName, - AuthAccountTypeBorrowFunctionType, - AuthAccountTypeBorrowFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountType, - ast.AccessAll, - AuthAccountTypeCheckFunctionName, - AuthAccountTypeCheckFunctionType, - AuthAccountTypeCheckFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountType, - ast.AccessAll, - AuthAccountTypeForEachPublicFunctionName, - AuthAccountTypeForEachPublicFunctionType, - AuthAccountTypeForEachPublicFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountType, - ast.AccessAll, - AuthAccountTypeForEachPrivateFunctionName, - AuthAccountTypeForEachPrivateFunctionType, - AuthAccountTypeForEachPrivateFunctionDocString, - ), - NewUnmeteredFunctionMember( - AuthAccountType, - ast.AccessAll, - AuthAccountTypeForEachStoredFunctionName, - AuthAccountTypeForEachStoredFunctionType, - AuthAccountTypeForEachStoredFunctionDocString, - ), - } - - AuthAccountType.Members = MembersAsMap(members) - AuthAccountType.Fields = MembersFieldNames(members) -} diff --git a/runtime/sema/authaccount.go b/runtime/sema/authaccount.go deleted file mode 100644 index 942257ed46..0000000000 --- a/runtime/sema/authaccount.go +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Cadence - The resource-oriented smart contract programming language - * - * Copyright Dapper Labs, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package sema - -//go:generate go run ./gen authaccount.cdc authaccount.gen.go - -var AuthAccountTypeAnnotation = NewTypeAnnotation(AuthAccountType) - -func init() { - AuthAccountContractsTypeAddFunctionType.Arity = &Arity{Min: 2} -} diff --git a/runtime/sema/block.gen.go b/runtime/sema/block.gen.go index 3bdd5a712e..058282a4ff 100644 --- a/runtime/sema/block.gen.go +++ b/runtime/sema/block.gen.go @@ -84,7 +84,7 @@ func init() { return MembersAsResolvers([]*Member{ NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, BlockTypeHeightFieldName, BlockTypeHeightFieldType, @@ -92,7 +92,7 @@ func init() { ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, BlockTypeViewFieldName, BlockTypeViewFieldType, @@ -100,7 +100,7 @@ func init() { ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, BlockTypeTimestampFieldName, BlockTypeTimestampFieldType, @@ -108,7 +108,7 @@ func init() { ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, BlockTypeIdFieldName, BlockTypeIdFieldType, diff --git a/runtime/sema/character.gen.go b/runtime/sema/character.gen.go index 72a4e70217..36d89e50c4 100644 --- a/runtime/sema/character.gen.go +++ b/runtime/sema/character.gen.go @@ -65,7 +65,7 @@ func init() { return MembersAsResolvers([]*Member{ NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, CharacterTypeUtf8FieldName, CharacterTypeUtf8FieldType, @@ -73,7 +73,7 @@ func init() { ), NewUnmeteredFunctionMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), CharacterTypeToStringFunctionName, CharacterTypeToStringFunctionType, CharacterTypeToStringFunctionDocString, diff --git a/runtime/sema/check_assignment.go b/runtime/sema/check_assignment.go index daaa23613d..a45c0f2a36 100644 --- a/runtime/sema/check_assignment.go +++ b/runtime/sema/check_assignment.go @@ -313,12 +313,12 @@ func (checker *Checker) visitIdentifierExpressionAssignment( } var mutableEntitledAccess = NewEntitlementSetAccess( - []*EntitlementType{MutateEntitlement}, + []*EntitlementType{MutateType}, Disjunction, ) -var insertableAndRemovableEntitledAccess = NewEntitlementSetAccess( - []*EntitlementType{InsertEntitlement, RemoveEntitlement}, +var insertAndRemoveEntitledAccess = NewEntitlementSetAccess( + []*EntitlementType{InsertType, RemoveType}, Conjunction, ) @@ -333,9 +333,9 @@ func (checker *Checker) visitIndexExpressionAssignment( if isReference && !mutableEntitledAccess.PermitsAccess(indexedRefType.Authorization) && - !insertableAndRemovableEntitledAccess.PermitsAccess(indexedRefType.Authorization) { + !insertAndRemoveEntitledAccess.PermitsAccess(indexedRefType.Authorization) { checker.report(&UnauthorizedReferenceAssignmentError{ - RequiredAccess: [2]Access{mutableEntitledAccess, insertableAndRemovableEntitledAccess}, + RequiredAccess: [2]Access{mutableEntitledAccess, insertAndRemoveEntitledAccess}, FoundAccess: indexedRefType.Authorization, Range: ast.NewRangeFromPositioned(checker.memoryGauge, indexExpression), }) diff --git a/runtime/sema/check_composite_declaration.go b/runtime/sema/check_composite_declaration.go index 98d3886cb3..731e6b6c99 100644 --- a/runtime/sema/check_composite_declaration.go +++ b/runtime/sema/check_composite_declaration.go @@ -95,10 +95,10 @@ func (checker *Checker) checkAttachmentMembersAccess(attachmentType *CompositeTy // while the definition of `qux` is not. var attachmentAccess Access = UnauthorizedAccess if attachmentType.AttachmentEntitlementAccess != nil { - attachmentAccess = *attachmentType.AttachmentEntitlementAccess + attachmentAccess = attachmentType.AttachmentEntitlementAccess } - if attachmentAccess, ok := attachmentAccess.(EntitlementMapAccess); ok { + if attachmentAccess, ok := attachmentAccess.(*EntitlementMapAccess); ok { codomain := attachmentAccess.Codomain() attachmentType.Members.Foreach(func(_ string, member *Member) { if memberAccess, ok := member.Access.(EntitlementSetAccess); ok { @@ -624,8 +624,8 @@ func (checker *Checker) declareAttachmentType(declaration *ast.AttachmentDeclara composite.baseType = checker.convertNominalType(declaration.BaseType) attachmentAccess := checker.accessFromAstAccess(declaration.Access) - if attachmentAccess, ok := attachmentAccess.(EntitlementMapAccess); ok { - composite.AttachmentEntitlementAccess = &attachmentAccess + if attachmentAccess, ok := attachmentAccess.(*EntitlementMapAccess); ok { + composite.AttachmentEntitlementAccess = attachmentAccess } // add all the required entitlements to a set for this attachment @@ -1740,7 +1740,7 @@ func (checker *Checker) defaultMembersAndOrigins( fieldAccess := checker.accessFromAstAccess(field.Access) - if entitlementMapAccess, ok := fieldAccess.(EntitlementMapAccess); ok { + if entitlementMapAccess, ok := fieldAccess.(*EntitlementMapAccess); ok { checker.entitlementMappingInScope = entitlementMapAccess.Type } fieldTypeAnnotation := checker.ConvertTypeAnnotation(field.TypeAnnotation) diff --git a/runtime/sema/check_event_declaration.go b/runtime/sema/check_event_declaration.go index e453f06907..5250b94bf3 100644 --- a/runtime/sema/check_event_declaration.go +++ b/runtime/sema/check_event_declaration.go @@ -61,6 +61,9 @@ func IsValidEventParameterType(t Type, results map[*Member]bool) bool { case *AddressType: return true + case *ReferenceType: + return IsValidEventParameterType(t.Type, results) + case *OptionalType: return IsValidEventParameterType(t.Type, results) diff --git a/runtime/sema/check_function.go b/runtime/sema/check_function.go index 456f02cc95..26c4ec7228 100644 --- a/runtime/sema/check_function.go +++ b/runtime/sema/check_function.go @@ -187,7 +187,7 @@ func (checker *Checker) checkFunction( functionActivation.InitializationInfo = initializationInfo if functionBlock != nil { - if mappedAccess, isMappedAccess := access.(EntitlementMapAccess); isMappedAccess { + if mappedAccess, isMappedAccess := access.(*EntitlementMapAccess); isMappedAccess { checker.entitlementMappingInScope = mappedAccess.Type } diff --git a/runtime/sema/check_member_expression.go b/runtime/sema/check_member_expression.go index 379b06cab3..2f27adf9a9 100644 --- a/runtime/sema/check_member_expression.go +++ b/runtime/sema/check_member_expression.go @@ -384,7 +384,7 @@ func (checker *Checker) isReadableMember(accessedType Type, member *Member, resu if checker.Config.AccessCheckMode.IsReadableAccess(member.Access) || checker.containerTypes[member.ContainerType] { - if mappedAccess, isMappedAccess := member.Access.(EntitlementMapAccess); isMappedAccess { + if mappedAccess, isMappedAccess := member.Access.(*EntitlementMapAccess); isMappedAccess { return checker.mapAccess(mappedAccess, accessedType, resultingType, accessRange) } @@ -428,7 +428,7 @@ func (checker *Checker) isReadableMember(accessedType Type, member *Member, resu // allowed as an owned value is considered fully authorized return true, member.Access } - case EntitlementMapAccess: + case *EntitlementMapAccess: return checker.mapAccess(access, accessedType, resultingType, accessRange) } @@ -436,7 +436,7 @@ func (checker *Checker) isReadableMember(accessedType Type, member *Member, resu } func (checker *Checker) mapAccess( - mappedAccess EntitlementMapAccess, + mappedAccess *EntitlementMapAccess, accessedType Type, resultingType Type, accessRange func() ast.Range, @@ -459,7 +459,7 @@ func (checker *Checker) mapAccess( return checker.mapAccess(mappedAccess, ty.Type, resultingType, accessRange) default: - if mappedAccess.Type == IdentityMappingType { + if mappedAccess.Type == IdentityType { access := AllSupportedEntitlements(resultingType) if access != nil { return true, access diff --git a/runtime/sema/check_transaction_declaration.go b/runtime/sema/check_transaction_declaration.go index ee3331550f..f6be79dabe 100644 --- a/runtime/sema/check_transaction_declaration.go +++ b/runtime/sema/check_transaction_declaration.go @@ -209,7 +209,7 @@ func (checker *Checker) checkTransactionPrepareFunctionParameters( parameterType := parameters[i].TypeAnnotation.Type if !parameterType.IsInvalidType() && - !IsSameTypeKind(parameterType, AuthAccountType) { + !IsSubType(parameterType, AccountReferenceType) { checker.report( &InvalidTransactionPrepareParameterTypeError{ diff --git a/runtime/sema/checker.go b/runtime/sema/checker.go index 9814d127b8..3228e003e6 100644 --- a/runtime/sema/checker.go +++ b/runtime/sema/checker.go @@ -1054,7 +1054,7 @@ func (checker *Checker) convertReferenceType(t *ast.ReferenceType) Type { if t.Authorization != nil { access = checker.accessFromAstAccess(ast.EntitlementAccess{EntitlementSet: t.Authorization.EntitlementSet}) switch mapAccess := access.(type) { - case EntitlementMapAccess: + case *EntitlementMapAccess: // mapped auth types are only allowed in the annotations of composite fields and accessor functions if checker.entitlementMappingInScope == nil || !checker.entitlementMappingInScope.Equal(mapAccess.Type) { checker.report(&InvalidMappedAuthorizationOutsideOfFieldError{ @@ -1289,7 +1289,7 @@ func (checker *Checker) functionType( // to allow entitlement mapping types to be used in the return annotation only of // a mapped accessor function, we introduce a "variable" into the typing scope while // checking the return - if mapAccess, isMapAccess := access.(EntitlementMapAccess); isMapAccess { + if mapAccess, isMapAccess := access.(*EntitlementMapAccess); isMapAccess { checker.entitlementMappingInScope = mapAccess.Type } convertedReturnTypeAnnotation = @@ -1734,7 +1734,7 @@ func (checker *Checker) checkDeclarationAccessModifier( switch access := access.(type) { case PrimitiveAccess: checker.checkPrimitiveAccess(access, isConstant, declarationKind, startPos) - case EntitlementMapAccess: + case *EntitlementMapAccess: checker.checkEntitlementMapAccess(access, declarationKind, declarationType, containerKind, startPos) case EntitlementSetAccess: checker.checkEntitlementSetAccess(declarationType, containerKind, startPos) @@ -1812,7 +1812,7 @@ func (checker *Checker) checkPrimitiveAccess( } func (checker *Checker) checkEntitlementMapAccess( - access EntitlementMapAccess, + access *EntitlementMapAccess, declarationKind common.DeclarationKind, declarationType Type, containerKind *common.CompositeKind, @@ -1895,7 +1895,7 @@ func (checker *Checker) checkEntitlementSetAccess( // when using entitlement set access, it is not permitted for the value to be declared with a mapped entitlement switch ty := declarationType.(type) { case *ReferenceType: - if _, isMap := ty.Authorization.(EntitlementMapAccess); isMap { + if _, isMap := ty.Authorization.(*EntitlementMapAccess); isMap { checker.report( &InvalidMappedEntitlementMemberError{ Pos: startPos, @@ -1905,7 +1905,7 @@ func (checker *Checker) checkEntitlementSetAccess( case *OptionalType: switch optionalType := ty.Type.(type) { case *ReferenceType: - if _, isMap := optionalType.Authorization.(EntitlementMapAccess); isMap { + if _, isMap := optionalType.Authorization.(*EntitlementMapAccess); isMap { checker.report( &InvalidMappedEntitlementMemberError{ Pos: startPos, @@ -2038,10 +2038,22 @@ func (checker *Checker) withSelfResourceInvalidationAllowed(f func()) { } const ResourceOwnerFieldName = "owner" + +var ResourceOwnerFieldType = &OptionalType{ + Type: AccountReferenceType, +} + const ResourceUUIDFieldName = "uuid" +var ResourceUUIDFieldType = UInt64Type + const ContractAccountFieldName = "account" +var ContractAccountFieldType = &ReferenceType{ + Type: AccountType, + Authorization: FullyEntitledAccountAccess, +} + const contractAccountFieldDocString = ` The account where the contract is deployed in ` @@ -2106,12 +2118,12 @@ func (checker *Checker) predeclaredMembers(containerType Type) []*Member { case common.CompositeKindContract: // All contracts have a predeclared member - // `access(self) let account: AuthAccount`, + // `access(self) let account: auth(Storage, Contracts, Keys, Inbox, Capabilities) &Account`, // which is ignored in serialization addPredeclaredMember( ContractAccountFieldName, - AuthAccountType, + ContractAccountFieldType, common.DeclarationKindField, ast.AccessSelf, true, @@ -2122,14 +2134,12 @@ func (checker *Checker) predeclaredMembers(containerType Type) []*Member { // All resources have two predeclared fields: - // `access(all) let owner: PublicAccount?`, + // `access(all) let owner: &Account?`, // ignored in serialization addPredeclaredMember( ResourceOwnerFieldName, - &OptionalType{ - Type: PublicAccountType, - }, + ResourceOwnerFieldType, common.DeclarationKindField, ast.AccessAll, true, @@ -2141,7 +2151,7 @@ func (checker *Checker) predeclaredMembers(containerType Type) []*Member { addPredeclaredMember( ResourceUUIDFieldName, - UInt64Type, + ResourceUUIDFieldType, common.DeclarationKindField, ast.AccessAll, false, diff --git a/runtime/sema/checker_test.go b/runtime/sema/checker_test.go index aa1d5289e0..5c88403d65 100644 --- a/runtime/sema/checker_test.go +++ b/runtime/sema/checker_test.go @@ -309,7 +309,7 @@ func TestReferenceSubtyping(t *testing.T) { Identifier: "Z", } - mapAccess := EntitlementMapAccess{ + mapAccess := &EntitlementMapAccess{ Type: &EntitlementMapType{ Location: testLocation, Identifier: "M", @@ -329,7 +329,7 @@ func TestReferenceSubtyping(t *testing.T) { Identifier: "X", } - containedMapAccess := EntitlementMapAccess{ + containedMapAccess := &EntitlementMapAccess{ Type: &EntitlementMapType{ Location: testLocation, containerType: &InterfaceType{ diff --git a/runtime/sema/deployedcontract.gen.go b/runtime/sema/deployedcontract.gen.go index 680a1c2668..1e502abccd 100644 --- a/runtime/sema/deployedcontract.gen.go +++ b/runtime/sema/deployedcontract.gen.go @@ -93,7 +93,7 @@ func init() { return MembersAsResolvers([]*Member{ NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, DeployedContractTypeAddressFieldName, DeployedContractTypeAddressFieldType, @@ -101,7 +101,7 @@ func init() { ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, DeployedContractTypeNameFieldName, DeployedContractTypeNameFieldType, @@ -109,7 +109,7 @@ func init() { ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, DeployedContractTypeCodeFieldName, DeployedContractTypeCodeFieldType, @@ -117,7 +117,7 @@ func init() { ), NewUnmeteredFunctionMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), DeployedContractTypePublicTypesFunctionName, DeployedContractTypePublicTypesFunctionType, DeployedContractTypePublicTypesFunctionDocString, diff --git a/runtime/sema/entitlements.gen.go b/runtime/sema/entitlements.gen.go index 55e7316f51..559ebf6937 100644 --- a/runtime/sema/entitlements.gen.go +++ b/runtime/sema/entitlements.gen.go @@ -19,23 +19,23 @@ package sema -var MutateEntitlement = &EntitlementType{ +var MutateType = &EntitlementType{ Identifier: "Mutate", } -var InsertEntitlement = &EntitlementType{ +var InsertType = &EntitlementType{ Identifier: "Insert", } -var RemoveEntitlement = &EntitlementType{ +var RemoveType = &EntitlementType{ Identifier: "Remove", } func init() { - BuiltinEntitlements[MutateEntitlement.Identifier] = MutateEntitlement - addToBaseActivation(MutateEntitlement) - BuiltinEntitlements[InsertEntitlement.Identifier] = InsertEntitlement - addToBaseActivation(InsertEntitlement) - BuiltinEntitlements[RemoveEntitlement.Identifier] = RemoveEntitlement - addToBaseActivation(RemoveEntitlement) + BuiltinEntitlements[MutateType.Identifier] = MutateType + addToBaseActivation(MutateType) + BuiltinEntitlements[InsertType.Identifier] = InsertType + addToBaseActivation(InsertType) + BuiltinEntitlements[RemoveType.Identifier] = RemoveType + addToBaseActivation(RemoveType) } diff --git a/runtime/sema/errors.go b/runtime/sema/errors.go index 64e465de86..62fed90011 100644 --- a/runtime/sema/errors.go +++ b/runtime/sema/errors.go @@ -3020,7 +3020,7 @@ func (e *InvalidAccessError) Error() string { } return fmt.Sprintf( - "cannot access `%s`: `%s` requires `%s` authorization%s", + "cannot access `%s`: %s requires `%s` authorization%s", e.Name, e.DeclarationKind.Name(), e.RestrictingAccess.Description(), @@ -3113,7 +3113,7 @@ func (*InvalidAssignmentAccessError) IsUserError() {} func (e *InvalidAssignmentAccessError) Error() string { return fmt.Sprintf( - "cannot assign to `%s`: %s has %s access", + "cannot assign to `%s`: %s has `%s` access", e.Name, e.DeclarationKind.Name(), e.RestrictingAccess.Description(), @@ -3403,8 +3403,8 @@ func (*InvalidTransactionPrepareParameterTypeError) IsUserError() {} func (e *InvalidTransactionPrepareParameterTypeError) Error() string { return fmt.Sprintf( - "prepare parameter must be of type `%s`, not `%s`", - AuthAccountType, + "prepare parameter must be subtype of `%s`, not `%s`", + AccountReferenceType, e.Type.QualifiedString(), ) } @@ -4708,7 +4708,7 @@ func (e *InvalidAttachmentEntitlementError) SecondaryError() string { switch access := e.AttachmentAccessModifier.(type) { case PrimitiveAccess: return "attachments declared with `access(all)` access do not support entitlements on their members" - case EntitlementMapAccess: + case *EntitlementMapAccess: return fmt.Sprintf("`%s` must appear in the output of the entitlement mapping `%s`", e.InvalidEntitlement.QualifiedIdentifier(), access.Type.QualifiedIdentifier()) diff --git a/runtime/sema/gen/main.go b/runtime/sema/gen/main.go index 31da9da27b..e2c223ce4d 100644 --- a/runtime/sema/gen/main.go +++ b/runtime/sema/gen/main.go @@ -34,6 +34,7 @@ import ( "github.com/onflow/cadence/runtime/ast" "github.com/onflow/cadence/runtime/common" + "github.com/onflow/cadence/runtime/errors" "github.com/onflow/cadence/runtime/parser" "github.com/onflow/cadence/runtime/pretty" ) @@ -575,7 +576,7 @@ func (*generator) VisitTransactionDeclaration(_ *ast.TransactionDeclaration) str func (g *generator) VisitEntitlementDeclaration(decl *ast.EntitlementDeclaration) (_ struct{}) { entitlementName := decl.Identifier.Identifier - typeVarName := entitlementVarName(entitlementName) + typeVarName := typeVarName(entitlementName) typeVarDecl := entitlementTypeLiteral(entitlementName) g.addDecls( @@ -588,9 +589,20 @@ func (g *generator) VisitEntitlementDeclaration(decl *ast.EntitlementDeclaration return } -func (*generator) VisitEntitlementMappingDeclaration(_ *ast.EntitlementMappingDeclaration) struct{} { - // TODO - panic("entitlement declarations are not supported") +func (g *generator) VisitEntitlementMappingDeclaration(decl *ast.EntitlementMappingDeclaration) (_ struct{}) { + + entitlementMappingName := decl.Identifier.Identifier + typeVarName := typeVarName(entitlementMappingName) + typeVarDecl := entitlementMapTypeLiteral(entitlementMappingName, decl.Elements) + + g.addDecls( + goVarDecl( + typeVarName, + typeVarDecl, + ), + ) + + return } func (g *generator) VisitFieldDeclaration(decl *ast.FieldDeclaration) (_ struct{}) { @@ -653,9 +665,15 @@ func typeExpr(t ast.Type, typeParams map[string]string) dst.Expr { }, } default: + var fullIdentifier strings.Builder + fullIdentifier.WriteString(escapeTypeName(identifier)) + for _, nestedIdentifier := range t.NestedIdentifiers { - identifier += nestedIdentifier.Identifier + fullIdentifier.WriteByte(typeNameSeparator) + fullIdentifier.WriteString(escapeTypeName(nestedIdentifier.Identifier)) } + + identifier = fullIdentifier.String() } return typeVarIdent(identifier) @@ -978,12 +996,23 @@ func (*generator) VisitImportDeclaration(_ *ast.ImportDeclaration) struct{} { panic("import declarations are not supported") } +const typeNameSeparator = '_' + func (g *generator) newFullTypeName(typeName string) string { if len(g.typeStack) == 0 { return typeName } parentFullTypeName := g.typeStack[len(g.typeStack)-1].fullTypeName - return parentFullTypeName + typeName + return fmt.Sprintf( + "%s%c%s", + escapeTypeName(parentFullTypeName), + typeNameSeparator, + escapeTypeName(typeName), + ) +} + +func escapeTypeName(typeName string) string { + return strings.ReplaceAll(typeName, string(typeNameSeparator), "__") } func (g *generator) currentTypeID() string { @@ -1012,66 +1041,123 @@ func (g *generator) currentMemberID(memberName string) string { func (g *generator) generateTypeInit(program *ast.Program) { - // Currently this only generate registering of entitlements. + // Currently this only generate registering of entitlements and entitlement mappings. // It is possible to extend this to register other types as well. // So they are not needed to be manually added to the base activation. + // + // Generates the following: + // + // func init() { + // BuiltinEntitlements[FooEntitlement.Identifier] = FooEntitlement + // addToBaseActivation(FooEntitlement) + // + // ... + // + // BuiltinEntitlements[BarEntitlementMapping.Identifier] = BarEntitlementMapping + // addToBaseActivation(BarEntitlementMapping) + // + // ... + // } + // - /* Generates the following: + var stmts []dst.Stmt + + for _, declaration := range program.EntitlementMappingDeclarations() { + stmts = append(stmts, entitlementMapInitStatements(declaration)...) + } - func init() { - BuiltinEntitlements[Foo.Identifier] = Foo - addToBaseActivation(Foo) - ... - } - */ + for _, declaration := range program.EntitlementDeclarations() { + stmts = append(stmts, entitlementInitStatements(declaration)...) + } - if len(program.EntitlementDeclarations()) == 0 { + if len(stmts) == 0 { return } - stmts := make([]dst.Stmt, 0) + for _, stmt := range stmts { + stmt.Decorations().Before = dst.NewLine + stmt.Decorations().After = dst.NewLine + } - for _, declaration := range program.EntitlementDeclarations() { - const entitlementsName = "BuiltinEntitlements" - varName := entitlementVarName(declaration.Identifier.Identifier) - - mapUpdateStmt := &dst.AssignStmt{ - Lhs: []dst.Expr{ - &dst.IndexExpr{ - X: dst.NewIdent(entitlementsName), - Index: &dst.SelectorExpr{ - X: dst.NewIdent(varName), - Sel: dst.NewIdent("Identifier"), - }, + initDecl := &dst.FuncDecl{ + Name: dst.NewIdent("init"), + Type: &dst.FuncType{}, + Body: &dst.BlockStmt{ + List: stmts, + }, + } + + g.addDecls(initDecl) +} + +func entitlementMapInitStatements(declaration *ast.EntitlementMappingDeclaration) []dst.Stmt { + const mapName = "BuiltinEntitlementMappings" + varName := typeVarName(declaration.Identifier.Identifier) + + mapUpdateStmt := &dst.AssignStmt{ + Lhs: []dst.Expr{ + &dst.IndexExpr{ + X: dst.NewIdent(mapName), + Index: &dst.SelectorExpr{ + X: dst.NewIdent(varName), + Sel: dst.NewIdent("Identifier"), }, }, - Tok: token.ASSIGN, - Rhs: []dst.Expr{ + }, + Tok: token.ASSIGN, + Rhs: []dst.Expr{ + dst.NewIdent(varName), + }, + } + + typeRegisterStmt := &dst.ExprStmt{ + X: &dst.CallExpr{ + Fun: dst.NewIdent("addToBaseActivation"), + Args: []dst.Expr{ dst.NewIdent(varName), }, - } + }, + } - typeRegisterStmt := &dst.ExprStmt{ - X: &dst.CallExpr{ - Fun: dst.NewIdent("addToBaseActivation"), - Args: []dst.Expr{ - dst.NewIdent(varName), + return []dst.Stmt{ + mapUpdateStmt, + typeRegisterStmt, + } +} + +func entitlementInitStatements(declaration *ast.EntitlementDeclaration) []dst.Stmt { + const mapName = "BuiltinEntitlements" + varName := typeVarName(declaration.Identifier.Identifier) + + mapUpdateStmt := &dst.AssignStmt{ + Lhs: []dst.Expr{ + &dst.IndexExpr{ + X: dst.NewIdent(mapName), + Index: &dst.SelectorExpr{ + X: dst.NewIdent(varName), + Sel: dst.NewIdent("Identifier"), }, }, - } - - stmts = append(stmts, mapUpdateStmt, typeRegisterStmt) + }, + Tok: token.ASSIGN, + Rhs: []dst.Expr{ + dst.NewIdent(varName), + }, } - initDecl := &dst.FuncDecl{ - Name: dst.NewIdent("init"), - Type: &dst.FuncType{}, - Body: &dst.BlockStmt{ - List: stmts, + typeRegisterStmt := &dst.ExprStmt{ + X: &dst.CallExpr{ + Fun: dst.NewIdent("addToBaseActivation"), + Args: []dst.Expr{ + dst.NewIdent(varName), + }, }, } - g.addDecls(initDecl) + return []dst.Stmt{ + mapUpdateStmt, + typeRegisterStmt, + } } func goField(name string, ty dst.Expr) *dst.Field { @@ -1155,10 +1241,6 @@ func typeVarName(typeName string) string { return fmt.Sprintf("%sType", typeName) } -func entitlementVarName(typeName string) string { - return fmt.Sprintf("%sEntitlement", typeName) -} - func typeVarIdent(typeName string) *dst.Ident { return dst.NewIdent(typeVarName(typeName)) } @@ -1359,10 +1441,62 @@ func simpleType() *dst.StarExpr { return &dst.StarExpr{X: dst.NewIdent("SimpleType")} } -func accessIdent(access ast.Access) *dst.Ident { - return &dst.Ident{ - Name: access.String(), - Path: "github.com/onflow/cadence/runtime/ast", +func accessExpr(access ast.Access) dst.Expr { + switch access := access.(type) { + case ast.PrimitiveAccess: + return &dst.CallExpr{ + Fun: dst.NewIdent("PrimitiveAccess"), + Args: []dst.Expr{ + &dst.Ident{ + Name: access.String(), + Path: "github.com/onflow/cadence/runtime/ast", + }, + }, + } + + case ast.EntitlementAccess: + entitlements := access.EntitlementSet.Entitlements() + + entitlementExprs := make([]dst.Expr, 0, len(entitlements)) + + for _, nominalType := range entitlements { + entitlementExpr := typeExpr(nominalType, nil) + entitlementExprs = append(entitlementExprs, entitlementExpr) + } + + var setKind dst.Expr + + switch access.EntitlementSet.Separator() { + case ast.Conjunction: + setKind = dst.NewIdent("Conjunction") + case ast.Disjunction: + setKind = dst.NewIdent("Disjunction") + default: + panic(errors.NewUnreachableError()) + } + + args := []dst.Expr{ + &dst.CompositeLit{ + Type: &dst.ArrayType{ + Elt: dst.NewIdent("Type"), + }, + Elts: entitlementExprs, + }, + setKind, + } + + for _, arg := range args { + arg.Decorations().Before = dst.NewLine + arg.Decorations().After = dst.NewLine + } + + return &dst.CallExpr{ + Fun: dst.NewIdent("newEntitlementAccess"), + Args: args, + } + + default: + panic(fmt.Errorf("unsupported access: %#+v\n", access)) } } @@ -1395,7 +1529,7 @@ func newDeclarationMember( if fieldDeclaration, ok := declaration.(*ast.FieldDeclaration); ok { args := []dst.Expr{ dst.NewIdent(containerTypeVariableIdentifier), - accessIdent(access), + accessExpr(access), variableKindIdent(fieldDeclaration.VariableKind), dst.NewIdent(memberNameVariableIdentifier), dst.NewIdent(fieldTypeVarName(fullTypeName, declarationName)), @@ -1420,7 +1554,7 @@ func newDeclarationMember( if declarationKind == common.DeclarationKindFunction { args := []dst.Expr{ dst.NewIdent(containerTypeVariableIdentifier), - accessIdent(access), + accessExpr(access), dst.NewIdent(memberNameVariableIdentifier), dst.NewIdent(functionTypeVarName(fullTypeName, declarationName)), dst.NewIdent(functionDocStringVarName(fullTypeName, declarationName)), @@ -1576,15 +1710,66 @@ func entitlementTypeLiteral(name string) dst.Expr { // Identifier: "Foo", //} - elements := []dst.Expr{ - goKeyValue("Identifier", goStringLit(name)), + return &dst.UnaryExpr{ + Op: token.AND, + X: &dst.CompositeLit{ + Type: dst.NewIdent("EntitlementType"), + Elts: []dst.Expr{ + goKeyValue("Identifier", goStringLit(name)), + }, + }, + } +} + +func entitlementMapTypeLiteral(name string, elements []ast.EntitlementMapElement) dst.Expr { + // &sema.EntitlementMapType{ + // Identifier: "Foo", + // Relations: []EntitlementRelation{ + // { + // Input: BarType, + // Output: BazType, + // }, + // } + // } + + relationExprs := make([]dst.Expr, 0, len(elements)) + + for _, element := range elements { + + relation, ok := element.(*ast.EntitlementMapRelation) + if !ok { + panic(fmt.Errorf("non-relation map element is not supported: %s", element)) + } + + relationExpr := &dst.CompositeLit{ + Type: dst.NewIdent("EntitlementRelation"), + Elts: []dst.Expr{ + goKeyValue("Input", typeExpr(relation.Input, nil)), + goKeyValue("Output", typeExpr(relation.Output, nil)), + }, + } + + relationExpr.Decorations().Before = dst.NewLine + relationExpr.Decorations().After = dst.NewLine + + relationExprs = append(relationExprs, relationExpr) + } + + relationsExpr := &dst.CompositeLit{ + Type: &dst.ArrayType{ + Elt: dst.NewIdent("EntitlementRelation"), + }, + Elts: relationExprs, } return &dst.UnaryExpr{ Op: token.AND, X: &dst.CompositeLit{ - Type: dst.NewIdent("EntitlementType"), - Elts: elements, + Type: dst.NewIdent("EntitlementMapType"), + Elts: []dst.Expr{ + goKeyValue("Identifier", goStringLit(name)), + goKeyValue("Relations", relationsExpr), + }, }, } } @@ -1603,7 +1788,7 @@ func parseCadenceFile(path string) *ast.Program { return program } -func gen(inPath string, outFile *os.File, registerTypes bool) { +func gen(inPath string, outFile *os.File) { program := parseCadenceFile(inPath) var gen generator @@ -1612,9 +1797,7 @@ func gen(inPath string, outFile *os.File, registerTypes bool) { _ = ast.AcceptDeclaration[struct{}](declaration, &gen) } - if registerTypes { - gen.generateTypeInit(program) - } + gen.generateTypeInit(program) writeGoFile(inPath, outFile, gen.decls) } @@ -1655,8 +1838,5 @@ func main() { } defer outFile.Close() - // Register generated test types in base activation. - const registerTypes = true - - gen(inPath, outFile, registerTypes) + gen(inPath, outFile) } diff --git a/runtime/sema/gen/main_test.go b/runtime/sema/gen/main_test.go index 32d2b49462..173adc1df1 100644 --- a/runtime/sema/gen/main_test.go +++ b/runtime/sema/gen/main_test.go @@ -50,10 +50,7 @@ func TestFiles(t *testing.T) { require.NoError(t, err) defer outFile.Close() - // Do not register generated test types in base activation. - const registerTypes = false - - gen(inputPath, outFile, registerTypes) + gen(inputPath, outFile) goldenPath := filepath.Join(testDataDirectory, testname+".golden.go") want, err := os.ReadFile(goldenPath) diff --git a/runtime/sema/gen/testdata/docstrings.golden.go b/runtime/sema/gen/testdata/docstrings.golden.go index 846a220c43..68f4102b92 100644 --- a/runtime/sema/gen/testdata/docstrings.golden.go +++ b/runtime/sema/gen/testdata/docstrings.golden.go @@ -122,7 +122,7 @@ func init() { return MembersAsResolvers([]*Member{ NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, DocstringsTypeOwoFieldName, DocstringsTypeOwoFieldType, @@ -130,7 +130,7 @@ func init() { ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, DocstringsTypeUwuFieldName, DocstringsTypeUwuFieldType, @@ -138,14 +138,14 @@ func init() { ), NewUnmeteredFunctionMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), DocstringsTypeNwnFunctionName, DocstringsTypeNwnFunctionType, DocstringsTypeNwnFunctionDocString, ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, DocstringsTypeWithBlanksFieldName, DocstringsTypeWithBlanksFieldType, @@ -153,14 +153,14 @@ func init() { ), NewUnmeteredFunctionMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), DocstringsTypeIsSmolBeanFunctionName, DocstringsTypeIsSmolBeanFunctionType, DocstringsTypeIsSmolBeanFunctionDocString, ), NewUnmeteredFunctionMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), DocstringsTypeRunningOutOfIdeasFunctionName, DocstringsTypeRunningOutOfIdeasFunctionType, DocstringsTypeRunningOutOfIdeasFunctionDocString, diff --git a/runtime/sema/gen/testdata/entitlement.cdc b/runtime/sema/gen/testdata/entitlement.cdc index e31709a3ad..c0b0a55564 100644 --- a/runtime/sema/gen/testdata/entitlement.cdc +++ b/runtime/sema/gen/testdata/entitlement.cdc @@ -1 +1,7 @@ entitlement Foo + +entitlement Bar + +entitlement mapping Baz { + Foo -> Bar +} diff --git a/runtime/sema/gen/testdata/entitlement.golden.go b/runtime/sema/gen/testdata/entitlement.golden.go index 1da6ff2297..ee860913a5 100644 --- a/runtime/sema/gen/testdata/entitlement.golden.go +++ b/runtime/sema/gen/testdata/entitlement.golden.go @@ -19,6 +19,29 @@ package sema -var FooEntitlement = &EntitlementType{ +var FooType = &EntitlementType{ Identifier: "Foo", } + +var BarType = &EntitlementType{ + Identifier: "Bar", +} + +var BazType = &EntitlementMapType{ + Identifier: "Baz", + Relations: []EntitlementRelation{ + EntitlementRelation{ + Input: FooType, + Output: BarType, + }, + }, +} + +func init() { + BuiltinEntitlementMappings[BazType.Identifier] = BazType + addToBaseActivation(BazType) + BuiltinEntitlements[FooType.Identifier] = FooType + addToBaseActivation(FooType) + BuiltinEntitlements[BarType.Identifier] = BarType + addToBaseActivation(BarType) +} diff --git a/runtime/sema/gen/testdata/fields.golden.go b/runtime/sema/gen/testdata/fields.golden.go index 9ecc3a2bc7..9fdabd602e 100644 --- a/runtime/sema/gen/testdata/fields.golden.go +++ b/runtime/sema/gen/testdata/fields.golden.go @@ -148,7 +148,7 @@ func init() { return MembersAsResolvers([]*Member{ NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, TestTypeTestIntFieldName, TestTypeTestIntFieldType, @@ -156,7 +156,7 @@ func init() { ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, TestTypeTestOptIntFieldName, TestTypeTestOptIntFieldType, @@ -164,7 +164,7 @@ func init() { ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, TestTypeTestRefIntFieldName, TestTypeTestRefIntFieldType, @@ -172,7 +172,7 @@ func init() { ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, TestTypeTestVarIntsFieldName, TestTypeTestVarIntsFieldType, @@ -180,7 +180,7 @@ func init() { ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, TestTypeTestConstIntsFieldName, TestTypeTestConstIntsFieldType, @@ -188,7 +188,7 @@ func init() { ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, TestTypeTestParamFieldName, TestTypeTestParamFieldType, @@ -196,7 +196,7 @@ func init() { ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, TestTypeTestAddressFieldName, TestTypeTestAddressFieldType, @@ -204,7 +204,7 @@ func init() { ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, TestTypeTestTypeFieldName, TestTypeTestTypeFieldType, @@ -212,7 +212,7 @@ func init() { ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, TestTypeTestCapFieldName, TestTypeTestCapFieldType, @@ -220,7 +220,7 @@ func init() { ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, TestTypeTestCapIntFieldName, TestTypeTestCapIntFieldType, @@ -228,7 +228,7 @@ func init() { ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, TestTypeTestIntersectionWithoutTypeFieldName, TestTypeTestIntersectionWithoutTypeFieldType, diff --git a/runtime/sema/gen/testdata/functions.golden.go b/runtime/sema/gen/testdata/functions.golden.go index fafd4cfaf4..41226f8238 100644 --- a/runtime/sema/gen/testdata/functions.golden.go +++ b/runtime/sema/gen/testdata/functions.golden.go @@ -194,56 +194,56 @@ func init() { return MembersAsResolvers([]*Member{ NewUnmeteredFunctionMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), TestTypeNothingFunctionName, TestTypeNothingFunctionType, TestTypeNothingFunctionDocString, ), NewUnmeteredFunctionMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), TestTypeParamsFunctionName, TestTypeParamsFunctionType, TestTypeParamsFunctionDocString, ), NewUnmeteredFunctionMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), TestTypeReturnBoolFunctionName, TestTypeReturnBoolFunctionType, TestTypeReturnBoolFunctionDocString, ), NewUnmeteredFunctionMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), TestTypeParamsAndReturnFunctionName, TestTypeParamsAndReturnFunctionType, TestTypeParamsAndReturnFunctionDocString, ), NewUnmeteredFunctionMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), TestTypeTypeParamFunctionName, TestTypeTypeParamFunctionType, TestTypeTypeParamFunctionDocString, ), NewUnmeteredFunctionMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), TestTypeTypeParamWithBoundFunctionName, TestTypeTypeParamWithBoundFunctionType, TestTypeTypeParamWithBoundFunctionDocString, ), NewUnmeteredFunctionMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), TestTypeTypeParamWithBoundAndParamFunctionName, TestTypeTypeParamWithBoundAndParamFunctionType, TestTypeTypeParamWithBoundAndParamFunctionDocString, ), NewUnmeteredFunctionMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), TestTypeViewFunctionFunctionName, TestTypeViewFunctionFunctionType, TestTypeViewFunctionFunctionDocString, diff --git a/runtime/sema/gen/testdata/nested.golden.go b/runtime/sema/gen/testdata/nested.golden.go index 446fe2716a..3f998c940a 100644 --- a/runtime/sema/gen/testdata/nested.golden.go +++ b/runtime/sema/gen/testdata/nested.golden.go @@ -38,29 +38,29 @@ foo const FooTypeBarFieldName = "bar" -var FooTypeBarFieldType = FooBarType +var FooTypeBarFieldType = Foo_BarType const FooTypeBarFieldDocString = ` Bar ` -const FooBarTypeBarFunctionName = "bar" +const Foo_BarTypeBarFunctionName = "bar" -var FooBarTypeBarFunctionType = &FunctionType{ +var Foo_BarTypeBarFunctionType = &FunctionType{ ReturnTypeAnnotation: NewTypeAnnotation( VoidType, ), } -const FooBarTypeBarFunctionDocString = ` +const Foo_BarTypeBarFunctionDocString = ` bar ` -const FooBarTypeName = "Bar" +const Foo_BarTypeName = "Bar" -var FooBarType = func() *CompositeType { +var Foo_BarType = func() *CompositeType { var t = &CompositeType{ - Identifier: FooBarTypeName, + Identifier: Foo_BarTypeName, Kind: common.CompositeKindStructure, importable: false, hasComputedMembers: true, @@ -72,16 +72,16 @@ var FooBarType = func() *CompositeType { func init() { var members = []*Member{ NewUnmeteredFunctionMember( - FooBarType, - ast.AccessAll, - FooBarTypeBarFunctionName, - FooBarTypeBarFunctionType, - FooBarTypeBarFunctionDocString, + Foo_BarType, + PrimitiveAccess(ast.AccessAll), + Foo_BarTypeBarFunctionName, + Foo_BarTypeBarFunctionType, + Foo_BarTypeBarFunctionDocString, ), } - FooBarType.Members = MembersAsMap(members) - FooBarType.Fields = MembersFieldNames(members) + Foo_BarType.Members = MembersAsMap(members) + Foo_BarType.Fields = MembersFieldNames(members) } const FooTypeName = "Foo" @@ -94,7 +94,7 @@ var FooType = func() *CompositeType { hasComputedMembers: true, } - t.SetNestedType(FooBarTypeName, FooBarType) + t.SetNestedType(Foo_BarTypeName, Foo_BarType) return t }() @@ -102,14 +102,14 @@ func init() { var members = []*Member{ NewUnmeteredFunctionMember( FooType, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), FooTypeFooFunctionName, FooTypeFooFunctionType, FooTypeFooFunctionDocString, ), NewUnmeteredFieldMember( FooType, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, FooTypeBarFieldName, FooTypeBarFieldType, diff --git a/runtime/sema/publicaccount.cdc b/runtime/sema/publicaccount.cdc deleted file mode 100644 index 0667c836d8..0000000000 --- a/runtime/sema/publicaccount.cdc +++ /dev/null @@ -1,111 +0,0 @@ - -access(all) -struct PublicAccount { - - /// The address of the account. - access(all) - let address: Address - - /// The FLOW balance of the default vault of this account. - access(all) - let balance: UFix64 - - /// The FLOW balance of the default vault of this account that is available to be moved. - access(all) - let availableBalance: UFix64 - - /// The current amount of storage used by the account in bytes. - access(all) - let storageUsed: UInt64 - - /// The storage capacity of the account in bytes. - access(all) - let storageCapacity: UInt64 - - /// The contracts deployed to the account. - access(all) - let contracts: PublicAccount.Contracts - - /// The keys assigned to the account. - access(all) - let keys: PublicAccount.Keys - - /// The capabilities of the account. - access(all) - let capabilities: PublicAccount.Capabilities - - /// All public paths of this account. - access(all) - let publicPaths: [PublicPath] - - /// Iterate over all the public paths of an account. - /// passing each path and type in turn to the provided callback function. - /// - /// The callback function takes two arguments: - /// 1. The path of the stored object - /// 2. The runtime type of that object - /// - /// Iteration is stopped early if the callback function returns `false`. - /// - /// The order of iteration, as well as the behavior of adding or removing objects from storage during iteration, - /// is undefined. - access(all) - fun forEachPublic(_ function: fun(PublicPath, Type): Bool) - - access(all) - struct Contracts { - - /// The names of all contracts deployed in the account. - access(all) - let names: [String] - - /// Returns the deployed contract for the contract/contract interface with the given name in the account, if any. - /// - /// Returns nil if no contract/contract interface with the given name exists in the account. - access(all) - view fun get(name: String): DeployedContract? - - /// Returns a reference of the given type to the contract with the given name in the account, if any. - /// - /// Returns nil if no contract with the given name exists in the account, - /// or if the contract does not conform to the given type. - access(all) - view fun borrow(name: String): T? - } - - access(all) - struct Keys { - - /// Returns the key at the given index, if it exists, or nil otherwise. - /// - /// Revoked keys are always returned, but they have `isRevoked` field set to true. - access(all) - view fun get(keyIndex: Int): AccountKey? - - /// Iterate over all unrevoked keys in this account, - /// passing each key in turn to the provided function. - /// - /// Iteration is stopped early if the function returns `false`. - /// The order of iteration is undefined. - access(all) - fun forEach(_ function: fun(AccountKey): Bool) - - /// The total number of unrevoked keys in this account. - access(all) - let count: UInt64 - } - - access(all) - struct Capabilities { - /// get returns the storage capability at the given path, if one was stored there. - access(all) - view fun get(_ path: PublicPath): Capability? - - /// borrow gets the storage capability at the given path, and borrows the capability if it exists. - /// - /// Returns nil if the capability does not exist or cannot be borrowed using the given type. - /// The function is equivalent to `get(path)?.borrow()`. - access(all) - view fun borrow(_ path: PublicPath): T? - } -} diff --git a/runtime/sema/publicaccount.gen.go b/runtime/sema/publicaccount.gen.go deleted file mode 100644 index f55c5947cd..0000000000 --- a/runtime/sema/publicaccount.gen.go +++ /dev/null @@ -1,573 +0,0 @@ -// Code generated from publicaccount.cdc. DO NOT EDIT. -/* - * Cadence - The resource-oriented smart contract programming language - * - * Copyright Dapper Labs, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package sema - -import ( - "github.com/onflow/cadence/runtime/ast" - "github.com/onflow/cadence/runtime/common" -) - -const PublicAccountTypeAddressFieldName = "address" - -var PublicAccountTypeAddressFieldType = TheAddressType - -const PublicAccountTypeAddressFieldDocString = ` -The address of the account. -` - -const PublicAccountTypeBalanceFieldName = "balance" - -var PublicAccountTypeBalanceFieldType = UFix64Type - -const PublicAccountTypeBalanceFieldDocString = ` -The FLOW balance of the default vault of this account. -` - -const PublicAccountTypeAvailableBalanceFieldName = "availableBalance" - -var PublicAccountTypeAvailableBalanceFieldType = UFix64Type - -const PublicAccountTypeAvailableBalanceFieldDocString = ` -The FLOW balance of the default vault of this account that is available to be moved. -` - -const PublicAccountTypeStorageUsedFieldName = "storageUsed" - -var PublicAccountTypeStorageUsedFieldType = UInt64Type - -const PublicAccountTypeStorageUsedFieldDocString = ` -The current amount of storage used by the account in bytes. -` - -const PublicAccountTypeStorageCapacityFieldName = "storageCapacity" - -var PublicAccountTypeStorageCapacityFieldType = UInt64Type - -const PublicAccountTypeStorageCapacityFieldDocString = ` -The storage capacity of the account in bytes. -` - -const PublicAccountTypeContractsFieldName = "contracts" - -var PublicAccountTypeContractsFieldType = PublicAccountContractsType - -const PublicAccountTypeContractsFieldDocString = ` -The contracts deployed to the account. -` - -const PublicAccountTypeKeysFieldName = "keys" - -var PublicAccountTypeKeysFieldType = PublicAccountKeysType - -const PublicAccountTypeKeysFieldDocString = ` -The keys assigned to the account. -` - -const PublicAccountTypeCapabilitiesFieldName = "capabilities" - -var PublicAccountTypeCapabilitiesFieldType = PublicAccountCapabilitiesType - -const PublicAccountTypeCapabilitiesFieldDocString = ` -The capabilities of the account. -` - -const PublicAccountTypePublicPathsFieldName = "publicPaths" - -var PublicAccountTypePublicPathsFieldType = &VariableSizedType{ - Type: PublicPathType, -} - -const PublicAccountTypePublicPathsFieldDocString = ` -All public paths of this account. -` - -const PublicAccountTypeForEachPublicFunctionName = "forEachPublic" - -var PublicAccountTypeForEachPublicFunctionType = &FunctionType{ - Parameters: []Parameter{ - { - Label: ArgumentLabelNotRequired, - Identifier: "function", - TypeAnnotation: NewTypeAnnotation(&FunctionType{ - Parameters: []Parameter{ - { - TypeAnnotation: NewTypeAnnotation(PublicPathType), - }, - { - TypeAnnotation: NewTypeAnnotation(MetaType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - BoolType, - ), - }), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - VoidType, - ), -} - -const PublicAccountTypeForEachPublicFunctionDocString = ` -Iterate over all the public paths of an account. -passing each path and type in turn to the provided callback function. - -The callback function takes two arguments: -1. The path of the stored object -2. The runtime type of that object - -Iteration is stopped early if the callback function returns ` + "`false`" + `. - -The order of iteration, as well as the behavior of adding or removing objects from storage during iteration, -is undefined. -` - -const PublicAccountContractsTypeNamesFieldName = "names" - -var PublicAccountContractsTypeNamesFieldType = &VariableSizedType{ - Type: StringType, -} - -const PublicAccountContractsTypeNamesFieldDocString = ` -The names of all contracts deployed in the account. -` - -const PublicAccountContractsTypeGetFunctionName = "get" - -var PublicAccountContractsTypeGetFunctionType = &FunctionType{ - Purity: FunctionPurityView, - Parameters: []Parameter{ - { - Identifier: "name", - TypeAnnotation: NewTypeAnnotation(StringType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - &OptionalType{ - Type: DeployedContractType, - }, - ), -} - -const PublicAccountContractsTypeGetFunctionDocString = ` -Returns the deployed contract for the contract/contract interface with the given name in the account, if any. - -Returns nil if no contract/contract interface with the given name exists in the account. -` - -const PublicAccountContractsTypeBorrowFunctionName = "borrow" - -var PublicAccountContractsTypeBorrowFunctionTypeParameterT = &TypeParameter{ - Name: "T", - TypeBound: &ReferenceType{ - Type: AnyType, - Authorization: UnauthorizedAccess, - }, -} - -var PublicAccountContractsTypeBorrowFunctionType = &FunctionType{ - Purity: FunctionPurityView, - TypeParameters: []*TypeParameter{ - PublicAccountContractsTypeBorrowFunctionTypeParameterT, - }, - Parameters: []Parameter{ - { - Identifier: "name", - TypeAnnotation: NewTypeAnnotation(StringType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - &OptionalType{ - Type: &GenericType{ - TypeParameter: PublicAccountContractsTypeBorrowFunctionTypeParameterT, - }, - }, - ), -} - -const PublicAccountContractsTypeBorrowFunctionDocString = ` -Returns a reference of the given type to the contract with the given name in the account, if any. - -Returns nil if no contract with the given name exists in the account, -or if the contract does not conform to the given type. -` - -const PublicAccountContractsTypeName = "Contracts" - -var PublicAccountContractsType = func() *CompositeType { - var t = &CompositeType{ - Identifier: PublicAccountContractsTypeName, - Kind: common.CompositeKindStructure, - importable: false, - hasComputedMembers: true, - } - - return t -}() - -func init() { - var members = []*Member{ - NewUnmeteredFieldMember( - PublicAccountContractsType, - ast.AccessAll, - ast.VariableKindConstant, - PublicAccountContractsTypeNamesFieldName, - PublicAccountContractsTypeNamesFieldType, - PublicAccountContractsTypeNamesFieldDocString, - ), - NewUnmeteredFunctionMember( - PublicAccountContractsType, - ast.AccessAll, - PublicAccountContractsTypeGetFunctionName, - PublicAccountContractsTypeGetFunctionType, - PublicAccountContractsTypeGetFunctionDocString, - ), - NewUnmeteredFunctionMember( - PublicAccountContractsType, - ast.AccessAll, - PublicAccountContractsTypeBorrowFunctionName, - PublicAccountContractsTypeBorrowFunctionType, - PublicAccountContractsTypeBorrowFunctionDocString, - ), - } - - PublicAccountContractsType.Members = MembersAsMap(members) - PublicAccountContractsType.Fields = MembersFieldNames(members) -} - -const PublicAccountKeysTypeGetFunctionName = "get" - -var PublicAccountKeysTypeGetFunctionType = &FunctionType{ - Purity: FunctionPurityView, - Parameters: []Parameter{ - { - Identifier: "keyIndex", - TypeAnnotation: NewTypeAnnotation(IntType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - &OptionalType{ - Type: AccountKeyType, - }, - ), -} - -const PublicAccountKeysTypeGetFunctionDocString = ` -Returns the key at the given index, if it exists, or nil otherwise. - -Revoked keys are always returned, but they have ` + "`isRevoked`" + ` field set to true. -` - -const PublicAccountKeysTypeForEachFunctionName = "forEach" - -var PublicAccountKeysTypeForEachFunctionType = &FunctionType{ - Parameters: []Parameter{ - { - Label: ArgumentLabelNotRequired, - Identifier: "function", - TypeAnnotation: NewTypeAnnotation(&FunctionType{ - Parameters: []Parameter{ - { - TypeAnnotation: NewTypeAnnotation(AccountKeyType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - BoolType, - ), - }), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - VoidType, - ), -} - -const PublicAccountKeysTypeForEachFunctionDocString = ` -Iterate over all unrevoked keys in this account, -passing each key in turn to the provided function. - -Iteration is stopped early if the function returns ` + "`false`" + `. -The order of iteration is undefined. -` - -const PublicAccountKeysTypeCountFieldName = "count" - -var PublicAccountKeysTypeCountFieldType = UInt64Type - -const PublicAccountKeysTypeCountFieldDocString = ` -The total number of unrevoked keys in this account. -` - -const PublicAccountKeysTypeName = "Keys" - -var PublicAccountKeysType = func() *CompositeType { - var t = &CompositeType{ - Identifier: PublicAccountKeysTypeName, - Kind: common.CompositeKindStructure, - importable: false, - hasComputedMembers: true, - } - - return t -}() - -func init() { - var members = []*Member{ - NewUnmeteredFunctionMember( - PublicAccountKeysType, - ast.AccessAll, - PublicAccountKeysTypeGetFunctionName, - PublicAccountKeysTypeGetFunctionType, - PublicAccountKeysTypeGetFunctionDocString, - ), - NewUnmeteredFunctionMember( - PublicAccountKeysType, - ast.AccessAll, - PublicAccountKeysTypeForEachFunctionName, - PublicAccountKeysTypeForEachFunctionType, - PublicAccountKeysTypeForEachFunctionDocString, - ), - NewUnmeteredFieldMember( - PublicAccountKeysType, - ast.AccessAll, - ast.VariableKindConstant, - PublicAccountKeysTypeCountFieldName, - PublicAccountKeysTypeCountFieldType, - PublicAccountKeysTypeCountFieldDocString, - ), - } - - PublicAccountKeysType.Members = MembersAsMap(members) - PublicAccountKeysType.Fields = MembersFieldNames(members) -} - -const PublicAccountCapabilitiesTypeGetFunctionName = "get" - -var PublicAccountCapabilitiesTypeGetFunctionTypeParameterT = &TypeParameter{ - Name: "T", - TypeBound: &ReferenceType{ - Type: AnyType, - Authorization: UnauthorizedAccess, - }, -} - -var PublicAccountCapabilitiesTypeGetFunctionType = &FunctionType{ - Purity: FunctionPurityView, - TypeParameters: []*TypeParameter{ - PublicAccountCapabilitiesTypeGetFunctionTypeParameterT, - }, - Parameters: []Parameter{ - { - Label: ArgumentLabelNotRequired, - Identifier: "path", - TypeAnnotation: NewTypeAnnotation(PublicPathType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - &OptionalType{ - Type: MustInstantiate( - &CapabilityType{}, - &GenericType{ - TypeParameter: PublicAccountCapabilitiesTypeGetFunctionTypeParameterT, - }, - ), - }, - ), -} - -const PublicAccountCapabilitiesTypeGetFunctionDocString = ` -get returns the storage capability at the given path, if one was stored there. -` - -const PublicAccountCapabilitiesTypeBorrowFunctionName = "borrow" - -var PublicAccountCapabilitiesTypeBorrowFunctionTypeParameterT = &TypeParameter{ - Name: "T", - TypeBound: &ReferenceType{ - Type: AnyType, - Authorization: UnauthorizedAccess, - }, -} - -var PublicAccountCapabilitiesTypeBorrowFunctionType = &FunctionType{ - Purity: FunctionPurityView, - TypeParameters: []*TypeParameter{ - PublicAccountCapabilitiesTypeBorrowFunctionTypeParameterT, - }, - Parameters: []Parameter{ - { - Label: ArgumentLabelNotRequired, - Identifier: "path", - TypeAnnotation: NewTypeAnnotation(PublicPathType), - }, - }, - ReturnTypeAnnotation: NewTypeAnnotation( - &OptionalType{ - Type: &GenericType{ - TypeParameter: PublicAccountCapabilitiesTypeBorrowFunctionTypeParameterT, - }, - }, - ), -} - -const PublicAccountCapabilitiesTypeBorrowFunctionDocString = ` -borrow gets the storage capability at the given path, and borrows the capability if it exists. - -Returns nil if the capability does not exist or cannot be borrowed using the given type. -The function is equivalent to ` + "`get(path)?.borrow()`" + `. -` - -const PublicAccountCapabilitiesTypeName = "Capabilities" - -var PublicAccountCapabilitiesType = func() *CompositeType { - var t = &CompositeType{ - Identifier: PublicAccountCapabilitiesTypeName, - Kind: common.CompositeKindStructure, - importable: false, - hasComputedMembers: true, - } - - return t -}() - -func init() { - var members = []*Member{ - NewUnmeteredFunctionMember( - PublicAccountCapabilitiesType, - ast.AccessAll, - PublicAccountCapabilitiesTypeGetFunctionName, - PublicAccountCapabilitiesTypeGetFunctionType, - PublicAccountCapabilitiesTypeGetFunctionDocString, - ), - NewUnmeteredFunctionMember( - PublicAccountCapabilitiesType, - ast.AccessAll, - PublicAccountCapabilitiesTypeBorrowFunctionName, - PublicAccountCapabilitiesTypeBorrowFunctionType, - PublicAccountCapabilitiesTypeBorrowFunctionDocString, - ), - } - - PublicAccountCapabilitiesType.Members = MembersAsMap(members) - PublicAccountCapabilitiesType.Fields = MembersFieldNames(members) -} - -const PublicAccountTypeName = "PublicAccount" - -var PublicAccountType = func() *CompositeType { - var t = &CompositeType{ - Identifier: PublicAccountTypeName, - Kind: common.CompositeKindStructure, - importable: false, - hasComputedMembers: true, - } - - t.SetNestedType(PublicAccountContractsTypeName, PublicAccountContractsType) - t.SetNestedType(PublicAccountKeysTypeName, PublicAccountKeysType) - t.SetNestedType(PublicAccountCapabilitiesTypeName, PublicAccountCapabilitiesType) - return t -}() - -func init() { - var members = []*Member{ - NewUnmeteredFieldMember( - PublicAccountType, - ast.AccessAll, - ast.VariableKindConstant, - PublicAccountTypeAddressFieldName, - PublicAccountTypeAddressFieldType, - PublicAccountTypeAddressFieldDocString, - ), - NewUnmeteredFieldMember( - PublicAccountType, - ast.AccessAll, - ast.VariableKindConstant, - PublicAccountTypeBalanceFieldName, - PublicAccountTypeBalanceFieldType, - PublicAccountTypeBalanceFieldDocString, - ), - NewUnmeteredFieldMember( - PublicAccountType, - ast.AccessAll, - ast.VariableKindConstant, - PublicAccountTypeAvailableBalanceFieldName, - PublicAccountTypeAvailableBalanceFieldType, - PublicAccountTypeAvailableBalanceFieldDocString, - ), - NewUnmeteredFieldMember( - PublicAccountType, - ast.AccessAll, - ast.VariableKindConstant, - PublicAccountTypeStorageUsedFieldName, - PublicAccountTypeStorageUsedFieldType, - PublicAccountTypeStorageUsedFieldDocString, - ), - NewUnmeteredFieldMember( - PublicAccountType, - ast.AccessAll, - ast.VariableKindConstant, - PublicAccountTypeStorageCapacityFieldName, - PublicAccountTypeStorageCapacityFieldType, - PublicAccountTypeStorageCapacityFieldDocString, - ), - NewUnmeteredFieldMember( - PublicAccountType, - ast.AccessAll, - ast.VariableKindConstant, - PublicAccountTypeContractsFieldName, - PublicAccountTypeContractsFieldType, - PublicAccountTypeContractsFieldDocString, - ), - NewUnmeteredFieldMember( - PublicAccountType, - ast.AccessAll, - ast.VariableKindConstant, - PublicAccountTypeKeysFieldName, - PublicAccountTypeKeysFieldType, - PublicAccountTypeKeysFieldDocString, - ), - NewUnmeteredFieldMember( - PublicAccountType, - ast.AccessAll, - ast.VariableKindConstant, - PublicAccountTypeCapabilitiesFieldName, - PublicAccountTypeCapabilitiesFieldType, - PublicAccountTypeCapabilitiesFieldDocString, - ), - NewUnmeteredFieldMember( - PublicAccountType, - ast.AccessAll, - ast.VariableKindConstant, - PublicAccountTypePublicPathsFieldName, - PublicAccountTypePublicPathsFieldType, - PublicAccountTypePublicPathsFieldDocString, - ), - NewUnmeteredFunctionMember( - PublicAccountType, - ast.AccessAll, - PublicAccountTypeForEachPublicFunctionName, - PublicAccountTypeForEachPublicFunctionType, - PublicAccountTypeForEachPublicFunctionDocString, - ), - } - - PublicAccountType.Members = MembersAsMap(members) - PublicAccountType.Fields = MembersFieldNames(members) -} diff --git a/runtime/sema/publicaccount.go b/runtime/sema/publicaccount.go deleted file mode 100644 index 9e8772a112..0000000000 --- a/runtime/sema/publicaccount.go +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Cadence - The resource-oriented smart contract programming language - * - * Copyright Dapper Labs, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package sema - -//go:generate go run ./gen publicaccount.cdc publicaccount.gen.go - -var PublicAccountTypeAnnotation = NewTypeAnnotation(PublicAccountType) diff --git a/runtime/sema/storage_capability_controller.gen.go b/runtime/sema/storage_capability_controller.gen.go index eb8cf3c123..c74ed0974a 100644 --- a/runtime/sema/storage_capability_controller.gen.go +++ b/runtime/sema/storage_capability_controller.gen.go @@ -149,7 +149,7 @@ func init() { return MembersAsResolvers([]*Member{ NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, StorageCapabilityControllerTypeCapabilityFieldName, StorageCapabilityControllerTypeCapabilityFieldType, @@ -157,7 +157,7 @@ func init() { ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindVariable, StorageCapabilityControllerTypeTagFieldName, StorageCapabilityControllerTypeTagFieldType, @@ -165,14 +165,14 @@ func init() { ), NewUnmeteredFunctionMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), StorageCapabilityControllerTypeSetTagFunctionName, StorageCapabilityControllerTypeSetTagFunctionType, StorageCapabilityControllerTypeSetTagFunctionDocString, ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, StorageCapabilityControllerTypeBorrowTypeFieldName, StorageCapabilityControllerTypeBorrowTypeFieldType, @@ -180,7 +180,7 @@ func init() { ), NewUnmeteredFieldMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), ast.VariableKindConstant, StorageCapabilityControllerTypeCapabilityIDFieldName, StorageCapabilityControllerTypeCapabilityIDFieldType, @@ -188,21 +188,21 @@ func init() { ), NewUnmeteredFunctionMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), StorageCapabilityControllerTypeDeleteFunctionName, StorageCapabilityControllerTypeDeleteFunctionType, StorageCapabilityControllerTypeDeleteFunctionDocString, ), NewUnmeteredFunctionMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), StorageCapabilityControllerTypeTargetFunctionName, StorageCapabilityControllerTypeTargetFunctionType, StorageCapabilityControllerTypeTargetFunctionDocString, ), NewUnmeteredFunctionMember( t, - ast.AccessAll, + PrimitiveAccess(ast.AccessAll), StorageCapabilityControllerTypeRetargetFunctionName, StorageCapabilityControllerTypeRetargetFunctionType, StorageCapabilityControllerTypeRetargetFunctionDocString, diff --git a/runtime/sema/type.go b/runtime/sema/type.go index f5e1b8c418..a507a9d26b 100644 --- a/runtime/sema/type.go +++ b/runtime/sema/type.go @@ -1965,12 +1965,18 @@ Available if the array element type is not resource-kinded. ` var insertableEntitledAccess = NewEntitlementSetAccess( - []*EntitlementType{InsertEntitlement, MutateEntitlement}, + []*EntitlementType{ + InsertType, + MutateType, + }, Disjunction, ) var removableEntitledAccess = NewEntitlementSetAccess( - []*EntitlementType{RemoveEntitlement, MutateEntitlement}, + []*EntitlementType{ + RemoveType, + MutateType, + }, Disjunction, ) @@ -2710,9 +2716,9 @@ func (t *VariableSizedType) SupportedEntitlements() *EntitlementOrderedSet { var arrayDictionaryEntitlements = func() *EntitlementOrderedSet { set := orderedmap.New[EntitlementOrderedSet](3) - set.Set(MutateEntitlement, struct{}{}) - set.Set(InsertEntitlement, struct{}{}) - set.Set(RemoveEntitlement, struct{}{}) + set.Set(MutateType, struct{}{}) + set.Set(InsertType, struct{}{}) + set.Set(RemoveType, struct{}{}) return set }() @@ -3699,8 +3705,7 @@ func init() { CharacterType, StringType, TheAddressType, - AuthAccountType, - PublicAccountType, + AccountType, PathType, StoragePathType, CapabilityPathType, @@ -3722,7 +3727,7 @@ func init() { addToBaseActivation(ty) } - addToBaseActivation(IdentityMappingType) + addToBaseActivation(IdentityType) // The AST contains empty type annotations, resolve them to Void @@ -3749,10 +3754,11 @@ func addToBaseActivation(ty Type) { const IdentityMappingIdentifier string = "Identity" -// The `Identity` mapping is an empty map that includes the Identity map, +// IdentityType represents the `Identity` entitlement mapping type. +// It is an empty map that includes the Identity map, // and is considered already "resolved" with regards to its (vacuously empty) inclusions. // defining it this way eliminates the need to do any special casing for its behavior -var IdentityMappingType = func() *EntitlementMapType { +var IdentityType = func() *EntitlementMapType { m := NewEntitlementMapType(nil, nil, IdentityMappingIdentifier) m.IncludesIdentity = true m.resolveInclusions.Do(func() {}) @@ -3839,7 +3845,7 @@ var AllNumberTypes = common.Concat( var BuiltinEntitlements = map[string]*EntitlementType{} var BuiltinEntitlementMappings = map[string]*EntitlementMapType{ - IdentityMappingType.QualifiedIdentifier(): IdentityMappingType, + IdentityType.QualifiedIdentifier(): IdentityType, } const NumberTypeMinFieldName = "min" @@ -4453,7 +4459,7 @@ func (t *CompositeType) SupportedEntitlements() (set *EntitlementOrderedSet) { set = orderedmap.New[EntitlementOrderedSet](t.Members.Len()) t.Members.Foreach(func(_ string, member *Member) { switch access := member.Access.(type) { - case EntitlementMapAccess: + case *EntitlementMapAccess: set.SetAll(access.Domain().Entitlements) case EntitlementSetAccess: set.SetAll(access.Entitlements) @@ -4820,7 +4826,7 @@ func NewPublicFunctionMember( func NewUnmeteredFunctionMember( containerType Type, - access ast.PrimitiveAccess, + access Access, identifier string, functionType *FunctionType, docString string, @@ -4828,7 +4834,7 @@ func NewUnmeteredFunctionMember( return NewFunctionMember( nil, containerType, - PrimitiveAccess(access), + access, identifier, functionType, docString, @@ -4895,7 +4901,7 @@ func NewPublicConstantFieldMember( func NewUnmeteredFieldMember( containerType Type, - access ast.PrimitiveAccess, + access Access, variableKind ast.VariableKind, identifier string, fieldType Type, @@ -4904,7 +4910,7 @@ func NewUnmeteredFieldMember( return NewFieldMember( nil, containerType, - PrimitiveAccess(access), + access, variableKind, identifier, fieldType, @@ -5151,7 +5157,7 @@ func (t *InterfaceType) SupportedEntitlements() (set *EntitlementOrderedSet) { set = orderedmap.New[EntitlementOrderedSet](t.Members.Len()) t.Members.Foreach(func(_ string, member *Member) { switch access := member.Access.(type) { - case EntitlementMapAccess: + case *EntitlementMapAccess: access.Domain().Entitlements.Foreach(func(entitlement *EntitlementType, _ struct{}) { set.Set(entitlement, struct{}{}) }) @@ -7986,8 +7992,7 @@ func init() { PublicKeyType, HashAlgorithmType, SignatureAlgorithmType, - AuthAccountType, - PublicAccountType, + AccountType, } for len(compositeTypes) > 0 { diff --git a/runtime/sema/type_test.go b/runtime/sema/type_test.go index eaa082063d..bb26ddd5e1 100644 --- a/runtime/sema/type_test.go +++ b/runtime/sema/type_test.go @@ -452,11 +452,11 @@ func TestQualifiedIdentifierCreation(t *testing.T) { assert.Equal(t, "foo", identifier) }) - t.Run("public account container", func(t *testing.T) { + t.Run("account container", func(t *testing.T) { t.Parallel() - identifier := qualifiedIdentifier("foo", PublicAccountType) - assert.Equal(t, "PublicAccount.foo", identifier) + identifier := qualifiedIdentifier("foo", AccountType) + assert.Equal(t, "Account.foo", identifier) }) } @@ -914,7 +914,7 @@ func TestCommonSuperType(t *testing.T) { name: "mixed type structs", types: []Type{ PublicKeyType, - AuthAccountType, + AccountType, }, expectedSuperType: AnyStructType, }, @@ -1875,7 +1875,7 @@ func BenchmarkSuperTypeInference(b *testing.B) { b.Run("composites", func(b *testing.B) { types := []Type{ PublicKeyType, - AuthAccountType, + AccountType, } b.ReportAllocs() diff --git a/runtime/sharedstate_test.go b/runtime/sharedstate_test.go index de0ddaa15f..8b18cd3d3f 100644 --- a/runtime/sharedstate_test.go +++ b/runtime/sharedstate_test.go @@ -144,7 +144,7 @@ func TestRuntimeSharedState(t *testing.T) { import C1 from 0x1 transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { C1.hello() } } diff --git a/runtime/stdlib/account.go b/runtime/stdlib/account.go index 02181b974f..b68c7f0e3d 100644 --- a/runtime/stdlib/account.go +++ b/runtime/stdlib/account.go @@ -32,19 +32,34 @@ import ( "github.com/onflow/cadence/runtime/sema" ) -const authAccountFunctionDocString = ` +const accountFunctionDocString = ` Creates a new account, paid by the given existing account ` -var authAccountFunctionType = sema.NewSimpleFunctionType( +// accountFunctionType is the type +// +// fun Account(payer: auth(BorrowValue | Storage) &Account): +// auth(Storage, Contracts, Keys, Inbox, Capabilities) &Account +var accountFunctionType = sema.NewSimpleFunctionType( sema.FunctionPurityImpure, []sema.Parameter{ { - Identifier: "payer", - TypeAnnotation: sema.AuthAccountTypeAnnotation, + Identifier: "payer", + TypeAnnotation: sema.NewTypeAnnotation( + &sema.ReferenceType{ + Authorization: sema.NewEntitlementSetAccess( + []*sema.EntitlementType{ + sema.BorrowValueType, + sema.StorageType, + }, + sema.Disjunction, + ), + Type: sema.AccountType, + }, + ), }, }, - sema.AuthAccountTypeAnnotation, + sema.FullyEntitledAccountReferenceTypeAnnotation, ) type EventEmitter interface { @@ -61,28 +76,27 @@ type AccountIDGenerator interface { GenerateAccountID(address common.Address) (uint64, error) } -type AuthAccountHandler interface { +type AccountHandler interface { AccountIDGenerator BalanceProvider AvailableBalanceProvider - StorageUsedProvider - StorageCapacityProvider - AuthAccountKeysHandler - AuthAccountContractsHandler + AccountStorageHandler + AccountKeysHandler + AccountContractsHandler } type AccountCreator interface { EventEmitter - AuthAccountHandler + AccountHandler // CreateAccount creates a new account. CreateAccount(payer common.Address) (address common.Address, err error) } -func NewAuthAccountConstructor(creator AccountCreator) StandardLibraryValue { +func NewAccountConstructor(creator AccountCreator) StandardLibraryValue { return NewStandardLibraryFunction( - "AuthAccount", - authAccountFunctionType, - authAccountFunctionDocString, + "Account", + accountFunctionType, + accountFunctionDocString, func(invocation interpreter.Invocation) interpreter.Value { payer, ok := invocation.Arguments[0].(interpreter.MemberAccessibleValue) @@ -95,14 +109,14 @@ func NewAuthAccountConstructor(creator AccountCreator) StandardLibraryValue { inter.ExpectType( payer, - sema.AuthAccountType, + sema.AccountReferenceType, locationRange, ) payerValue := payer.GetMember( inter, locationRange, - sema.AuthAccountTypeAddressFieldName, + sema.AccountTypeAddressFieldName, ) if payerValue == nil { panic(errors.NewUnexpectedError("payer address is not set")) @@ -137,36 +151,54 @@ func NewAuthAccountConstructor(creator AccountCreator) StandardLibraryValue { locationRange, ) - return NewAuthAccountValue( + return NewAccountReferenceValue( inter, creator, addressValue, + interpreter.FullyEntitledAccountAccess, ) }, ) } -const getAuthAccountDocString = ` -Returns the AuthAccount for the given address. Only available in scripts +const getAuthAccountFunctionName = "getAuthAccount" +const getAuthAccountFunctionDocString = ` +Returns the account for the given address. Only available in scripts ` -var getAuthAccountFunctionType = sema.NewSimpleFunctionType( - sema.FunctionPurityView, - []sema.Parameter{ - { - Label: sema.ArgumentLabelNotRequired, - Identifier: "address", - TypeAnnotation: sema.AddressTypeAnnotation, +// getAuthAccountFunctionType represents the type +// +// fun getAuthAccount(_ address: Address): T +var getAuthAccountFunctionType = func() *sema.FunctionType { + + typeParam := &sema.TypeParameter{ + Name: "T", + TypeBound: sema.AccountReferenceType, + } + + return &sema.FunctionType{ + Purity: sema.FunctionPurityView, + TypeParameters: []*sema.TypeParameter{typeParam}, + Parameters: []sema.Parameter{ + { + Label: sema.ArgumentLabelNotRequired, + Identifier: "address", + TypeAnnotation: sema.AddressTypeAnnotation, + }, }, - }, - sema.AuthAccountTypeAnnotation, -) + ReturnTypeAnnotation: sema.NewTypeAnnotation( + &sema.GenericType{ + TypeParameter: typeParam, + }, + ), + } +}() -func NewGetAuthAccountFunction(handler AuthAccountHandler) StandardLibraryValue { +func NewGetAuthAccountFunction(handler AccountHandler) StandardLibraryValue { return NewStandardLibraryFunction( - "getAuthAccount", + getAuthAccountFunctionName, getAuthAccountFunctionType, - getAuthAccountDocString, + getAuthAccountFunctionDocString, func(invocation interpreter.Invocation) interpreter.Value { accountAddress, ok := invocation.Arguments[0].(interpreter.AddressValue) if !ok { @@ -175,50 +207,89 @@ func NewGetAuthAccountFunction(handler AuthAccountHandler) StandardLibraryValue gauge := invocation.Interpreter - return NewAuthAccountValue( + typeParameterPair := invocation.TypeParameterTypes.Oldest() + if typeParameterPair == nil { + panic(errors.NewUnreachableError()) + } + + ty := typeParameterPair.Value + + referenceType, ok := ty.(*sema.ReferenceType) + if !ok { + panic(errors.NewUnreachableError()) + } + + authorization := interpreter.ConvertSemaAccessToStaticAuthorization( + gauge, + referenceType.Authorization, + ) + + return NewAccountReferenceValue( gauge, handler, accountAddress, + authorization, ) }, ) } -func NewAuthAccountValue( +func NewAccountReferenceValue( + gauge common.MemoryGauge, + handler AccountHandler, + addressValue interpreter.AddressValue, + authorization interpreter.Authorization, +) interpreter.Value { + account := NewAccountValue(gauge, handler, addressValue) + return interpreter.NewEphemeralReferenceValue( + gauge, + authorization, + account, + sema.AccountType, + ) +} + +func NewAccountValue( gauge common.MemoryGauge, - handler AuthAccountHandler, + handler AccountHandler, addressValue interpreter.AddressValue, ) interpreter.Value { - return interpreter.NewAuthAccountValue( + + return interpreter.NewAccountValue( gauge, addressValue, newAccountBalanceGetFunction(gauge, handler, addressValue), newAccountAvailableBalanceGetFunction(gauge, handler, addressValue), - newStorageUsedGetFunction(handler, addressValue), - newStorageCapacityGetFunction(handler, addressValue), func() interpreter.Value { - return newAuthAccountContractsValue( + return newAccountStorageValue( gauge, handler, addressValue, ) }, func() interpreter.Value { - return newAuthAccountKeysValue( + return newAccountContractsValue( gauge, handler, addressValue, ) }, func() interpreter.Value { - return newAuthAccountInboxValue( + return newAccountKeysValue( gauge, handler, addressValue, ) }, func() interpreter.Value { - return newAuthAccountCapabilitiesValue( + return newAccountInboxValue( + gauge, + handler, + addressValue, + ) + }, + func() interpreter.Value { + return newAccountCapabilitiesValue( gauge, handler, addressValue, @@ -227,48 +298,48 @@ func NewAuthAccountValue( ) } -type AuthAccountContractsHandler interface { +type AccountContractsHandler interface { AccountContractProvider AccountContractAdditionHandler AccountContractRemovalHandler AccountContractNamesProvider } -func newAuthAccountContractsValue( +func newAccountContractsValue( gauge common.MemoryGauge, - handler AuthAccountContractsHandler, + handler AccountContractsHandler, addressValue interpreter.AddressValue, ) interpreter.Value { - return interpreter.NewAuthAccountContractsValue( + return interpreter.NewAccountContractsValue( gauge, addressValue, - newAuthAccountContractsChangeFunction( - sema.AuthAccountContractsTypeAddFunctionType, + newAccountContractsChangeFunction( + sema.Account_ContractsTypeAddFunctionType, gauge, handler, addressValue, false, ), - newAuthAccountContractsChangeFunction( - sema.AuthAccountContractsTypeUpdate__experimentalFunctionType, + newAccountContractsChangeFunction( + sema.Account_ContractsTypeUpdateFunctionType, gauge, handler, addressValue, true, ), newAccountContractsGetFunction( - sema.AuthAccountContractsTypeGetFunctionType, + sema.Account_ContractsTypeGetFunctionType, gauge, handler, addressValue, ), newAccountContractsBorrowFunction( - sema.AuthAccountContractsTypeBorrowFunctionType, + sema.Account_ContractsTypeBorrowFunctionType, gauge, handler, addressValue, ), - newAuthAccountContractsRemoveFunction( + newAccountContractsRemoveFunction( gauge, handler, addressValue, @@ -280,18 +351,36 @@ func newAuthAccountContractsValue( ) } -type AuthAccountKeysHandler interface { +type AccountStorageHandler interface { + StorageUsedProvider + StorageCapacityProvider +} + +func newAccountStorageValue( + gauge common.MemoryGauge, + handler AccountStorageHandler, + addressValue interpreter.AddressValue, +) interpreter.Value { + return interpreter.NewAccountStorageValue( + gauge, + addressValue, + newStorageUsedGetFunction(handler, addressValue), + newStorageCapacityGetFunction(handler, addressValue), + ) +} + +type AccountKeysHandler interface { AccountKeyProvider AccountKeyAdditionHandler AccountKeyRevocationHandler } -func newAuthAccountKeysValue( +func newAccountKeysValue( gauge common.MemoryGauge, - handler AuthAccountKeysHandler, + handler AccountKeysHandler, addressValue interpreter.AddressValue, ) interpreter.Value { - return interpreter.NewAuthAccountKeysValue( + return interpreter.NewAccountKeysValue( gauge, addressValue, newAccountKeysAddFunction( @@ -300,7 +389,7 @@ func newAuthAccountKeysValue( addressValue, ), newAccountKeysGetFunction( - sema.AuthAccountKeysTypeGetFunctionType, + sema.Account_KeysTypeGetFunctionType, gauge, handler, addressValue, @@ -311,7 +400,7 @@ func newAuthAccountKeysValue( addressValue, ), newAccountKeysForEachFunction( - sema.AuthAccountKeysTypeForEachFunctionType, + sema.Account_KeysTypeForEachFunctionType, gauge, handler, addressValue, @@ -478,7 +567,7 @@ func newAccountKeysAddFunction( return interpreter.NewHostFunctionValue( gauge, - sema.AuthAccountKeysTypeAddFunctionType, + sema.Account_KeysTypeAddFunctionType, func(invocation interpreter.Invocation) interpreter.Value { publicKeyValue, ok := invocation.Arguments[0].(*interpreter.CompositeValue) if !ok { @@ -604,7 +693,7 @@ func newAccountKeysGetFunction( } // accountKeysForEachCallbackTypeParams are the parameter types of the callback function of -// `Auth/PublicAccount.Keys.forEachKey(_ f: fun(AccountKey): Bool)` +// `Account.Keys.forEachKey(_ f: fun(AccountKey): Bool)` var accountKeysForEachCallbackTypeParams = []sema.Type{sema.AccountKeyType} func newAccountKeysForEachFunction( @@ -753,7 +842,7 @@ func newAccountKeysRevokeFunction( return interpreter.NewHostFunctionValue( gauge, - sema.AuthAccountKeysTypeRevokeFunctionType, + sema.Account_KeysTypeRevokeFunctionType, func(invocation interpreter.Invocation) interpreter.Value { indexValue, ok := invocation.Arguments[0].(interpreter.IntValue) if !ok { @@ -805,73 +894,9 @@ func newAccountKeysRevokeFunction( ) } -type PublicAccountKeysHandler interface { - AccountKeyProvider -} - -func newPublicAccountKeysValue( - gauge common.MemoryGauge, - handler PublicAccountKeysHandler, - addressValue interpreter.AddressValue, -) interpreter.Value { - return interpreter.NewPublicAccountKeysValue( - gauge, - addressValue, - newAccountKeysGetFunction( - sema.PublicAccountKeysTypeGetFunctionType, - gauge, - handler, - addressValue, - ), - newAccountKeysForEachFunction( - sema.PublicAccountKeysTypeForEachFunctionType, - gauge, - handler, - addressValue, - ), - newAccountKeysCountGetter( - gauge, - handler, - addressValue, - ), - ) -} - -type PublicAccountContractsHandler interface { - AccountContractNamesProvider - AccountContractProvider -} - -func newPublicAccountContractsValue( - gauge common.MemoryGauge, - handler PublicAccountContractsHandler, - addressValue interpreter.AddressValue, -) interpreter.Value { - return interpreter.NewPublicAccountContractsValue( - gauge, - addressValue, - newAccountContractsGetFunction( - sema.PublicAccountContractsTypeGetFunctionType, - gauge, - handler, - addressValue, - ), - newAccountContractsBorrowFunction( - sema.PublicAccountContractsTypeBorrowFunctionType, - gauge, - handler, - addressValue, - ), - newAccountContractsGetNamesFunction( - handler, - addressValue, - ), - ) -} - const InboxStorageDomain = "inbox" -func newAuthAccountInboxPublishFunction( +func newAccountInboxPublishFunction( gauge common.MemoryGauge, handler EventEmitter, providerValue interpreter.AddressValue, @@ -879,7 +904,7 @@ func newAuthAccountInboxPublishFunction( provider := providerValue.ToAddress() return interpreter.NewHostFunctionValue( gauge, - sema.AuthAccountInboxTypePublishFunctionType, + sema.Account_InboxTypePublishFunctionType, func(invocation interpreter.Invocation) interpreter.Value { value, ok := invocation.Arguments[0].(*interpreter.CapabilityValue) if !ok { @@ -934,7 +959,7 @@ func newAuthAccountInboxPublishFunction( ) } -func newAuthAccountInboxUnpublishFunction( +func newAccountInboxUnpublishFunction( gauge common.MemoryGauge, handler EventEmitter, providerValue interpreter.AddressValue, @@ -942,7 +967,7 @@ func newAuthAccountInboxUnpublishFunction( provider := providerValue.ToAddress() return interpreter.NewHostFunctionValue( gauge, - sema.AuthAccountInboxTypeUnpublishFunctionType, + sema.Account_InboxTypeUnpublishFunctionType, func(invocation interpreter.Invocation) interpreter.Value { nameValue, ok := invocation.Arguments[0].(*interpreter.StringValue) if !ok { @@ -1009,14 +1034,14 @@ func newAuthAccountInboxUnpublishFunction( ) } -func newAuthAccountInboxClaimFunction( +func newAccountInboxClaimFunction( gauge common.MemoryGauge, handler EventEmitter, recipientValue interpreter.AddressValue, ) *interpreter.HostFunctionValue { return interpreter.NewHostFunctionValue( gauge, - sema.AuthAccountInboxTypePublishFunctionType, + sema.Account_InboxTypePublishFunctionType, func(invocation interpreter.Invocation) interpreter.Value { nameValue, ok := invocation.Arguments[0].(*interpreter.StringValue) if !ok { @@ -1096,17 +1121,17 @@ func newAuthAccountInboxClaimFunction( ) } -func newAuthAccountInboxValue( +func newAccountInboxValue( gauge common.MemoryGauge, handler EventEmitter, addressValue interpreter.AddressValue, ) interpreter.Value { - return interpreter.NewAuthAccountInboxValue( + return interpreter.NewAccountInboxValue( gauge, addressValue, - newAuthAccountInboxPublishFunction(gauge, handler, addressValue), - newAuthAccountInboxUnpublishFunction(gauge, handler, addressValue), - newAuthAccountInboxClaimFunction(gauge, handler, addressValue), + newAccountInboxPublishFunction(gauge, handler, addressValue), + newAccountInboxUnpublishFunction(gauge, handler, addressValue), + newAccountInboxClaimFunction(gauge, handler, addressValue), ) } @@ -1227,7 +1252,7 @@ func newAccountContractsGetFunction( func newAccountContractsBorrowFunction( functionType *sema.FunctionType, gauge common.MemoryGauge, - handler PublicAccountContractsHandler, + handler AccountContractsHandler, addressValue interpreter.AddressValue, ) *interpreter.HostFunctionValue { @@ -1330,10 +1355,10 @@ type AccountContractAdditionHandler interface { TemporarilyRecordCode(location common.AddressLocation, code []byte) } -// newAuthAccountContractsChangeFunction called when e.g. -// - adding: `AuthAccount.contracts.add(name: "Foo", code: [...])` (isUpdate = false) -// - updating: `AuthAccount.contracts.update__experimental(name: "Foo", code: [...])` (isUpdate = true) -func newAuthAccountContractsChangeFunction( +// newAccountContractsChangeFunction called when e.g. +// - adding: `Account.contracts.add(name: "Foo", code: [...])` (isUpdate = false) +// - updating: `Account.contracts.update(name: "Foo", code: [...])` (isUpdate = true) +func newAccountContractsChangeFunction( functionType *sema.FunctionType, gauge common.MemoryGauge, handler AccountContractAdditionHandler, @@ -1680,7 +1705,7 @@ func updateAccountContractCode( // If a contract is deployed, it is only instantiated // when options.createContract is true, // i.e. the Cadence `add` function is used. - // If the Cadence `update__experimental` function is used, + // If the Cadence `update` function is used, // the new contract will NOT be deployed (options.createContract is false). var contractValue *interpreter.CompositeValue @@ -1836,7 +1861,7 @@ type AccountContractRemovalHandler interface { RecordContractRemoval(location common.AddressLocation) } -func newAuthAccountContractsRemoveFunction( +func newAccountContractsRemoveFunction( gauge common.MemoryGauge, handler AccountContractRemovalHandler, addressValue interpreter.AddressValue, @@ -1847,7 +1872,7 @@ func newAuthAccountContractsRemoveFunction( return interpreter.NewHostFunctionValue( gauge, - sema.AuthAccountContractsTypeRemoveFunctionType, + sema.Account_ContractsTypeRemoveFunctionType, func(invocation interpreter.Invocation) interpreter.Value { inter := invocation.Interpreter @@ -1949,33 +1974,22 @@ func (e *ContractRemovalError) Error() string { } const getAccountFunctionDocString = ` -Returns the public account for the given address +Returns the account for the given address ` var getAccountFunctionType = sema.NewSimpleFunctionType( sema.FunctionPurityView, []sema.Parameter{ { - Label: sema.ArgumentLabelNotRequired, - Identifier: "address", - TypeAnnotation: sema.NewTypeAnnotation( - sema.TheAddressType, - ), + Label: sema.ArgumentLabelNotRequired, + Identifier: "address", + TypeAnnotation: sema.AddressTypeAnnotation, }, }, - sema.PublicAccountTypeAnnotation, + sema.AccountReferenceTypeAnnotation, ) -type PublicAccountHandler interface { - BalanceProvider - AvailableBalanceProvider - StorageUsedProvider - StorageCapacityProvider - PublicAccountKeysHandler - PublicAccountContractsHandler -} - -func NewGetAccountFunction(handler PublicAccountHandler) StandardLibraryValue { +func NewGetAccountFunction(handler AccountHandler) StandardLibraryValue { return NewStandardLibraryFunction( "getAccount", getAccountFunctionType, @@ -1986,45 +2000,11 @@ func NewGetAccountFunction(handler PublicAccountHandler) StandardLibraryValue { panic(errors.NewUnreachableError()) } - return NewPublicAccountValue( + return NewAccountReferenceValue( invocation.Interpreter, handler, accountAddress, - ) - }, - ) -} - -func NewPublicAccountValue( - gauge common.MemoryGauge, - handler PublicAccountHandler, - addressValue interpreter.AddressValue, -) interpreter.Value { - return interpreter.NewPublicAccountValue( - gauge, - addressValue, - newAccountBalanceGetFunction(gauge, handler, addressValue), - newAccountAvailableBalanceGetFunction(gauge, handler, addressValue), - newStorageUsedGetFunction(handler, addressValue), - newStorageCapacityGetFunction(handler, addressValue), - func() interpreter.Value { - return newPublicAccountKeysValue( - gauge, - handler, - addressValue, - ) - }, - func() interpreter.Value { - return newPublicAccountContractsValue( - gauge, - handler, - addressValue, - ) - }, - func() interpreter.Value { - return newPublicAccountCapabilitiesValue( - gauge, - addressValue, + interpreter.UnauthorizedAccess, ) }, ) @@ -2088,57 +2068,57 @@ func CodeToHashValue(inter *interpreter.Interpreter, code []byte) *interpreter.A return interpreter.ByteSliceToConstantSizedByteArrayValue(inter, codeHash[:]) } -func newAuthAccountStorageCapabilitiesValue( +func newAccountStorageCapabilitiesValue( gauge common.MemoryGauge, accountIDGenerator AccountIDGenerator, addressValue interpreter.AddressValue, ) interpreter.Value { - return interpreter.NewAuthAccountStorageCapabilitiesValue( + return interpreter.NewAccountStorageCapabilitiesValue( gauge, addressValue, - newAuthAccountStorageCapabilitiesGetControllerFunction(gauge, addressValue), - newAuthAccountStorageCapabilitiesGetControllersFunction(gauge, addressValue), - newAuthAccountStorageCapabilitiesForEachControllerFunction(gauge, addressValue), - newAuthAccountStorageCapabilitiesIssueFunction(gauge, accountIDGenerator, addressValue), + newAccountStorageCapabilitiesGetControllerFunction(gauge, addressValue), + newAccountStorageCapabilitiesGetControllersFunction(gauge, addressValue), + newAccountStorageCapabilitiesForEachControllerFunction(gauge, addressValue), + newAccountStorageCapabilitiesIssueFunction(gauge, accountIDGenerator, addressValue), ) } -func newAuthAccountAccountCapabilitiesValue( +func newAccountAccountCapabilitiesValue( gauge common.MemoryGauge, accountIDGenerator AccountIDGenerator, addressValue interpreter.AddressValue, ) interpreter.Value { - return interpreter.NewAuthAccountAccountCapabilitiesValue( + return interpreter.NewAccountAccountCapabilitiesValue( gauge, addressValue, - newAuthAccountAccountCapabilitiesGetControllerFunction(gauge, addressValue), - newAuthAccountAccountCapabilitiesGetControllersFunction(gauge, addressValue), - newAuthAccountAccountCapabilitiesForEachControllerFunction(gauge, addressValue), - newAuthAccountAccountCapabilitiesIssueFunction(gauge, accountIDGenerator, addressValue), + newAccountAccountCapabilitiesGetControllerFunction(gauge, addressValue), + newAccountAccountCapabilitiesGetControllersFunction(gauge, addressValue), + newAccountAccountCapabilitiesForEachControllerFunction(gauge, addressValue), + newAccountAccountCapabilitiesIssueFunction(gauge, accountIDGenerator, addressValue), ) } -func newAuthAccountCapabilitiesValue( +func newAccountCapabilitiesValue( gauge common.MemoryGauge, idGenerator AccountIDGenerator, addressValue interpreter.AddressValue, ) interpreter.Value { - return interpreter.NewAuthAccountCapabilitiesValue( + return interpreter.NewAccountCapabilitiesValue( gauge, addressValue, - newAccountCapabilitiesGetFunction(gauge, addressValue, sema.AuthAccountType, false), - newAccountCapabilitiesGetFunction(gauge, addressValue, sema.AuthAccountType, true), - newAuthAccountCapabilitiesPublishFunction(gauge, addressValue), - newAuthAccountCapabilitiesUnpublishFunction(gauge, addressValue), + newAccountCapabilitiesGetFunction(gauge, addressValue, false), + newAccountCapabilitiesGetFunction(gauge, addressValue, true), + newAccountCapabilitiesPublishFunction(gauge, addressValue), + newAccountCapabilitiesUnpublishFunction(gauge, addressValue), func() interpreter.Value { - return newAuthAccountStorageCapabilitiesValue( + return newAccountStorageCapabilitiesValue( gauge, idGenerator, addressValue, ) }, func() interpreter.Value { - return newAuthAccountAccountCapabilitiesValue( + return newAccountAccountCapabilitiesValue( gauge, idGenerator, addressValue, @@ -2147,14 +2127,14 @@ func newAuthAccountCapabilitiesValue( ) } -func newAuthAccountStorageCapabilitiesGetControllerFunction( +func newAccountStorageCapabilitiesGetControllerFunction( gauge common.MemoryGauge, addressValue interpreter.AddressValue, ) interpreter.FunctionValue { address := addressValue.ToAddress() return interpreter.NewHostFunctionValue( gauge, - sema.AuthAccountStorageCapabilitiesTypeGetControllerFunctionType, + sema.Account_StorageCapabilitiesTypeGetControllerFunctionType, func(invocation interpreter.Invocation) interpreter.Value { inter := invocation.Interpreter @@ -2185,14 +2165,14 @@ var storageCapabilityControllerReferencesArrayStaticType = interpreter.VariableS }, } -func newAuthAccountStorageCapabilitiesGetControllersFunction( +func newAccountStorageCapabilitiesGetControllersFunction( gauge common.MemoryGauge, addressValue interpreter.AddressValue, ) interpreter.FunctionValue { address := addressValue.ToAddress() return interpreter.NewHostFunctionValue( gauge, - sema.AuthAccountStorageCapabilitiesTypeGetControllersFunctionType, + sema.Account_StorageCapabilitiesTypeGetControllersFunctionType, func(invocation interpreter.Invocation) interpreter.Value { inter := invocation.Interpreter @@ -2241,14 +2221,14 @@ func newAuthAccountStorageCapabilitiesGetControllersFunction( // `(&StorageCapabilityController)` in // `forEachController(forPath: StoragePath, _ function: fun(&StorageCapabilityController): Bool)` -var authAccountStorageCapabilitiesForEachControllerCallbackTypeParams = []sema.Type{ +var accountStorageCapabilitiesForEachControllerCallbackTypeParams = []sema.Type{ &sema.ReferenceType{ Type: sema.StorageCapabilityControllerType, Authorization: sema.UnauthorizedAccess, }, } -func newAuthAccountStorageCapabilitiesForEachControllerFunction( +func newAccountStorageCapabilitiesForEachControllerFunction( gauge common.MemoryGauge, addressValue interpreter.AddressValue, ) *interpreter.HostFunctionValue { @@ -2256,7 +2236,7 @@ func newAuthAccountStorageCapabilitiesForEachControllerFunction( return interpreter.NewHostFunctionValue( gauge, - sema.AuthAccountStorageCapabilitiesTypeForEachControllerFunctionType, + sema.Account_StorageCapabilitiesTypeForEachControllerFunctionType, func(invocation interpreter.Invocation) interpreter.Value { inter := invocation.Interpreter @@ -2314,7 +2294,7 @@ func newAuthAccountStorageCapabilitiesForEachControllerFunction( nil, nil, []interpreter.Value{referenceValue}, - authAccountStorageCapabilitiesForEachControllerCallbackTypeParams, + accountStorageCapabilitiesForEachControllerCallbackTypeParams, nil, locationRange, ) @@ -2354,7 +2334,7 @@ func newAuthAccountStorageCapabilitiesForEachControllerFunction( ) } -func newAuthAccountStorageCapabilitiesIssueFunction( +func newAccountStorageCapabilitiesIssueFunction( gauge common.MemoryGauge, idGenerator AccountIDGenerator, addressValue interpreter.AddressValue, @@ -2362,7 +2342,7 @@ func newAuthAccountStorageCapabilitiesIssueFunction( address := addressValue.ToAddress() return interpreter.NewHostFunctionValue( gauge, - sema.AuthAccountStorageCapabilitiesTypeIssueFunctionType, + sema.Account_StorageCapabilitiesTypeIssueFunctionType, func(invocation interpreter.Invocation) interpreter.Value { inter := invocation.Interpreter @@ -2444,7 +2424,7 @@ func issueStorageCapabilityController( return capabilityIDValue, borrowStaticType } -func newAuthAccountAccountCapabilitiesIssueFunction( +func newAccountAccountCapabilitiesIssueFunction( gauge common.MemoryGauge, idGenerator AccountIDGenerator, addressValue interpreter.AddressValue, @@ -2452,7 +2432,7 @@ func newAuthAccountAccountCapabilitiesIssueFunction( address := addressValue.ToAddress() return interpreter.NewHostFunctionValue( gauge, - sema.AuthAccountAccountCapabilitiesTypeIssueFunctionType, + sema.Account_AccountCapabilitiesTypeIssueFunctionType, func(invocation interpreter.Invocation) interpreter.Value { inter := invocation.Interpreter @@ -3027,14 +3007,14 @@ func getAccountCapabilityControllerIDsIterator( return } -func newAuthAccountCapabilitiesPublishFunction( +func newAccountCapabilitiesPublishFunction( gauge common.MemoryGauge, addressValue interpreter.AddressValue, ) *interpreter.HostFunctionValue { address := addressValue.ToAddress() return interpreter.NewHostFunctionValue( gauge, - sema.AuthAccountCapabilitiesTypePublishFunctionType, + sema.Account_CapabilitiesTypePublishFunctionType, func(invocation interpreter.Invocation) interpreter.Value { inter := invocation.Interpreter @@ -3107,14 +3087,14 @@ func newAuthAccountCapabilitiesPublishFunction( ) } -func newAuthAccountCapabilitiesUnpublishFunction( +func newAccountCapabilitiesUnpublishFunction( gauge common.MemoryGauge, addressValue interpreter.AddressValue, ) *interpreter.HostFunctionValue { address := addressValue.ToAddress() return interpreter.NewHostFunctionValue( gauge, - sema.AuthAccountCapabilitiesTypeUnpublishFunctionType, + sema.Account_CapabilitiesTypeUnpublishFunctionType, func(invocation interpreter.Invocation) interpreter.Value { inter := invocation.Interpreter @@ -3172,18 +3152,6 @@ func newAuthAccountCapabilitiesUnpublishFunction( ) } -func newPublicAccountCapabilitiesValue( - gauge common.MemoryGauge, - addressValue interpreter.AddressValue, -) interpreter.Value { - return interpreter.NewPublicAccountCapabilitiesValue( - gauge, - addressValue, - newAccountCapabilitiesGetFunction(gauge, addressValue, sema.PublicAccountType, false), - newAccountCapabilitiesGetFunction(gauge, addressValue, sema.PublicAccountType, true), - ) -} - func getCheckedCapabilityController( inter *interpreter.Interpreter, capabilityAddressValue interpreter.AddressValue, @@ -3329,27 +3297,16 @@ func CheckCapabilityController( func newAccountCapabilitiesGetFunction( gauge common.MemoryGauge, addressValue interpreter.AddressValue, - accountType *sema.CompositeType, borrow bool, ) *interpreter.HostFunctionValue { address := addressValue.ToAddress() var funcType *sema.FunctionType - switch accountType { - case sema.AuthAccountType: - if borrow { - funcType = sema.AuthAccountCapabilitiesTypeBorrowFunctionType - } else { - funcType = sema.AuthAccountCapabilitiesTypeGetFunctionType - } - case sema.PublicAccountType: - if borrow { - funcType = sema.PublicAccountCapabilitiesTypeBorrowFunctionType - } else { - funcType = sema.PublicAccountCapabilitiesTypeGetFunctionType - } - default: - panic(errors.NewUnreachableError()) + + if borrow { + funcType = sema.Account_CapabilitiesTypeBorrowFunctionType + } else { + funcType = sema.Account_CapabilitiesTypeGetFunctionType } return interpreter.NewHostFunctionValue( @@ -3484,14 +3441,14 @@ func getAccountCapabilityControllerReference( ) } -func newAuthAccountAccountCapabilitiesGetControllerFunction( +func newAccountAccountCapabilitiesGetControllerFunction( gauge common.MemoryGauge, addressValue interpreter.AddressValue, ) interpreter.FunctionValue { address := addressValue.ToAddress() return interpreter.NewHostFunctionValue( gauge, - sema.AuthAccountAccountCapabilitiesTypeGetControllerFunctionType, + sema.Account_AccountCapabilitiesTypeGetControllerFunctionType, func(invocation interpreter.Invocation) interpreter.Value { inter := invocation.Interpreter @@ -3522,14 +3479,14 @@ var accountCapabilityControllerReferencesArrayStaticType = interpreter.VariableS }, } -func newAuthAccountAccountCapabilitiesGetControllersFunction( +func newAccountAccountCapabilitiesGetControllersFunction( gauge common.MemoryGauge, addressValue interpreter.AddressValue, ) interpreter.FunctionValue { address := addressValue.ToAddress() return interpreter.NewHostFunctionValue( gauge, - sema.AuthAccountAccountCapabilitiesTypeGetControllersFunctionType, + sema.Account_AccountCapabilitiesTypeGetControllersFunctionType, func(invocation interpreter.Invocation) interpreter.Value { inter := invocation.Interpreter @@ -3571,7 +3528,7 @@ func newAuthAccountAccountCapabilitiesGetControllersFunction( // `(&AccountCapabilityController)` in // `forEachController(_ function: fun(&AccountCapabilityController): Bool)` -var authAccountAccountCapabilitiesForEachControllerCallbackTypeParams = []sema.Type{ +var accountAccountCapabilitiesForEachControllerCallbackTypeParams = []sema.Type{ &sema.ReferenceType{ Type: sema.AccountCapabilityControllerType, Authorization: sema.UnauthorizedAccess, @@ -3591,7 +3548,7 @@ func (CapabilityControllersMutatedDuringIterationError) Error() string { return "capability controller iteration continued after changes to controllers" } -func newAuthAccountAccountCapabilitiesForEachControllerFunction( +func newAccountAccountCapabilitiesForEachControllerFunction( gauge common.MemoryGauge, addressValue interpreter.AddressValue, ) *interpreter.HostFunctionValue { @@ -3599,7 +3556,7 @@ func newAuthAccountAccountCapabilitiesForEachControllerFunction( return interpreter.NewHostFunctionValue( gauge, - sema.AuthAccountAccountCapabilitiesTypeForEachControllerFunctionType, + sema.Account_AccountCapabilitiesTypeForEachControllerFunctionType, func(invocation interpreter.Invocation) interpreter.Value { inter := invocation.Interpreter @@ -3649,7 +3606,7 @@ func newAuthAccountAccountCapabilitiesForEachControllerFunction( nil, nil, []interpreter.Value{referenceValue}, - authAccountAccountCapabilitiesForEachControllerCallbackTypeParams, + accountAccountCapabilitiesForEachControllerCallbackTypeParams, nil, locationRange, ) diff --git a/runtime/stdlib/builtin.go b/runtime/stdlib/builtin.go index 60e0111fc2..d292eb1bef 100644 --- a/runtime/stdlib/builtin.go +++ b/runtime/stdlib/builtin.go @@ -23,7 +23,6 @@ type StandardLibraryHandler interface { UnsafeRandomGenerator BlockAtHeightProvider CurrentBlockProvider - PublicAccountHandler AccountCreator PublicKeyValidator PublicKeySignatureVerifier @@ -44,7 +43,7 @@ func DefaultStandardLibraryValues(handler StandardLibraryHandler) []StandardLibr NewGetBlockFunction(handler), NewGetCurrentBlockFunction(handler), NewGetAccountFunction(handler), - NewAuthAccountConstructor(handler), + NewAccountConstructor(handler), NewPublicKeyConstructor(handler, handler, handler), NewBLSContract(nil, handler), NewHashAlgorithmConstructor(handler), diff --git a/runtime/stdlib/contracts/test.cdc b/runtime/stdlib/contracts/test.cdc index 73b185d6bd..f9a022518c 100644 --- a/runtime/stdlib/contracts/test.cdc +++ b/runtime/stdlib/contracts/test.cdc @@ -28,7 +28,7 @@ contract Test { /// The returned account can be used to sign and authorize transactions. /// access(all) - fun createAccount(): Account { + fun createAccount(): TestAccount { return self.backend.createAccount() } @@ -89,7 +89,7 @@ contract Test { fun deployContract( name: String, code: String, - account: Account, + account: TestAccount, arguments: [AnyStruct] ): Error? { return self.backend.deployContract( @@ -119,7 +119,7 @@ contract Test { /// transactions with this account. /// access(all) - fun serviceAccount(): Account { + fun serviceAccount(): TestAccount { return self.backend.serviceAccount() } @@ -197,7 +197,7 @@ contract Test { /// Result is the interface to be implemented by the various execution /// operations, such as transactions and scripts. - ///\ + /// access(all) struct interface Result { /// The result status of an executed operation. @@ -260,10 +260,10 @@ contract Test { } } - /// Account represents info about the account created on the blockchain. + /// TestAccount represents info about the account created on the blockchain. /// access(all) - struct Account { + struct TestAccount { access(all) let address: Address @@ -303,13 +303,12 @@ contract Test { let authorizers: [Address] access(all) - let signers: [Account] + let signers: [TestAccount] access(all) let arguments: [AnyStruct] - - init(code: String, authorizers: [Address], signers: [Account], arguments: [AnyStruct]) { + init(code: String, authorizers: [Address], signers: [TestAccount], arguments: [AnyStruct]) { self.code = code self.authorizers = authorizers self.signers = signers @@ -333,7 +332,7 @@ contract Test { /// The returned account can be used to sign and authorize transactions. /// access(all) - fun createAccount(): Account + fun createAccount(): TestAccount /// Add a transaction to the current block. /// @@ -358,7 +357,7 @@ contract Test { fun deployContract( name: String, code: String, - account: Account, + account: TestAccount, arguments: [AnyStruct] ): Error? @@ -377,7 +376,7 @@ contract Test { /// transactions with this account. /// access(all) - fun serviceAccount(): Account + fun serviceAccount(): TestAccount /// Returns all events emitted from the blockchain, optionally filtered /// by type. diff --git a/runtime/storage_test.go b/runtime/storage_test.go index c31f39de9b..d7cd3dfb89 100644 --- a/runtime/storage_test.go +++ b/runtime/storage_test.go @@ -157,8 +157,8 @@ func TestRuntimeStorageWrite(t *testing.T) { tx := []byte(` transaction { - prepare(signer: AuthAccount) { - signer.save(1, to: /storage/one) + prepare(signer: auth(Storage) &Account) { + signer.storage.save(1, to: /storage/one) } } `) @@ -217,10 +217,10 @@ func TestRuntimeAccountStorage(t *testing.T) { script := []byte(` transaction { - prepare(signer: AuthAccount) { - let before = signer.storageUsed - signer.save(42, to: /storage/answer) - let after = signer.storageUsed + prepare(signer: auth(Storage) &Account) { + let before = signer.storage.used + signer.storage.save(42, to: /storage/answer) + let after = signer.storage.used log(after != before) } } @@ -360,13 +360,13 @@ func TestRuntimePublicCapabilityBorrowTypeConfusion(t *testing.T) { import TestContract from 0xaad3e26e406987c2 transaction { - prepare(acct: AuthAccount) { + prepare(signer: auth(Storage, Capabilities) &Account) { let rc <- TestContract.createConverter() - acct.save(<-rc, to: /storage/rc) + signer.storage.save(<-rc, to: /storage/rc) - let cap = acct.capabilities.storage.issue<&TestContract.resourceConverter2>(/storage/rc) - acct.capabilities.publish(cap, at: /public/rc) + let cap = signer.capabilities.storage.issue<&TestContract.resourceConverter2>(/storage/rc) + signer.capabilities.publish(cap, at: /public/rc) let ref = getAccount(0xaad3e26e406987c2) .capabilities @@ -414,8 +414,8 @@ func TestRuntimeStorageReadAndBorrow(t *testing.T) { Script{ Source: []byte(` transaction { - prepare(signer: AuthAccount) { - signer.save(42, to: /storage/test) + prepare(signer: auth(Storage, Capabilities) &Account) { + signer.storage.save(42, to: /storage/test) let cap = signer.capabilities.storage.issue<&Int>(/storage/test) signer.capabilities.publish(cap, at: /public/test) } @@ -483,7 +483,7 @@ func TestRuntimeStorageReadAndBorrow(t *testing.T) { cadence.Address(signer), cadence.NewReferenceType( cadence.Unauthorized{}, - cadence.IntType{}, + cadence.IntType, ), ), value, @@ -681,8 +681,8 @@ func TestRuntimeTopShotBatchTransfer(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - let adminRef = signer.borrow<&TopShot.Admin>(from: /storage/TopShotAdmin)! + prepare(signer: auth(Storage) &Account) { + let adminRef = signer.storage.borrow<&TopShot.Admin>(from: /storage/TopShotAdmin)! let playID = adminRef.createPlay(metadata: {"name": "Test"}) let setID = TopShot.nextSetID @@ -692,7 +692,7 @@ func TestRuntimeTopShotBatchTransfer(t *testing.T) { let moments <- setRef.batchMintMoment(playID: playID, quantity: 2) - signer.borrow<&TopShot.Collection>(from: /storage/MomentCollection)! + signer.storage.borrow<&TopShot.Collection>(from: /storage/MomentCollection)! .batchDeposit(tokens: <-moments) } } @@ -713,8 +713,8 @@ func TestRuntimeTopShotBatchTransfer(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - signer.save( + prepare(signer: auth(Storage, Capabilities) &Account) { + signer.storage.save( <-TopShot.createEmptyCollection(), to: /storage/MomentCollection ) @@ -749,8 +749,8 @@ func TestRuntimeTopShotBatchTransfer(t *testing.T) { transaction(momentIDs: [UInt64]) { let transferTokens: @{NonFungibleToken.Collection} - prepare(acct: AuthAccount) { - let ref = acct.borrow<&TopShot.Collection>(from: /storage/MomentCollection)! + prepare(signer: auth(Storage) &Account) { + let ref = signer.storage.borrow<&TopShot.Collection>(from: /storage/MomentCollection)! self.transferTokens <- ref.batchWithdraw(ids: momentIDs) } @@ -856,7 +856,7 @@ func TestRuntimeBatchMintAndTransfer(t *testing.T) { } init() { - self.account.save( + self.account.storage.save( <-Test.createEmptyCollection(), to: /storage/MainCollection ) @@ -949,12 +949,12 @@ func TestRuntimeBatchMintAndTransfer(t *testing.T) { transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Storage) &Account) { let collection <- Test.batchMint(count: 1000) log(collection.getIDs()) - signer.borrow<&Test.Collection>(from: /storage/MainCollection)! + signer.storage.borrow<&Test.Collection>(from: /storage/MainCollection)! .batchDeposit(collection: <-collection) } } @@ -974,8 +974,8 @@ func TestRuntimeBatchMintAndTransfer(t *testing.T) { transaction { - prepare(signer: AuthAccount) { - signer.save( + prepare(signer: auth(Storage, Capabilities) &Account) { + signer.storage.save( <-Test.createEmptyCollection(), to: /storage/TestCollection ) @@ -1009,8 +1009,9 @@ func TestRuntimeBatchMintAndTransfer(t *testing.T) { transaction(ids: [UInt64]) { let collection: @Test.Collection - prepare(signer: AuthAccount) { - self.collection <- signer.borrow<&Test.Collection>(from: /storage/MainCollection)! + prepare(signer: auth(Storage) &Account) { + self.collection <- signer.storage + .borrow<&Test.Collection>(from: /storage/MainCollection)! .batchWithdraw(ids: ids) } @@ -1073,8 +1074,8 @@ func TestRuntimeStoragePublishAndUnpublish(t *testing.T) { Script{ Source: []byte(` transaction { - prepare(signer: AuthAccount) { - signer.save(42, to: /storage/test) + prepare(signer: auth(Storage, Capabilities) &Account) { + signer.storage.save(42, to: /storage/test) let cap = signer.capabilities.storage.issue<&Int>(/storage/test) signer.capabilities.publish(cap, at: /public/test) @@ -1097,7 +1098,7 @@ func TestRuntimeStoragePublishAndUnpublish(t *testing.T) { Script{ Source: []byte(` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { signer.capabilities.unpublish(/public/test) assert(signer.capabilities.borrow<&Int>(/public/test) == nil) @@ -1118,7 +1119,7 @@ func TestRuntimeStoragePublishAndUnpublish(t *testing.T) { Script{ Source: []byte(` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Capabilities) &Account) { assert(signer.capabilities.borrow<&Int>(/public/test) == nil) } } @@ -1153,7 +1154,7 @@ func TestRuntimeStorageSaveCapability(t *testing.T) { ty := &cadence.ReferenceType{ Authorization: cadence.UnauthorizedAccess, - Type: cadence.IntType{}, + Type: cadence.IntType, } var storagePathCounter int @@ -1181,13 +1182,13 @@ func TestRuntimeStorageSaveCapability(t *testing.T) { Source: []byte(fmt.Sprintf( ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Storage, Capabilities) &Account) { let cap = signer.capabilities.storage.issue<%[1]s>(/storage/test)! signer.capabilities.publish(cap, at: /public/test) - signer.save(cap, to: %[2]s) + signer.storage.save(cap, to: %[2]s) let cap2 = signer.capabilities.get<%[1]s>(/public/test)! - signer.save(cap2, to: %[3]s) + signer.storage.save(cap2, to: %[3]s) } } `, @@ -1282,8 +1283,8 @@ func TestRuntimeStorageReferenceCast(t *testing.T) { import Test from 0x42 transaction { - prepare(signer: AuthAccount) { - signer.save(<-Test.createR(), to: /storage/r) + prepare(signer: auth(Storage, Capabilities) &Account) { + signer.storage.save(<-Test.createR(), to: /storage/r) let cap = signer.capabilities.storage .issue<&Test.R>(/storage/r) @@ -1380,8 +1381,8 @@ func TestRuntimeStorageReferenceDowncast(t *testing.T) { import Test from 0x42 transaction { - prepare(signer: AuthAccount) { - signer.save(<-Test.createR(), to: /storage/r) + prepare(signer: auth(Storage, Capabilities) &Account) { + signer.storage.save(<-Test.createR(), to: /storage/r) let cap = signer.capabilities.storage.issue<&Test.R>(/storage/r) signer.capabilities.publish(cap, at: /public/r) @@ -1419,8 +1420,8 @@ func TestRuntimeStorageNonStorable(t *testing.T) { let value = &1 as &Int `, "storage reference": ` - signer.save("test", to: /storage/string) - let value = signer.borrow<&String>(from: /storage/string)! + signer.storage.save("test", to: /storage/string) + let value = signer.storage.borrow<&String>(from: /storage/string)! `, "function": ` let value = fun () {} @@ -1433,9 +1434,9 @@ func TestRuntimeStorageNonStorable(t *testing.T) { fmt.Sprintf( ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Storage) &Account) { %s - signer.save((value as AnyStruct), to: /storage/value) + signer.storage.save((value as AnyStruct), to: /storage/value) } } `, @@ -1478,10 +1479,10 @@ func TestRuntimeStorageRecursiveReference(t *testing.T) { const code = ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Storage) &Account) { let refs: [AnyStruct] = [] refs.insert(at: 0, &refs as &AnyStruct) - signer.save(refs, to: /storage/refs) + signer.storage.save(refs, to: /storage/refs) } } ` @@ -1537,8 +1538,8 @@ func TestRuntimeStorageTransfer(t *testing.T) { storeTx := []byte(` transaction { - prepare(signer: AuthAccount) { - signer.save([1], to: /storage/test) + prepare(signer: auth(Storage) &Account) { + signer.storage.save([1], to: /storage/test) } } `) @@ -1560,9 +1561,12 @@ func TestRuntimeStorageTransfer(t *testing.T) { transferTx := []byte(` transaction { - prepare(signer1: AuthAccount, signer2: AuthAccount) { - let value = signer1.load<[Int]>(from: /storage/test)! - signer2.save(value, to: /storage/test) + prepare( + signer1: auth(Storage) &Account, + signer2: auth(Storage) &Account + ) { + let value = signer1.storage.load<[Int]>(from: /storage/test)! + signer2.storage.save(value, to: /storage/test) } } `) @@ -1693,8 +1697,8 @@ func TestRuntimeResourceOwnerChange(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { - signer.save(<-Test.createR(), to: /storage/test) + prepare(signer: auth(Storage) &Account) { + signer.storage.save(<-Test.createR(), to: /storage/test) } } `) @@ -1718,9 +1722,12 @@ func TestRuntimeResourceOwnerChange(t *testing.T) { import Test from 0x1 transaction { - prepare(signer1: AuthAccount, signer2: AuthAccount) { - let value <- signer1.load<@Test.R>(from: /storage/test)! - signer2.save(<-value, to: /storage/test) + prepare( + signer1: auth(Storage) &Account, + signer2: auth(Storage) &Account + ) { + let value <- signer1.storage.load<@Test.R>(from: /storage/test)! + signer2.storage.save(<-value, to: /storage/test) } } `) @@ -1853,7 +1860,7 @@ func TestRuntimeStorageUsed(t *testing.T) { var count = 0 for address in addresses { let account = getAccount(address) - var x = account.storageUsed + var x = account.storage.used } } `) @@ -1871,7 +1878,7 @@ func TestRuntimeStorageUsed(t *testing.T) { } -func TestSortContractUpdates(t *testing.T) { +func TestRuntimeSortContractUpdates(t *testing.T) { t.Parallel() @@ -1997,8 +2004,8 @@ access(all) contract Test { } init() { - self.account.save<@AAA>(<- create AAA(), to: /storage/TestAAA) - self.account.save<@BBB>(<- create BBB(), to: /storage/TestBBB) + self.account.storage.save<@AAA>(<- create AAA(), to: /storage/TestAAA) + self.account.storage.save<@BBB>(<- create BBB(), to: /storage/TestBBB) self.capabilities = {} self.capabilities[Role.aaa] = self.account.capabilities.storage.issue<&AAA>(/storage/TestAAA)! @@ -2012,7 +2019,8 @@ access(all) contract Test { import Test from 0x1 transaction { - prepare(acct: AuthAccount) {} + prepare(signer: &Account) {} + execute { let holder <- Test.createHolder() Test.attach(asRole: Test.Role.aaa, receiver: &holder as &{Test.Receiver}) @@ -2114,15 +2122,17 @@ func TestRuntimeReferenceOwnerAccess(t *testing.T) { transaction { - prepare(accountA: AuthAccount, accountB: AuthAccount) { - + prepare( + accountA: auth(Storage, Capabilities) &Account, + accountB: auth(Storage, Capabilities) &Account + ) { let testResource <- TestContract.makeTestResource() let ref1 = &testResource as &TestContract.TestResource // At this point the resource is not in storage log(ref1.owner?.address) - accountA.save(<-testResource, to: /storage/test) + accountA.storage.save(<-testResource, to: /storage/test) // At this point the resource is in storage A let cap = accountA.capabilities.storage.issue<&TestContract.TestResource>(/storage/test) @@ -2131,14 +2141,14 @@ func TestRuntimeReferenceOwnerAccess(t *testing.T) { let ref2 = accountA.capabilities.borrow<&TestContract.TestResource>(/public/test)! log(ref2.owner?.address) - let testResource2 <- accountA.load<@TestContract.TestResource>(from: /storage/test)! + let testResource2 <- accountA.storage.load<@TestContract.TestResource>(from: /storage/test)! let ref3 = &testResource2 as &TestContract.TestResource // At this point the resource is not in storage log(ref3.owner?.address) - accountB.save(<-testResource2, to: /storage/test) + accountB.storage.save(<-testResource2, to: /storage/test) let cap2 = accountB.capabilities.storage.issue<&TestContract.TestResource>(/storage/test) accountB.capabilities.publish(cap2, at: /public/test) @@ -2261,7 +2271,7 @@ func TestRuntimeReferenceOwnerAccess(t *testing.T) { transaction { - prepare(account: AuthAccount) { + prepare(account: auth(Storage, Capabilities) &Account) { let testResources <- [<-TestContract.makeTestResource()] let ref1 = &testResources[0] as &TestContract.TestResource @@ -2269,7 +2279,7 @@ func TestRuntimeReferenceOwnerAccess(t *testing.T) { // At this point the resource is not in storage log(ref1.owner?.address) - account.save(<-testResources, to: /storage/test) + account.storage.save(<-testResources, to: /storage/test) // At this point the resource is in storage let cap = account.capabilities.storage.issue<&[TestContract.TestResource]>(/storage/test) @@ -2397,7 +2407,7 @@ func TestRuntimeReferenceOwnerAccess(t *testing.T) { transaction { - prepare(account: AuthAccount) { + prepare(account: auth(Storage, Capabilities) &Account) { let nestingResource <- TestContract.makeTestNestingResource() var nestingResourceRef = &nestingResource as &TestContract.TestNestingResource @@ -2407,7 +2417,7 @@ func TestRuntimeReferenceOwnerAccess(t *testing.T) { log(nestingResourceRef.owner?.address) log(nestedElementResourceRef.owner?.address) - account.save(<-nestingResource, to: /storage/test) + account.storage.save(<-nestingResource, to: /storage/test) // At this point the nesting and nested resources are both in storage let cap = account.capabilities.storage.issue<&TestContract.TestNestingResource>(/storage/test) @@ -2527,7 +2537,7 @@ func TestRuntimeReferenceOwnerAccess(t *testing.T) { transaction { - prepare(account: AuthAccount) { + prepare(account: auth(Storage, Capabilities) &Account) { let testResources <- [<-[<-TestContract.makeTestResource()]] var ref = &testResources[0] as &[TestContract.TestResource] @@ -2535,7 +2545,7 @@ func TestRuntimeReferenceOwnerAccess(t *testing.T) { // At this point the resource is not in storage log(ref[0].owner?.address) - account.save(<-testResources, to: /storage/test) + account.storage.save(<-testResources, to: /storage/test) // At this point the resource is in storage let cap = account.capabilities.storage.issue<&[[TestContract.TestResource]]>(/storage/test) @@ -2651,7 +2661,7 @@ func TestRuntimeReferenceOwnerAccess(t *testing.T) { transaction { - prepare(account: AuthAccount) { + prepare(account: auth(Storage, Capabilities) &Account) { let testResources <- [<-{0: <-TestContract.makeTestResource()}] var ref = &testResources[0] as &{Int: TestContract.TestResource} @@ -2659,7 +2669,7 @@ func TestRuntimeReferenceOwnerAccess(t *testing.T) { // At this point the resource is not in storage log(ref[0]?.owner?.address) - account.save(<-testResources, to: /storage/test) + account.storage.save(<-testResources, to: /storage/test) // At this point the resource is in storage let cap = account.capabilities.storage.issue<&[{Int: TestContract.TestResource}]>(/storage/test) @@ -2772,10 +2782,10 @@ func TestRuntimeNoAtreeSendOnClosedChannelDuringCommit(t *testing.T) { const code = ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Storage) &Account) { let refs: [AnyStruct] = [] refs.append(&refs as &AnyStruct) - signer.save(refs, to: /storage/refs) + signer.storage.save(refs, to: /storage/refs) } } ` @@ -2921,9 +2931,9 @@ func TestRuntimeStorageEnumCase(t *testing.T) { import C from 0x1 transaction { - prepare(signer: AuthAccount) { - signer.save(<-C.createEmptyCollection(), to: /storage/collection) - let collection = signer.borrow<&C.Collection>(from: /storage/collection)! + prepare(signer: auth(Storage) &Account) { + signer.storage.save(<-C.createEmptyCollection(), to: /storage/collection) + let collection = signer.storage.borrow<&C.Collection>(from: /storage/collection)! collection.deposit(<-C.createR(id: 0, e: C.E.B)) } } @@ -2944,8 +2954,8 @@ func TestRuntimeStorageEnumCase(t *testing.T) { import C from 0x1 transaction { - prepare(signer: AuthAccount) { - let collection = signer.borrow<&C.Collection>(from: /storage/collection)! + prepare(signer: auth(Storage) &Account) { + let collection = signer.storage.borrow<&C.Collection>(from: /storage/collection)! let r <- collection.withdraw(id: 0) log(r.e) destroy r @@ -2992,7 +3002,7 @@ func TestRuntimeStorageReadNoImplicitWrite(t *testing.T) { Script{ Source: []byte((` transaction { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { let ref = getAccount(0x2).capabilities.borrow<&AnyStruct>(/public/test) assert(ref == nil) } @@ -3086,10 +3096,10 @@ func TestRuntimeStorageInternalAccess(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { - signer.save("Hello, World!", to: /storage/first) - signer.save(["one", "two", "three"], to: /storage/second) - signer.save(<-Test.createR(), to: /storage/r) + prepare(signer: auth(Storage) &Account) { + signer.storage.save("Hello, World!", to: /storage/first) + signer.storage.save(["one", "two", "three"], to: /storage/second) + signer.storage.save(<-Test.createR(), to: /storage/r) } } `), @@ -3224,13 +3234,13 @@ func TestRuntimeStorageIteration(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { - signer.save("Hello, World!", to: /storage/first) - signer.save(["one", "two", "three"], to: /storage/second) - signer.save(Test.Foo(), to: /storage/third) - signer.save(1, to: /storage/fourth) - signer.save(Test.Foo(), to: /storage/fifth) - signer.save("two", to: /storage/sixth) + prepare(signer: auth(Storage) &Account) { + signer.storage.save("Hello, World!", to: /storage/first) + signer.storage.save(["one", "two", "three"], to: /storage/second) + signer.storage.save(Test.Foo(), to: /storage/third) + signer.storage.save(1, to: /storage/fourth) + signer.storage.save(Test.Foo(), to: /storage/fifth) + signer.storage.save("two", to: /storage/sixth) } } `), @@ -3254,10 +3264,10 @@ func TestRuntimeStorageIteration(t *testing.T) { Script{ Source: []byte(` transaction { - prepare(account: AuthAccount) { + prepare(account: auth(Storage) &Account) { var total = 0 - account.forEachStored(fun (path: StoragePath, type: Type): Bool { - account.borrow<&AnyStruct>(from: path)! + account.storage.forEachStored(fun (path: StoragePath, type: Type): Bool { + account.storage.borrow<&AnyStruct>(from: path)! total = total + 1 return true }) @@ -3348,13 +3358,13 @@ func TestRuntimeStorageIteration(t *testing.T) { import Test from 0x1 transaction { - prepare(signer: AuthAccount) { - signer.save("Hello, World!", to: /storage/first) - signer.save(["one", "two", "three"], to: /storage/second) - signer.save(Test.Foo(), to: /storage/third) - signer.save(1, to: /storage/fourth) - signer.save(Test.Foo(), to: /storage/fifth) - signer.save("two", to: /storage/sixth) + prepare(signer: auth(Storage, Capabilities) &Account) { + signer.storage.save("Hello, World!", to: /storage/first) + signer.storage.save(["one", "two", "three"], to: /storage/second) + signer.storage.save(Test.Foo(), to: /storage/third) + signer.storage.save(1, to: /storage/fourth) + signer.storage.save(Test.Foo(), to: /storage/fifth) + signer.storage.save("two", to: /storage/sixth) let capA = signer.capabilities.storage.issue<&String>(/storage/first) signer.capabilities.publish(capA, at: /public/a) @@ -3389,9 +3399,9 @@ func TestRuntimeStorageIteration(t *testing.T) { Script{ Source: []byte(` transaction { - prepare(account: AuthAccount) { + prepare(account: auth(Storage) &Account) { var total = 0 - account.forEachPublic(fun (path: PublicPath, type: Type): Bool { + account.storage.forEachPublic(fun (path: PublicPath, type: Type): Bool { account.capabilities.borrow<&AnyStruct>(path)! total = total + 1 return true @@ -3481,13 +3491,13 @@ func TestRuntimeStorageIteration(t *testing.T) { Source: []byte(` import Test from 0x1 transaction { - prepare(signer: AuthAccount) { - signer.save("Hello, World!", to: /storage/first) - signer.save(["one", "two", "three"], to: /storage/second) - signer.save(Test.Foo(), to: /storage/third) - signer.save(1, to: /storage/fourth) - signer.save(Test.Foo(), to: /storage/fifth) - signer.save("two", to: /storage/sixth) + prepare(signer: auth(Storage, Capabilities) &Account) { + signer.storage.save("Hello, World!", to: /storage/first) + signer.storage.save(["one", "two", "three"], to: /storage/second) + signer.storage.save(Test.Foo(), to: /storage/third) + signer.storage.save(1, to: /storage/fourth) + signer.storage.save(Test.Foo(), to: /storage/fifth) + signer.storage.save("two", to: /storage/sixth) let capA = signer.capabilities.storage.issue<&String>(/storage/first) signer.capabilities.publish(capA, at: /public/a) @@ -3522,9 +3532,9 @@ func TestRuntimeStorageIteration(t *testing.T) { Script{ Source: []byte(` transaction { - prepare(account: AuthAccount) { + prepare(account: &Account) { var total = 0 - account.forEachPublic(fun (path: PublicPath, type: Type): Bool { + account.storage.forEachPublic(fun (path: PublicPath, type: Type): Bool { account.capabilities.borrow<&AnyStruct>(path)! total = total + 1 return true @@ -3613,13 +3623,13 @@ func TestRuntimeStorageIteration(t *testing.T) { Source: []byte(` import Test from 0x1 transaction { - prepare(signer: AuthAccount) { - signer.save("Hello, World!", to: /storage/first) - signer.save(["one", "two", "three"], to: /storage/second) - signer.save(Test.Foo(), to: /storage/third) - signer.save(1, to: /storage/fourth) - signer.save(Test.Foo(), to: /storage/fifth) - signer.save("two", to: /storage/sixth) + prepare(signer: auth(Storage, Capabilities) &Account) { + signer.storage.save("Hello, World!", to: /storage/first) + signer.storage.save(["one", "two", "three"], to: /storage/second) + signer.storage.save(Test.Foo(), to: /storage/third) + signer.storage.save(1, to: /storage/fourth) + signer.storage.save(Test.Foo(), to: /storage/fifth) + signer.storage.save("two", to: /storage/sixth) let capA = signer.capabilities.storage.issue<&String>(/storage/first) signer.capabilities.publish(capA, at: /public/a) @@ -3666,9 +3676,9 @@ func TestRuntimeStorageIteration(t *testing.T) { Script{ Source: []byte(` transaction { - prepare(account: AuthAccount) { + prepare(account: &Account) { var total = 0 - account.forEachPublic(fun (path: PublicPath, type: Type): Bool { + account.storage.forEachPublic(fun (path: PublicPath, type: Type): Bool { account.capabilities.borrow<&AnyStruct>(path)! total = total + 1 return true @@ -3790,11 +3800,11 @@ func TestRuntimeStorageIteration(t *testing.T) { import Foo from 0x1 transaction { - prepare(signer: AuthAccount) { - signer.save("Hello, World!", to: /storage/first) + prepare(signer: auth(Storage, Capabilities) &Account) { + signer.storage.save("Hello, World!", to: /storage/first) var structArray: [{Foo.Collection}] = [Bar.CollectionImpl()] - signer.save(structArray, to: /storage/second) + signer.storage.save(structArray, to: /storage/second) let capA = signer.capabilities.storage.issue<&String>(/storage/first) signer.capabilities.publish(capA, at: /public/a) @@ -3825,11 +3835,11 @@ func TestRuntimeStorageIteration(t *testing.T) { import Foo from 0x1 transaction { - prepare(account: AuthAccount) { + prepare(account: &Account) { var total = 0 var capTaken = false - account.forEachPublic(fun (path: PublicPath, type: Type): Bool { + account.storage.forEachPublic(fun (path: PublicPath, type: Type): Bool { total = total + 1 if var cap = account.capabilities.get<&[{Foo.Collection}]>(path) { cap.check() @@ -3861,11 +3871,11 @@ func TestRuntimeStorageIteration(t *testing.T) { import Foo from 0x1 transaction { - prepare(account: AuthAccount) { + prepare(account: &Account) { var total = 0 - account.forEachStored(fun (path: StoragePath, type: Type): Bool { - account.check<[{Foo.Collection}]>(from: path) + account.storage.forEachStored(fun (path: StoragePath, type: Type): Bool { + account.storage.check<[{Foo.Collection}]>(from: path) total = total + 1 return true }) @@ -3988,9 +3998,9 @@ func TestRuntimeStorageIteration(t *testing.T) { import Foo from 0x1 transaction { - prepare(signer: AuthAccount) { - signer.save("Hello, World!", to: /storage/first) - signer.save(<- Bar.getCollection(), to: /storage/second) + prepare(signer: auth(Storage, Capabilities) &Account) { + signer.storage.save("Hello, World!", to: /storage/first) + signer.storage.save(<- Bar.getCollection(), to: /storage/second) let capA = signer.capabilities.storage.issue<&String>(/storage/first) signer.capabilities.publish(capA, at: /public/a) @@ -4021,11 +4031,11 @@ func TestRuntimeStorageIteration(t *testing.T) { import Foo from 0x1 transaction { - prepare(account: AuthAccount) { + prepare(account: &Account) { var total = 0 var capTaken = false - account.forEachPublic(fun (path: PublicPath, type: Type): Bool { + account.storage.forEachPublic(fun (path: PublicPath, type: Type): Bool { total = total + 1 if var cap = account.capabilities.get<&{Foo.Collection}>(path) { @@ -4061,12 +4071,12 @@ func TestRuntimeStorageIteration(t *testing.T) { import Foo from 0x1 transaction { - prepare(account: AuthAccount) { + prepare(account: &Account) { var total = 0 var capTaken = false - account.forEachStored(fun (path: StoragePath, type: Type): Bool { - account.check<@{Foo.Collection}>(from: path) + account.storage.forEachStored(fun (path: StoragePath, type: Type): Bool { + account.storage.check<@{Foo.Collection}>(from: path) total = total + 1 return true }) @@ -4100,22 +4110,22 @@ func TestRuntimeStorageIteration(t *testing.T) { contractIsBroken := false deployFoo := DeploymentTransaction("Foo", []byte(` - access(all) contract Foo { - access(all) resource interface Collection {} - } - `)) + access(all) contract Foo { + access(all) resource interface Collection {} + } + `)) deployBar := DeploymentTransaction("Bar", []byte(` - import Foo from 0x1 + import Foo from 0x1 - access(all) contract Bar { - access(all) resource CollectionImpl: Foo.Collection {} + access(all) contract Bar { + access(all) resource CollectionImpl: Foo.Collection {} - access(all) fun getCollection(): @Bar.CollectionImpl { - return <- create Bar.CollectionImpl() - } - } - `)) + access(all) fun getCollection(): @Bar.CollectionImpl { + return <- create Bar.CollectionImpl() + } + } + `)) newRuntimeInterface := func() Interface { return &testRuntimeInterface{ @@ -4132,17 +4142,18 @@ func TestRuntimeStorageIteration(t *testing.T) { if contractIsBroken && location.Name == "Bar" { // Contract has a semantic error. i.e: Mismatched types at `bar` function return []byte(` - import Foo from 0x1 - - access(all) contract Bar { - access(all) resource CollectionImpl: Foo.Collection { - access(all) var mismatch: Int - - init() { - self.mismatch = "hello" - } - } - }`), nil + import Foo from 0x1 + + access(all) contract Bar { + access(all) resource CollectionImpl: Foo.Collection { + access(all) var mismatch: Int + + init() { + self.mismatch = "hello" + } + } + } + `), nil } code = accountCodes[location] @@ -4189,22 +4200,22 @@ func TestRuntimeStorageIteration(t *testing.T) { err = runtime.ExecuteTransaction( Script{ Source: []byte(` - import Bar from 0x1 - import Foo from 0x1 + import Bar from 0x1 + import Foo from 0x1 - transaction { - prepare(signer: AuthAccount) { - signer.save("Hello, World!", to: /storage/first) - signer.save(<- Bar.getCollection(), to: /storage/second) + transaction { + prepare(signer: auth(Storage, Capabilities) &Account) { + signer.storage.save("Hello, World!", to: /storage/first) + signer.storage.save(<- Bar.getCollection(), to: /storage/second) - let capA = signer.capabilities.storage.issue<&String>(/storage/first) - signer.capabilities.publish(capA, at: /public/a) + let capA = signer.capabilities.storage.issue<&String>(/storage/first) + signer.capabilities.publish(capA, at: /public/a) - let capB = signer.capabilities.storage.issue<&String>(/storage/second) - signer.capabilities.publish(capB, at: /public/b) - } - } - `), + let capB = signer.capabilities.storage.issue<&String>(/storage/second) + signer.capabilities.publish(capB, at: /public/b) + } + } + `), }, Context{ Interface: runtimeInterface, @@ -4230,23 +4241,23 @@ func TestRuntimeStorageIteration(t *testing.T) { err = runtime.ExecuteTransaction( Script{ Source: []byte(fmt.Sprintf(` - import Foo from 0x1 - - transaction { - prepare(account: AuthAccount) { - var total = 0 - account.forEachPublic(fun (path: PublicPath, type: Type): Bool { - var cap = account.capabilities.get<&String>(path)! - cap.check() - total = total + 1 - return true - }) - - // The broken value must be skipped. - assert(total == %d) - } - } - `, + import Foo from 0x1 + + transaction { + prepare(account: &Account) { + var total = 0 + account.storage.forEachPublic(fun (path: PublicPath, type: Type): Bool { + var cap = account.capabilities.get<&String>(path)! + cap.check() + total = total + 1 + return true + }) + + // The broken value must be skipped. + assert(total == %d) + } + } + `, count, )), }, @@ -4308,17 +4319,17 @@ func TestRuntimeStorageIteration2(t *testing.T) { contract Test { access(all) fun saveStorage() { - self.account.save(0, to:/storage/foo) + self.account.storage.save(0, to:/storage/foo) } access(all) fun saveOtherStorage() { - self.account.save(0, to:/storage/bar) + self.account.storage.save(0, to:/storage/bar) } access(all) fun loadStorage() { - self.account.load(from:/storage/foo) + self.account.storage.load(from:/storage/foo) } access(all) @@ -4333,13 +4344,13 @@ func TestRuntimeStorageIteration2(t *testing.T) { } access(all) - fun getStoragePaths(): [StoragePath] { - return self.account.storagePaths + fun getStoragePaths(): &[StoragePath] { + return self.account.storage.storagePaths } access(all) - fun getPublicPaths(): [PublicPath] { - return getAccount(self.account.address).publicPaths + fun getPublicPaths(): &[PublicPath] { + return getAccount(self.account.address).storage.publicPaths } } ` @@ -4504,11 +4515,11 @@ func TestRuntimeStorageIteration2(t *testing.T) { access(all) fun main(): Int { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) let pubAccount = getAccount(0x1) - account.save(S(value: 2), to: /storage/foo) - account.save("", to: /storage/bar) + account.storage.save(S(value: 2), to: /storage/foo) + account.storage.save("", to: /storage/bar) let capA = account.capabilities.storage.issue<&S>(/storage/foo) account.capabilities.publish(capA, at: /public/a) let capB = account.capabilities.storage.issue<&String>(/storage/bar) @@ -4521,7 +4532,7 @@ func TestRuntimeStorageIteration2(t *testing.T) { account.capabilities.publish(capE, at: /public/e) var total = 0 - pubAccount.forEachPublic(fun (path: PublicPath, type: Type): Bool { + pubAccount.storage.forEachPublic(fun (path: PublicPath, type: Type): Bool { if type == Type>() { total = total + pubAccount.capabilities.borrow<&S>(path)!.value } @@ -4567,11 +4578,11 @@ func TestRuntimeStorageIteration2(t *testing.T) { access(all) fun main(): Int { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) let pubAccount = getAccount(0x1) - account.save(S(value: 2), to: /storage/foo) - account.save("", to: /storage/bar) + account.storage.save(S(value: 2), to: /storage/foo) + account.storage.save("", to: /storage/bar) let capA = account.capabilities.storage.issue<&S>(/storage/foo) account.capabilities.publish(capA, at: /public/a) let capB = account.capabilities.storage.issue<&String>(/storage/bar) @@ -4584,7 +4595,7 @@ func TestRuntimeStorageIteration2(t *testing.T) { account.capabilities.publish(capE, at: /public/e) var total = 0 - pubAccount.forEachPublic(fun (path: PublicPath, type: Type): Bool { + pubAccount.storage.forEachPublic(fun (path: PublicPath, type: Type): Bool { total = total + 1 return true }) @@ -4627,11 +4638,11 @@ func TestRuntimeStorageIteration2(t *testing.T) { access(all) fun main(): Int { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) let pubAccount = getAccount(0x1) - account.save(S(value: 2), to: /storage/foo) - account.save("", to: /storage/bar) + account.storage.save(S(value: 2), to: /storage/foo) + account.storage.save("", to: /storage/bar) let capA = account.capabilities.storage.issue<&S>(/storage/foo) account.capabilities.publish(capA, at: /public/a) let capB = account.capabilities.storage.issue<&String>(/storage/bar) @@ -4644,7 +4655,7 @@ func TestRuntimeStorageIteration2(t *testing.T) { account.capabilities.publish(capE, at: /public/e) var total = 0 - account.forEachPublic(fun (path: PublicPath, type: Type): Bool { + account.storage.forEachPublic(fun (path: PublicPath, type: Type): Bool { if type == Type>() { total = total + account.capabilities.borrow<&S>(path)!.value } @@ -4673,59 +4684,6 @@ func TestRuntimeStorageIteration2(t *testing.T) { ) }) - t.Run("forEachPrivate", func(t *testing.T) { - - runtime, runtimeInterface := newRuntime() - - const script = ` - access(all) - struct S { - access(all) - let value: Int - - init(value: Int) { - self.value = value - } - } - - access(all) - fun main(): Int { - let account = getAuthAccount(0x1) - let pubAccount = getAccount(0x1) - - account.save(S(value: 2), to: /storage/foo) - account.save("test", to: /storage/bar) - let capA = account.capabilities.storage.issue<&S>(/storage/foo) - account.capabilities.publish(capA, at: /public/a) - - var total = 0 - account.forEachPrivate(fun (path: PrivatePath, type: Type): Bool { - total = total + 1 - return true - }) - - return total - } - ` - - result, err := runtime.ExecuteScript( - Script{ - Source: []byte(script), - }, - Context{ - Interface: runtimeInterface, - Location: common.ScriptLocation{}, - }, - ) - require.NoError(t, err) - - assert.Equal( - t, - cadence.NewInt(0), - result, - ) - }) - t.Run("forEachStored", func(t *testing.T) { runtime, runtimeInterface := newRuntime() @@ -4742,18 +4700,18 @@ func TestRuntimeStorageIteration2(t *testing.T) { access(all) fun main(): Int { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) - account.save(S(value: 1), to: /storage/foo1) - account.save(S(value: 2), to: /storage/foo2) - account.save(S(value: 5), to: /storage/foo3) - account.save("", to: /storage/bar1) - account.save(4, to: /storage/bar2) + account.storage.save(S(value: 1), to: /storage/foo1) + account.storage.save(S(value: 2), to: /storage/foo2) + account.storage.save(S(value: 5), to: /storage/foo3) + account.storage.save("", to: /storage/bar1) + account.storage.save(4, to: /storage/bar2) var total = 0 - account.forEachStored(fun (path: StoragePath, type: Type): Bool { + account.storage.forEachStored(fun (path: StoragePath, type: Type): Bool { if type == Type() { - total = total + account.borrow<&S>(from: path)!.value + total = total + account.storage.borrow<&S>(from: path)!.value } return true }) @@ -4796,17 +4754,17 @@ func TestRuntimeStorageIteration2(t *testing.T) { access(all) fun main(): Int { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) var total = 0 - account.forEachStored(fun (path: StoragePath, type: Type): Bool { + account.storage.forEachStored(fun (path: StoragePath, type: Type): Bool { total = total + 1 return true }) - account.save(S(value: 1), to: /storage/foo1) - account.save(S(value: 2), to: /storage/foo2) - account.save(S(value: 5), to: /storage/foo3) + account.storage.save(S(value: 1), to: /storage/foo1) + account.storage.save(S(value: 2), to: /storage/foo2) + account.storage.save(S(value: 5), to: /storage/foo3) return total } @@ -4834,10 +4792,10 @@ func TestRuntimeStorageIteration2(t *testing.T) { const script2 = ` access(all) fun main(): Int { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) var total = 0 - account.forEachStored(fun (path: StoragePath, type: Type): Bool { + account.storage.forEachStored(fun (path: StoragePath, type: Type): Bool { total = total + 1 return true }) @@ -4884,24 +4842,24 @@ func TestRuntimeStorageIteration2(t *testing.T) { access(all) fun main(): Int { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) - account.save(S(value: 1), to: /storage/foo1) - account.save(S(value: 2), to: /storage/foo2) - account.save(S(value: 5), to: /storage/foo3) - account.save("", to: /storage/bar1) - account.save(4, to: /storage/bar2) + account.storage.save(S(value: 1), to: /storage/foo1) + account.storage.save(S(value: 2), to: /storage/foo2) + account.storage.save(S(value: 5), to: /storage/foo3) + account.storage.save("", to: /storage/bar1) + account.storage.save(4, to: /storage/bar2) var total = 0 - account.forEachStored(fun (path: StoragePath, type: Type): Bool { + account.storage.forEachStored(fun (path: StoragePath, type: Type): Bool { if type == Type() { - account.borrow<&S>(from: path)!.increment() + account.storage.borrow<&S>(from: path)!.increment() } return true }) - account.forEachStored(fun (path: StoragePath, type: Type): Bool { + account.storage.forEachStored(fun (path: StoragePath, type: Type): Bool { if type == Type() { - total = total + account.borrow<&S>(from: path)!.value + total = total + account.storage.borrow<&S>(from: path)!.value } return true }) @@ -4949,22 +4907,22 @@ func TestRuntimeStorageIteration2(t *testing.T) { access(all) fun main(): Int { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) - account.save(S(value: 1), to: /storage/foo1) - account.save(S(value: 2), to: /storage/foo2) - account.save(S(value: 5), to: /storage/foo3) - account.save("qux", to: /storage/bar1) - account.save(4, to: /storage/bar2) + account.storage.save(S(value: 1), to: /storage/foo1) + account.storage.save(S(value: 2), to: /storage/foo2) + account.storage.save(S(value: 5), to: /storage/foo3) + account.storage.save("qux", to: /storage/bar1) + account.storage.save(4, to: /storage/bar2) var total = 0 - account.forEachStored(fun (path: StoragePath, type: Type): Bool { + account.storage.forEachStored(fun (path: StoragePath, type: Type): Bool { if type == Type() { - total = total + account.borrow<&S>(from: path)!.value + total = total + account.storage.borrow<&S>(from: path)!.value } if type == Type() { - let id = account.load(from: path)! - account.save(S(value:3), to: StoragePath(identifier: id)!) + let id = account.storage.load(from: path)! + account.storage.save(S(value:3), to: StoragePath(identifier: id)!) } return true }) @@ -5008,21 +4966,21 @@ func TestRuntimeStorageIteration2(t *testing.T) { access(all) fun main(): Int { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) - account.save(1, to: /storage/foo1) - account.save(2, to: /storage/foo2) - account.save(3, to: /storage/foo3) - account.save(4, to: /storage/bar1) - account.save(5, to: /storage/bar2) + account.storage.save(1, to: /storage/foo1) + account.storage.save(2, to: /storage/foo2) + account.storage.save(3, to: /storage/foo3) + account.storage.save(4, to: /storage/bar1) + account.storage.save(5, to: /storage/bar2) var seen = 0 var stuff: [&AnyStruct] = [] - account.forEachStored(fun (path: StoragePath, type: Type): Bool { + account.storage.forEachStored(fun (path: StoragePath, type: Type): Bool { if seen >= 3 { return false } - stuff.append(account.borrow<&AnyStruct>(from: path)!) + stuff.append(account.storage.borrow<&AnyStruct>(from: path)!) seen = seen + 1 return true }) @@ -5092,16 +5050,16 @@ func TestRuntimeAccountIterationMutation(t *testing.T) { ` access(all) fun main() { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) - account.save(1, to: /storage/foo1) - account.save(2, to: /storage/foo2) - account.save(3, to: /storage/foo3) - account.save("qux", to: /storage/foo4) + account.storage.save(1, to: /storage/foo1) + account.storage.save(2, to: /storage/foo2) + account.storage.save(3, to: /storage/foo3) + account.storage.save("qux", to: /storage/foo4) - account.forEachStored(fun (path: StoragePath, type: Type): Bool { + account.storage.forEachStored(fun (path: StoragePath, type: Type): Bool { if type == Type() { - account.save("bar", to: /storage/foo5) + account.storage.save("bar", to: /storage/foo5) return %t } return true @@ -5139,18 +5097,21 @@ func TestRuntimeAccountIterationMutation(t *testing.T) { ` access(all) fun main() { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) + + account.storage.save(1, to: /storage/foo1) - account.save(1, to: /storage/foo1) - account.save("", to: /storage/foo2) let capA = account.capabilities.storage.issue<&Int>(/storage/foo1) account.capabilities.publish(capA, at: /public/foo1) + + account.storage.save("", to: /storage/foo2) + let capB = account.capabilities.storage.issue<&String>(/storage/foo2) account.capabilities.publish(capB, at: /public/foo2) - account.forEachPublic(fun (path: PublicPath, type: Type): Bool { + account.storage.forEachPublic(fun (path: PublicPath, type: Type): Bool { if type == Type>() { - account.save("bar", to: /storage/foo3) + account.storage.save("bar", to: /storage/foo3) return %t } return true @@ -5188,21 +5149,21 @@ func TestRuntimeAccountIterationMutation(t *testing.T) { ` access(all) fun foo() { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) - account.save("bar", to: /storage/foo5) + account.storage.save("bar", to: /storage/foo5) } access(all) fun main() { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) - account.save(1, to: /storage/foo1) - account.save(2, to: /storage/foo2) - account.save(3, to: /storage/foo3) - account.save("qux", to: /storage/foo4) + account.storage.save(1, to: /storage/foo1) + account.storage.save(2, to: /storage/foo2) + account.storage.save(3, to: /storage/foo3) + account.storage.save("qux", to: /storage/foo4) - account.forEachStored(fun (path: StoragePath, type: Type): Bool { + account.storage.forEachStored(fun (path: StoragePath, type: Type): Bool { if type == Type() { foo() return %t @@ -5242,24 +5203,24 @@ func TestRuntimeAccountIterationMutation(t *testing.T) { ` access(all) fun foo() { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) - account.forEachStored(fun (path: StoragePath, type: Type): Bool { + account.storage.forEachStored(fun (path: StoragePath, type: Type): Bool { return true }) - account.save("bar", to: /storage/foo5) + account.storage.save("bar", to: /storage/foo5) } access(all) fun main() { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) - account.save(1, to: /storage/foo1) - account.save(2, to: /storage/foo2) - account.save(3, to: /storage/foo3) - account.save("qux", to: /storage/foo4) + account.storage.save(1, to: /storage/foo1) + account.storage.save(2, to: /storage/foo2) + account.storage.save(3, to: /storage/foo3) + account.storage.save("qux", to: /storage/foo4) - account.forEachStored(fun (path: StoragePath, type: Type): Bool { + account.storage.forEachStored(fun (path: StoragePath, type: Type): Bool { if type == Type() { foo() return %t @@ -5299,16 +5260,16 @@ func TestRuntimeAccountIterationMutation(t *testing.T) { ` access(all) fun main() { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) - account.save(1, to: /storage/foo1) - account.save(2, to: /storage/foo2) - account.save(3, to: /storage/foo3) - account.save("qux", to: /storage/foo4) + account.storage.save(1, to: /storage/foo1) + account.storage.save(2, to: /storage/foo2) + account.storage.save(3, to: /storage/foo3) + account.storage.save("qux", to: /storage/foo4) - account.forEachStored(fun (path: StoragePath, type: Type): Bool { + account.storage.forEachStored(fun (path: StoragePath, type: Type): Bool { if type == Type() { - account.load(from: /storage/foo1) + account.storage.load(from: /storage/foo1) return %t } return true @@ -5345,16 +5306,16 @@ func TestRuntimeAccountIterationMutation(t *testing.T) { ` access(all) fun main() { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) - account.save(1, to: /storage/foo1) - account.save("", to: /storage/foo2) + account.storage.save(1, to: /storage/foo1) + account.storage.save("", to: /storage/foo2) let capA = account.capabilities.storage.issue<&Int>(/storage/foo1) account.capabilities.publish(capA, at: /public/foo1) let capB = account.capabilities.storage.issue<&String>(/storage/foo2) account.capabilities.publish(capB, at: /public/foo2) - account.forEachPublic(fun (path: PublicPath, type: Type): Bool { + account.storage.forEachPublic(fun (path: PublicPath, type: Type): Bool { if type == Type>() { account.capabilities.storage.issue<&Int>(/storage/foo1) return %t @@ -5393,16 +5354,16 @@ func TestRuntimeAccountIterationMutation(t *testing.T) { ` access(all) fun main() { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) - account.save(1, to: /storage/foo1) - account.save("", to: /storage/foo2) + account.storage.save(1, to: /storage/foo1) + account.storage.save("", to: /storage/foo2) let capA = account.capabilities.storage.issue<&Int>(/storage/foo1) account.capabilities.publish(capA, at: /public/foo1) let capB = account.capabilities.storage.issue<&String>(/storage/foo2) account.capabilities.publish(capB, at: /public/foo2) - account.forEachPublic(fun (path: PublicPath, type: Type): Bool { + account.storage.forEachPublic(fun (path: PublicPath, type: Type): Bool { if type == Type>() { account.capabilities.unpublish(/public/foo1) return %t @@ -5445,7 +5406,7 @@ func TestRuntimeAccountIterationMutation(t *testing.T) { access(all) fun foo() { - self.account.save("bar", to: /storage/foo5) + self.account.storage.save("bar", to: /storage/foo5) } } ` @@ -5470,14 +5431,14 @@ func TestRuntimeAccountIterationMutation(t *testing.T) { access(all) fun main() { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) - account.save(1, to: /storage/foo1) - account.save(2, to: /storage/foo2) - account.save(3, to: /storage/foo3) - account.save("qux", to: /storage/foo4) + account.storage.save(1, to: /storage/foo1) + account.storage.save(2, to: /storage/foo2) + account.storage.save(3, to: /storage/foo3) + account.storage.save("qux", to: /storage/foo4) - account.forEachStored(fun (path: StoragePath, type: Type): Bool { + account.storage.forEachStored(fun (path: StoragePath, type: Type): Bool { if type == Type() { Test.foo() return %t @@ -5519,25 +5480,25 @@ func TestRuntimeAccountIterationMutation(t *testing.T) { const script = ` access(all) fun main() { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) - account.save(1, to: /storage/foo1) - account.save(2, to: /storage/foo2) - account.save(3, to: /storage/foo3) - account.save("qux", to: /storage/foo4) + account.storage.save(1, to: /storage/foo1) + account.storage.save(2, to: /storage/foo2) + account.storage.save(3, to: /storage/foo3) + account.storage.save("qux", to: /storage/foo4) - account.forEachStored(fun (path: StoragePath, type: Type): Bool { + account.storage.forEachStored(fun (path: StoragePath, type: Type): Bool { return true }) - account.save("bar", to: /storage/foo5) + account.storage.save("bar", to: /storage/foo5) - account.forEachStored(fun (path: StoragePath, type: Type): Bool { - account.forEachStored(fun (path: StoragePath, type: Type): Bool { + account.storage.forEachStored(fun (path: StoragePath, type: Type): Bool { + account.storage.forEachStored(fun (path: StoragePath, type: Type): Bool { return true }) return true }) - account.save("baz", to: /storage/foo6) + account.storage.save("baz", to: /storage/foo6) } ` @@ -5566,9 +5527,9 @@ func TestRuntimeAccountIterationMutation(t *testing.T) { access(all) fun main() { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) - account.forEachStored(foo) + account.storage.forEachStored(foo) } ` @@ -5602,9 +5563,9 @@ func TestRuntimeAccountIterationMutation(t *testing.T) { access(all) fun main() { - let account = getAuthAccount(0x1) + let account = getAuthAccount(0x1) let s = S() - account.forEachStored(s.foo) + account.storage.forEachStored(s.foo) } ` diff --git a/runtime/tests/checker/account_test.go b/runtime/tests/checker/account_test.go index 6d42772bef..d87ec8cb42 100644 --- a/runtime/tests/checker/account_test.go +++ b/runtime/tests/checker/account_test.go @@ -27,45 +27,26 @@ import ( "github.com/onflow/cadence/runtime/common" "github.com/onflow/cadence/runtime/sema" - "github.com/onflow/cadence/runtime/stdlib" "github.com/onflow/cadence/runtime/tests/utils" ) -func ParseAndCheckAccountWithConfig(t *testing.T, code string, config sema.Config) (*sema.Checker, error) { +func TestCheckAccountStorageSave(t *testing.T) { - constantDeclaration := func(name string, ty sema.Type) stdlib.StandardLibraryValue { - return stdlib.StandardLibraryValue{ - Name: name, - Type: ty, - Kind: common.DeclarationKindConstant, - } - } - - baseValueActivation := config.BaseValueActivation - if baseValueActivation == nil { - baseValueActivation = sema.BaseValueActivation - } + t.Parallel() - baseValueActivation = sema.NewVariableActivation(baseValueActivation) - baseValueActivation.DeclareValue(constantDeclaration("authAccount", sema.AuthAccountType)) - baseValueActivation.DeclareValue(constantDeclaration("publicAccount", sema.PublicAccountType)) - config.BaseValueActivation = baseValueActivation - - return ParseAndCheckWithOptions(t, - code, - ParseAndCheckOptions{ - Config: &config, - }, - ) -} + t.Run("unauthorized", func(t *testing.T) { + t.Parallel() -func ParseAndCheckAccount(t *testing.T, code string) (*sema.Checker, error) { - return ParseAndCheckAccountWithConfig(t, code, sema.Config{}) -} + _, err := ParseAndCheck(t, ` + fun test(storage: &Account.Storage) { + storage.save(1, to: /storage/foo) + } + `) -func TestCheckAccount_save(t *testing.T) { + errs := RequireCheckerErrors(t, err, 1) - t.Parallel() + require.IsType(t, &sema.InvalidAccessError{}, errs[0]) + }) testImplicitTypeArgument := func(domain common.PathDomain) { @@ -84,14 +65,14 @@ func TestCheckAccount_save(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, fmt.Sprintf( ` resource R {} - fun test() { + fun test(storage: auth(Storage) &Account.Storage) { let r <- create R() - authAccount.save(<-r, to: /%s/r) + storage.save(<-r, to: /%s/r) } `, domainIdentifier, @@ -111,14 +92,14 @@ func TestCheckAccount_save(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, fmt.Sprintf( ` struct S {} - fun test() { + fun test(storage: auth(Storage) &Account.Storage) { let s = S() - authAccount.save(s, to: /%s/s) + storage.save(s, to: /%s/s) } `, domainIdentifier, @@ -152,14 +133,14 @@ func TestCheckAccount_save(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, fmt.Sprintf( ` resource R {} - fun test() { + fun test(storage: auth(Storage) &Account.Storage) { let r <- create R() - authAccount.save<@R>(<-r, to: /%s/r) + storage.save<@R>(<-r, to: /%s/r) } `, domainIdentifier, @@ -179,14 +160,14 @@ func TestCheckAccount_save(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, fmt.Sprintf( ` struct S {} - fun test() { + fun test(storage: auth(Storage) &Account.Storage) { let s = S() - authAccount.save(s, to: /%s/s) + storage.save(s, to: /%s/s) } `, domainIdentifier, @@ -220,16 +201,16 @@ func TestCheckAccount_save(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, fmt.Sprintf( ` resource R {} resource T {} - fun test() { + fun test(storage: auth(Storage) &Account.Storage) { let r <- create R() - authAccount.save<@T>(<-r, to: /%s/r) + storage.save<@T>(<-r, to: /%s/r) } `, domainIdentifier, @@ -255,16 +236,16 @@ func TestCheckAccount_save(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, fmt.Sprintf( ` struct S {} struct T {} - fun test() { + fun test(storage: auth(Storage) &Account.Storage) { let s = S() - authAccount.save(s, to: /%s/s) + storage.save(s, to: /%s/s) } `, domainIdentifier, @@ -304,15 +285,15 @@ func TestCheckAccount_save(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, fmt.Sprintf( ` fun one(): Int { return 1 } - fun test() { - authAccount.save(one, to: /%s/one) + fun test(storage: auth(Storage) &Account.Storage) { + storage.save(one, to: /%s/one) } `, domainIdentifier, @@ -335,15 +316,15 @@ func TestCheckAccount_save(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, fmt.Sprintf( ` fun one(): Int { return 1 } - fun test() { - authAccount.save(one, to: /%s/one) + fun test(storage: auth(Storage) &Account.Storage) { + storage.save(one, to: /%s/one) } `, domainIdentifier, @@ -371,7 +352,7 @@ func TestCheckAccount_save(t *testing.T) { } } -func TestCheckAccount_typeAt(t *testing.T) { +func TestCheckAccountStorageType(t *testing.T) { t.Parallel() @@ -380,23 +361,19 @@ func TestCheckAccount_typeAt(t *testing.T) { t.Parallel() - checker, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, fmt.Sprintf( ` - let t: Type = authAccount.type(at: /%s/r)! - `, + fun test(storage: &Account.Storage) { + let t: Type = storage.type(at: /%s/r)! + } + `, domain.Identifier(), ), ) if domain == common.PathDomainStorage { - require.NoError(t, err) - - typ := RequireGlobalValue(t, checker.Elaboration, "t") - - require.Equal(t, sema.MetaType, typ) - } else { errs := RequireCheckerErrors(t, err, 1) @@ -410,10 +387,24 @@ func TestCheckAccount_typeAt(t *testing.T) { } } -func TestCheckAccount_load(t *testing.T) { +func TestCheckAccountStorageLoad(t *testing.T) { t.Parallel() + t.Run("unauthorized", func(t *testing.T) { + t.Parallel() + + _, err := ParseAndCheck(t, ` + fun test(storage: &Account.Storage) { + storage.load(from: /storage/foo) + } + `) + + errs := RequireCheckerErrors(t, err, 1) + + require.IsType(t, &sema.InvalidAccessError{}, errs[0]) + }) + testMissingTypeArguments := func(domain common.PathDomain) { testName := fmt.Sprintf( @@ -425,10 +416,12 @@ func TestCheckAccount_load(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, fmt.Sprintf( ` - let s = authAccount.load(from: /%s/s) + fun test(storage: auth(Storage) &Account.Storage) { + let s = storage.load(from: /%s/s) + } `, domain.Identifier(), ), @@ -463,31 +456,22 @@ func TestCheckAccount_load(t *testing.T) { t.Parallel() - checker, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, fmt.Sprintf( ` resource R {} - let r <- authAccount.load<@R>(from: /%s/r) + fun test(storage: auth(Storage) &Account.Storage) { + let r: @R? <- storage.load<@R>(from: /%s/r) + destroy r + } `, domain.Identifier(), ), ) if domain == common.PathDomainStorage { - require.NoError(t, err) - - rType := RequireGlobalType(t, checker.Elaboration, "R") - rValueType := RequireGlobalValue(t, checker.Elaboration, "r") - - require.Equal(t, - &sema.OptionalType{ - Type: rType, - }, - rValueType, - ) - } else { errs := RequireCheckerErrors(t, err, 1) @@ -499,30 +483,21 @@ func TestCheckAccount_load(t *testing.T) { t.Parallel() - checker, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, fmt.Sprintf( ` struct S {} - let s = authAccount.load(from: /%s/s) + fun test(storage: auth(Storage) &Account.Storage) { + let s: S? = storage.load(from: /%s/s) + } `, domain.Identifier(), ), ) if domain == common.PathDomainStorage { - require.NoError(t, err) - - sType := RequireGlobalType(t, checker.Elaboration, "S") - sValueType := RequireGlobalValue(t, checker.Elaboration, "s") - - require.Equal(t, - &sema.OptionalType{ - Type: sType, - }, - sValueType, - ) } else { errs := RequireCheckerErrors(t, err, 1) @@ -538,7 +513,7 @@ func TestCheckAccount_load(t *testing.T) { } } -func TestCheckAccount_copy(t *testing.T) { +func TestCheckAccountStorageCopy(t *testing.T) { t.Parallel() @@ -553,12 +528,14 @@ func TestCheckAccount_copy(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, fmt.Sprintf( ` struct S {} - let s = authAccount.copy(from: /%s/s) + fun test(storage: &Account.Storage) { + let s = storage.copy(from: /%s/s) + } `, domain.Identifier(), ), @@ -593,12 +570,14 @@ func TestCheckAccount_copy(t *testing.T) { t.Parallel() - checker, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, fmt.Sprintf( ` struct S {} - let s = authAccount.copy(from: /%s/s) + fun test(storage: &Account.Storage) { + let s = storage.copy(from: /%s/s) + } `, domain.Identifier(), ), @@ -606,17 +585,6 @@ func TestCheckAccount_copy(t *testing.T) { if domain == common.PathDomainStorage { require.NoError(t, err) - - sType := RequireGlobalType(t, checker.Elaboration, "S") - sValueType := RequireGlobalValue(t, checker.Elaboration, "s") - - require.Equal(t, - &sema.OptionalType{ - Type: sType, - }, - sValueType, - ) - } else { errs := RequireCheckerErrors(t, err, 1) @@ -628,12 +596,15 @@ func TestCheckAccount_copy(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, fmt.Sprintf( ` resource R {} - let r <- authAccount.copy<@R>(from: /%s/r) + fun test(storage: &Account.Storage) { + let r <- storage.copy<@R>(from: /%s/r) + destroy r + } `, domain.Identifier(), ), @@ -660,10 +631,24 @@ func TestCheckAccount_copy(t *testing.T) { } } -func TestCheckAccount_borrow(t *testing.T) { +func TestCheckAccountStorageBorrow(t *testing.T) { t.Parallel() + t.Run("unauthorized", func(t *testing.T) { + + t.Parallel() + + _, err := ParseAndCheck(t, ` + fun test(storage: &Account.Storage) { + let r = storage.borrow<&Int>(from: /storage/foo) + } + `) + errs := RequireCheckerErrors(t, err, 1) + + require.IsType(t, &sema.InvalidAccessError{}, errs[0]) + }) + testMissingTypeArgument := func(domain common.PathDomain) { testName := fmt.Sprintf( @@ -679,10 +664,12 @@ func TestCheckAccount_borrow(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, fmt.Sprintf( ` - let r = authAccount.borrow(from: /%s/r) + fun test(storage: auth(Storage) &Account.Storage) { + let r = storage.borrow(from: /%s/r) + } `, domain.Identifier(), ), @@ -705,10 +692,12 @@ func TestCheckAccount_borrow(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, fmt.Sprintf( ` - let s = authAccount.borrow(from: /%s/s) + fun test(storage: auth(Storage) &Account.Storage) { + let s = storage.borrow(from: /%s/s) + } `, domain.Identifier(), ), @@ -747,13 +736,16 @@ func TestCheckAccount_borrow(t *testing.T) { t.Parallel() - checker, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, fmt.Sprintf( ` resource R {} - entitlement X - let r = authAccount.borrow<%s &R>(from: /%s/r) + entitlement X + + fun test(storage: auth(Storage) &Account.Storage) { + let r: %[1]s &R? = storage.borrow<%[1]s &R>(from: /%[2]s/r) + } `, authKeyword, domain.Identifier(), @@ -761,29 +753,7 @@ func TestCheckAccount_borrow(t *testing.T) { ) if domain == common.PathDomainStorage { - require.NoError(t, err) - - rType := RequireGlobalType(t, checker.Elaboration, "R") - rValueType := RequireGlobalValue(t, checker.Elaboration, "r") - - xType := RequireGlobalType(t, checker.Elaboration, "X") - require.IsType(t, &sema.EntitlementType{}, xType) - xEntitlement := xType.(*sema.EntitlementType) - var access sema.Access = sema.UnauthorizedAccess - if !auth.Equal(sema.UnauthorizedAccess) { - access = sema.NewEntitlementSetAccess([]*sema.EntitlementType{xEntitlement}, sema.Conjunction) - } - - require.Equal(t, - &sema.OptionalType{ - Type: &sema.ReferenceType{ - Authorization: access, - Type: rType, - }, - }, - rValueType, - ) } else { errs := RequireCheckerErrors(t, err, 1) @@ -795,13 +765,16 @@ func TestCheckAccount_borrow(t *testing.T) { t.Parallel() - checker, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, fmt.Sprintf( ` struct S {} - entitlement X - let s = authAccount.borrow<%s &S>(from: /%s/s) + entitlement X + + fun test(storage: auth(Storage) &Account.Storage) { + let s: %[1]s &S? = storage.borrow<%[1]s &S>(from: /%[2]s/s) + } `, authKeyword, domain.Identifier(), @@ -810,27 +783,6 @@ func TestCheckAccount_borrow(t *testing.T) { if domain == common.PathDomainStorage { require.NoError(t, err) - - sType := RequireGlobalType(t, checker.Elaboration, "S") - sValueType := RequireGlobalValue(t, checker.Elaboration, "s") - - xType := RequireGlobalType(t, checker.Elaboration, "X") - require.IsType(t, &sema.EntitlementType{}, xType) - xEntitlement := xType.(*sema.EntitlementType) - var access sema.Access = sema.UnauthorizedAccess - if !auth.Equal(sema.UnauthorizedAccess) { - access = sema.NewEntitlementSetAccess([]*sema.EntitlementType{xEntitlement}, sema.Conjunction) - } - - require.Equal(t, - &sema.OptionalType{ - Type: &sema.ReferenceType{ - Authorization: access, - Type: sType, - }, - }, - sValueType, - ) } else { errs := RequireCheckerErrors(t, err, 1) @@ -855,12 +807,15 @@ func TestCheckAccount_borrow(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, fmt.Sprintf( ` resource R {} - let r <- authAccount.borrow<@R>(from: /%s/r) + fun test(storage: auth(Storage) &Account.Storage) { + let r <- storage.borrow<@R>(from: /%s/r) + destroy r + } `, domain.Identifier(), ), @@ -883,12 +838,14 @@ func TestCheckAccount_borrow(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, fmt.Sprintf( ` struct S {} - let s = authAccount.borrow(from: /%s/s) + fun test(storage: auth(Storage) &Account.Storage) { + let s = storage.borrow(from: /%s/s) + } `, domain.Identifier(), ), @@ -930,342 +887,245 @@ func TestCheckAccount_borrow(t *testing.T) { } } -func TestCheckAccount_BalanceFields(t *testing.T) { +func TestCheckAccountBalanceFields(t *testing.T) { t.Parallel() - for accountType, accountVariable := range map[string]string{ - "AuthAccount": "authAccount", - "PublicAccount": "publicAccount", + for _, fieldName := range []string{ + "balance", + "availableBalance", } { - for _, fieldName := range []string{ - "balance", - "availableBalance", - } { + t.Run(fieldName, func(t *testing.T) { - testName := fmt.Sprintf( - "%s.%s", - accountType, + code := fmt.Sprintf( + ` + fun test(account: &Account): UFix64 { + return account.%s + } + `, fieldName, ) - - t.Run(testName, func(t *testing.T) { - - code := fmt.Sprintf( - ` - fun test(): UFix64 { - return %s.%s - } - - let amount = test() - `, - accountVariable, - fieldName, - ) - checker, err := ParseAndCheckAccount( - t, - code, - ) - - require.NoError(t, err) - - amountType := RequireGlobalValue(t, checker.Elaboration, "amount") - - assert.Equal(t, sema.UFix64Type, amountType) - }) - } + _, err := ParseAndCheck(t, code) + require.NoError(t, err) + }) } } -func TestCheckAccount_StorageFields(t *testing.T) { +func TestCheckAccountStorageFields(t *testing.T) { t.Parallel() - for accountType, accountVariable := range map[string]string{ - "AuthAccount": "authAccount", - "PublicAccount": "publicAccount", + for _, fieldName := range []string{ + "used", + "capacity", } { - for _, fieldName := range []string{ - "storageUsed", - "storageCapacity", - } { + t.Run(fieldName, func(t *testing.T) { - testName := fmt.Sprintf( - "%s.%s", - accountType, + code := fmt.Sprintf( + ` + fun test(storage: &Account.Storage): UInt64 { + return storage.%s + } + `, fieldName, ) - t.Run(testName, func(t *testing.T) { + _, err := ParseAndCheck(t, code) - code := fmt.Sprintf( - ` - fun test(): UInt64 { - return %s.%s - } - - let amount = test() - `, - accountVariable, - fieldName, - ) - checker, err := ParseAndCheckAccount( - t, - code, - ) - - require.NoError(t, err) - - amountType := RequireGlobalValue(t, checker.Elaboration, "amount") - - assert.Equal(t, sema.UInt64Type, amountType) - }) - } + require.NoError(t, err) + }) } } -func TestAuthAccountContracts(t *testing.T) { +func TestCheckAccountContractsNames(t *testing.T) { t.Parallel() - t.Run("contracts type", func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, ` - let contracts: AuthAccount.Contracts = authAccount.contracts - `) - - require.NoError(t, err) - }) + t.Run("read", func(t *testing.T) { - t.Run("contracts names", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - let names: [String] = authAccount.contracts.names - `) + _, err := ParseAndCheck(t, ` + fun test(contracts: &Account.Contracts) { + let names: &[String] = contracts.names + } + `) require.NoError(t, err) }) - t.Run("update contracts names", func(t *testing.T) { + t.Run("assign", func(t *testing.T) { + t.Parallel() - _, err := ParseAndCheckAccount(t, ` - fun test() { - authAccount.contracts.names = ["foo"] - } - `) + + _, err := ParseAndCheck(t, ` + fun test(contracts: &Account.Contracts) { + contracts.names = &["foo"] + } + `) errors := RequireCheckerErrors(t, err, 2) assert.IsType(t, &sema.InvalidAssignmentAccessError{}, errors[0]) assert.IsType(t, &sema.AssignmentToConstantMemberError{}, errors[1]) }) +} - t.Run("get contract", func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, ` - fun test(): DeployedContract { - return authAccount.contracts.get(name: "foo")! - } - `) +func TestCheckAccountContractsGet(t *testing.T) { - require.NoError(t, err) - }) + t.Parallel() + + _, err := ParseAndCheck(t, ` + fun test(contracts: &Account.Contracts): DeployedContract { + return contracts.get(name: "foo")! + } + `) + + require.NoError(t, err) + +} + +func TestCheckAccountContractsBorrow(t *testing.T) { + + t.Parallel() t.Run("borrow contract", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` + + _, err := ParseAndCheck(t, ` contract C {} - fun test(): &C { - return authAccount.contracts.borrow<&C>(name: "foo")! + fun test(contracts: &Account.Contracts): &C { + return contracts.borrow<&C>(name: "foo")! } - `) - + `) require.NoError(t, err) }) t.Run("invalid borrow contract: missing type argument", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` + + _, err := ParseAndCheck(t, ` contract C {} - fun test(): &AnyStruct { - return authAccount.contracts.borrow(name: "foo")! + fun test(contracts: &Account.Contracts): &AnyStruct { + return contracts.borrow(name: "foo")! } - `) + `) errors := RequireCheckerErrors(t, err, 1) assert.IsType(t, &sema.TypeParameterTypeInferenceError{}, errors[0]) }) +} - t.Run("add contract", func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, ` - fun test(): DeployedContract { - return authAccount.contracts.add(name: "foo", code: "012".decodeHex()) - } - `) +func TestCheckAccountContractsAdd(t *testing.T) { - require.NoError(t, err) - }) + t.Parallel() - t.Run("update contract", func(t *testing.T) { + t.Run("unauthorized", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - fun test(): DeployedContract { - return authAccount.contracts.update__experimental(name: "foo", code: "012".decodeHex()) + + _, err := ParseAndCheck(t, ` + fun test(contracts: &Account.Contracts): DeployedContract { + return contracts.add(name: "foo", code: "012".decodeHex()) } - `) + `) - require.NoError(t, err) + errors := RequireCheckerErrors(t, err, 1) + + var invalidAccessErr *sema.InvalidAccessError + require.ErrorAs(t, errors[0], &invalidAccessErr) + assert.Equal(t, "add", invalidAccessErr.Name) }) - t.Run("remove contract", func(t *testing.T) { + t.Run("authorized", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - fun test(): DeployedContract { - return authAccount.contracts.remove(name: "foo")! - } - `) + _, err := ParseAndCheck(t, ` + fun test(contracts: auth(Contracts) &Account.Contracts): DeployedContract { + return contracts.add(name: "foo", code: "012".decodeHex()) + } + `) require.NoError(t, err) }) - } -func TestPublicAccountContracts(t *testing.T) { +func TestCheckAccountContractsUpdate(t *testing.T) { t.Parallel() - t.Run("contracts type", func(t *testing.T) { + t.Run("unauthorized", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - let contracts: PublicAccount.Contracts = publicAccount.contracts - `) - require.NoError(t, err) - }) - - t.Run("contracts names", func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, ` - let names: [String] = publicAccount.contracts.names - `) - - require.NoError(t, err) - }) - - t.Run("update contracts names", func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, ` - fun test() { - publicAccount.contracts.names = ["foo"] + _, err := ParseAndCheck(t, ` + fun test(contracts: &Account.Contracts): DeployedContract { + return contracts.update(name: "foo", code: "012".decodeHex()) } - `) - - errors := RequireCheckerErrors(t, err, 2) - - assert.IsType(t, &sema.InvalidAssignmentAccessError{}, errors[0]) - assert.IsType(t, &sema.AssignmentToConstantMemberError{}, errors[1]) - }) + `) - t.Run("get contract", func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, ` - fun test(): DeployedContract { - return publicAccount.contracts.get(name: "foo")! - } - `) + errors := RequireCheckerErrors(t, err, 1) - require.NoError(t, err) + var invalidAccessErr *sema.InvalidAccessError + require.ErrorAs(t, errors[0], &invalidAccessErr) + assert.Equal(t, "update", invalidAccessErr.Name) }) - t.Run("borrow contract", func(t *testing.T) { + t.Run("authorized", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - contract C {} - fun test(): &C { - return publicAccount.contracts.borrow<&C>(name: "foo")! + _, err := ParseAndCheck(t, ` + fun test(contracts: auth(Contracts) &Account.Contracts): DeployedContract { + return contracts.update(name: "foo", code: "012".decodeHex()) } - `) - + `) require.NoError(t, err) }) +} - t.Run("invalid borrow contract: missing type argument", func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, ` - contract C {} - - fun test(): &AnyStruct { - return publicAccount.contracts.borrow(name: "foo")! - } - `) - - errors := RequireCheckerErrors(t, err, 1) +func TestCheckAccountContractsRemove(t *testing.T) { - assert.IsType(t, &sema.TypeParameterTypeInferenceError{}, errors[0]) - }) + t.Parallel() - t.Run("add contract", func(t *testing.T) { + t.Run("unauthorized", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - fun test(): DeployedContract { - return publicAccount.contracts.add(name: "foo", code: "012".decodeHex()) - } - `) - - errors := RequireCheckerErrors(t, err, 1) - - require.IsType(t, &sema.NotDeclaredMemberError{}, errors[0]) - notDeclaredError := errors[0].(*sema.NotDeclaredMemberError) - assert.Equal(t, "add", notDeclaredError.Name) - }) - t.Run("update contract", func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, ` - fun test(): DeployedContract { - return publicAccount.contracts.update__experimental(name: "foo", code: "012".decodeHex()) + _, err := ParseAndCheck(t, ` + fun test(contracts: &Account.Contracts): DeployedContract? { + return contracts.remove(name: "foo") } - `) + `) errors := RequireCheckerErrors(t, err, 1) - require.IsType(t, &sema.NotDeclaredMemberError{}, errors[0]) - notDeclaredError := errors[0].(*sema.NotDeclaredMemberError) - assert.Equal(t, "update__experimental", notDeclaredError.Name) + var invalidAccessErr *sema.InvalidAccessError + require.ErrorAs(t, errors[0], &invalidAccessErr) + assert.Equal(t, "remove", invalidAccessErr.Name) }) - t.Run("remove contract", func(t *testing.T) { + t.Run("authorized", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - fun test(): DeployedContract { - return publicAccount.contracts.remove(name: "foo") - } - `) - - errors := RequireCheckerErrors(t, err, 1) - require.IsType(t, &sema.NotDeclaredMemberError{}, errors[0]) - notDeclaredError := errors[0].(*sema.NotDeclaredMemberError) - assert.Equal(t, "remove", notDeclaredError.Name) + _, err := ParseAndCheck(t, ` + fun test(contracts: auth(Contracts) &Account.Contracts): DeployedContract? { + return contracts.remove(name: "foo") + } + `) + require.NoError(t, err) }) - } -func TestCheckAccountPaths(t *testing.T) { +func TestCheckAccountStoragePaths(t *testing.T) { t.Parallel() + t.Run("capitalized", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, - ` - let paths = authAccount.StoragePaths - `, - ) + + _, err := ParseAndCheck(t, ` + fun test(storage: &Account.Storage) { + let paths = storage.StoragePaths + } + `) errors := RequireCheckerErrors(t, err, 1) @@ -1277,524 +1137,477 @@ func TestCheckAccountPaths(t *testing.T) { t.Run("annotation", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, - ` - let publicPaths: [PublicPath] = authAccount.publicPaths - let privatePaths: [PrivatePath] = authAccount.privatePaths - let storagePaths: [StoragePath] = authAccount.storagePaths - `, - ) + _, err := ParseAndCheck(t, ` + fun test(storage: &Account.Storage) { + let publicPaths: &[PublicPath] = storage.publicPaths + let storagePaths: &[StoragePath] = storage.storagePaths + } + `) require.NoError(t, err) }) t.Run("supertype annotation", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, - ` - let publicPaths: [Path] = authAccount.publicPaths - let privatePaths: [CapabilityPath] = authAccount.privatePaths - let storagePaths: [Path] = authAccount.storagePaths - `, - ) + _, err := ParseAndCheck(t, ` + fun test(storage: &Account.Storage) { + let publicPaths: &[Path] = storage.publicPaths + let storagePaths: &[Path] = storage.storagePaths + } + `) require.NoError(t, err) }) t.Run("incorrect annotation", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, - ` - let paths: [PublicPath] = authAccount.privatePaths - `, - ) - - errors := RequireCheckerErrors(t, err, 1) - require.IsType(t, &sema.TypeMismatchError{}, errors[0]) - }) - - t.Run("publicAccount annotation", func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, - ` - let paths: [PublicPath] = publicAccount.publicPaths - `, - ) - - require.NoError(t, err) - }) - - t.Run("publicAccount supertype annotation", func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, - ` - let paths: [Path] = publicAccount.publicPaths - `, - ) - - require.NoError(t, err) - }) - - t.Run("publicAccount iteration", func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, ` - let paths: [PublicPath] = publicAccount.publicPaths - `) - require.NoError(t, err) - }) + _, err := ParseAndCheck(t, ` + fun test(storage: &Account.Storage) { + let paths: &[PublicPath] = storage.storagePaths + } + `) - t.Run("iteration", func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, - ` - fun test() { - let paths = authAccount.storagePaths - for storagePath in paths { - let t = authAccount.type(at: storagePath) - } - } - `, - ) + errors := RequireCheckerErrors(t, err, 1) - require.NoError(t, err) + require.IsType(t, &sema.TypeMismatchError{}, errors[0]) }) } -func TestCheckPublicAccountIteration(t *testing.T) { +func TestCheckAccountStorageIteration(t *testing.T) { t.Parallel() - t.Run("basic", func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, - ` - fun test() { - publicAccount.forEachPublic(fun (path: PublicPath, type:Type): Bool { - return true - }) - } - `, - ) + type testCase struct { + storageRefType string + functionName string + pathType string + } - require.NoError(t, err) - }) + test := func(t *testing.T, testCase testCase) { + t.Run(fmt.Sprintf("basic %s", testCase.pathType), func(t *testing.T) { + t.Parallel() - t.Run("labels irrelevant", func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, - ` - fun test() { - publicAccount.forEachPublic(fun (foo: PublicPath, bar:Type): Bool { - return true - }) - } - `, - ) + _, err := ParseAndCheck(t, + fmt.Sprintf( + ` + fun test(storage: %s) { + storage.%s(fun (path: %s, type: Type): Bool { + return true + }) + } + `, + testCase.storageRefType, + testCase.functionName, + testCase.pathType, + ), + ) + require.NoError(t, err) + }) - require.NoError(t, err) - }) + t.Run(fmt.Sprintf("labels irrelevant %s", testCase.pathType), func(t *testing.T) { + t.Parallel() - t.Run("incompatible return", func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, - ` - fun test() { - publicAccount.forEachPublic(fun (path: PublicPath, type:Type): Bool { - return 3 - }) - } - `, - ) + _, err := ParseAndCheck(t, + fmt.Sprintf( + ` + fun test(storage: %s) { + storage.%s(fun (foo: %s, bar: Type): Bool { + return true + }) + } + `, + testCase.storageRefType, + testCase.functionName, + testCase.pathType, + ), + ) + require.NoError(t, err) + }) - errors := RequireCheckerErrors(t, err, 1) - require.IsType(t, &sema.TypeMismatchError{}, errors[0]) - }) + t.Run(fmt.Sprintf("incompatible return %s", testCase.pathType), func(t *testing.T) { + t.Parallel() - t.Run("incompatible return annot", func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, - ` - fun test() { - publicAccount.forEachPublic(fun (path: PublicPath, type:Type): Void {}) - } - `, - ) + _, err := ParseAndCheck(t, + fmt.Sprintf( + ` + fun test(storage: %s) { + storage.%s(fun (path: %s, type: Type): Bool { + return 3 + }) + } + `, + testCase.storageRefType, + testCase.functionName, + testCase.pathType, + ), + ) - errors := RequireCheckerErrors(t, err, 1) - require.IsType(t, &sema.TypeMismatchError{}, errors[0]) - }) + errors := RequireCheckerErrors(t, err, 1) - t.Run("incompatible arg 1", func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, - ` - fun test() { - publicAccount.forEachPublic(fun (path: StoragePath, type:Type): Void {}) - } - `, - ) + require.IsType(t, &sema.TypeMismatchError{}, errors[0]) + }) - errors := RequireCheckerErrors(t, err, 1) - require.IsType(t, &sema.TypeMismatchError{}, errors[0]) - }) + t.Run(fmt.Sprintf("incompatible return annotation %s", testCase.pathType), func(t *testing.T) { + t.Parallel() - t.Run("incompatible arg 2", func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, - ` - fun test() { - publicAccount.forEachPublic(fun (path: PublicPath, type:Int): Void {}) - } - `, - ) + _, err := ParseAndCheck(t, + fmt.Sprintf( + ` + fun test(storage: %s) { + storage.%s(fun (path: %s, type: Type): Void {}) + } + `, + testCase.storageRefType, + testCase.functionName, + testCase.pathType, + ), + ) - errors := RequireCheckerErrors(t, err, 1) - require.IsType(t, &sema.TypeMismatchError{}, errors[0]) - }) + errors := RequireCheckerErrors(t, err, 1) - t.Run("supertype", func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, - ` - fun test() { - publicAccount.forEachPublic(fun (path: CapabilityPath, type:Type): Void {}) - } - `, - ) + require.IsType(t, &sema.TypeMismatchError{}, errors[0]) + }) - errors := RequireCheckerErrors(t, err, 1) - require.IsType(t, &sema.TypeMismatchError{}, errors[0]) - }) -} + t.Run(fmt.Sprintf("incompatible arg 1 %s", testCase.pathType), func(t *testing.T) { + t.Parallel() -func TestCheckAuthAccountIteration(t *testing.T) { + _, err := ParseAndCheck(t, + fmt.Sprintf( + ` + fun test(storage: %s) { + storage.%s(fun (path: Int, type: Type): Void {}) + } + `, + testCase.storageRefType, + testCase.functionName, + ), + ) - t.Parallel() + errors := RequireCheckerErrors(t, err, 1) - t.Run("basic suite", func(t *testing.T) { - t.Parallel() + require.IsType(t, &sema.TypeMismatchError{}, errors[0]) + }) - nameTypePairs := []struct { - name string - correctType string - }{ - {name: "forEachPublic", correctType: "PublicPath"}, - {name: "forEachPrivate", correctType: "PrivatePath"}, - {name: "forEachStored", correctType: "StoragePath"}, - } + t.Run(fmt.Sprintf("incompatible arg 2 %s", testCase.pathType), func(t *testing.T) { + t.Parallel() - test := func(pair struct { - name string - correctType string - }) { - t.Run(fmt.Sprintf("basic %s", pair.correctType), func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, - fmt.Sprintf(` - fun test() { - authAccount.%s(fun (path: %s, type:Type): Bool { - return true - }) - } - `, pair.name, pair.correctType), - ) + _, err := ParseAndCheck(t, + fmt.Sprintf( + ` + fun test(storage: %s) { + storage.%s(fun (path: %s, type: Int): Void {}) + } + `, + testCase.storageRefType, + testCase.functionName, + testCase.pathType, + ), + ) - require.NoError(t, err) - }) + errors := RequireCheckerErrors(t, err, 1) - t.Run(fmt.Sprintf("labels irrelevant %s", pair.correctType), func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, - fmt.Sprintf(` - fun test() { - authAccount.%s(fun (foo: %s, bar:Type): Bool { - return true - }) - } - `, pair.name, pair.correctType), - ) + require.IsType(t, &sema.TypeMismatchError{}, errors[0]) + }) - require.NoError(t, err) - }) + t.Run(fmt.Sprintf("supertype %s", testCase.pathType), func(t *testing.T) { + t.Parallel() - t.Run(fmt.Sprintf("incompatible return %s", pair.correctType), func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, - fmt.Sprintf(` - fun test() { - authAccount.%s(fun (path: %s, type:Type): Bool { - return 3 - }) - } - `, pair.name, pair.correctType), - ) + _, err := ParseAndCheck(t, + fmt.Sprintf( + ` + fun test(storage: %s) { + storage.%s(fun (path: Path, type: Type): Void {}) + } + `, + testCase.storageRefType, + testCase.functionName, + ), + ) - errors := RequireCheckerErrors(t, err, 1) - require.IsType(t, &sema.TypeMismatchError{}, errors[0]) - }) + errors := RequireCheckerErrors(t, err, 1) - t.Run(fmt.Sprintf("incompatible return annot %s", pair.correctType), func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, - fmt.Sprintf(` - fun test() { - authAccount.%s(fun (path: %s, type:Type): Void {}) - } - `, pair.name, pair.correctType), - ) - - errors := RequireCheckerErrors(t, err, 1) - require.IsType(t, &sema.TypeMismatchError{}, errors[0]) - }) + require.IsType(t, &sema.TypeMismatchError{}, errors[0]) + }) + } - t.Run(fmt.Sprintf("incompatible arg 1 %s", pair.correctType), func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, - fmt.Sprintf(` - fun test() { - authAccount.%s(fun (path: Int, type:Type): Void {}) - } - `, pair.name), - ) + functionPairs := []struct { + functionName string + pathType string + }{ + {functionName: "forEachPublic", pathType: "PublicPath"}, + {functionName: "forEachStored", pathType: "StoragePath"}, + } - errors := RequireCheckerErrors(t, err, 1) - require.IsType(t, &sema.TypeMismatchError{}, errors[0]) - }) + for _, storageRefType := range []string{ + "auth(Storage) &Account.Storage", + "&Account.Storage", + } { + t.Run(storageRefType, func(t *testing.T) { - t.Run(fmt.Sprintf("incompatible arg 2 %s", pair.correctType), func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, - fmt.Sprintf(` - fun test() { - authAccount.%s(fun (path: %s, type:Int): Void {}) - } - `, pair.name, pair.correctType), - ) + for _, pair := range functionPairs { + test(t, testCase{ + storageRefType: storageRefType, + functionName: pair.functionName, + pathType: pair.pathType, + }) + } + }) + } +} - errors := RequireCheckerErrors(t, err, 1) - require.IsType(t, &sema.TypeMismatchError{}, errors[0]) - }) +func TestCheckAccountInboxPublish(t *testing.T) { - t.Run(fmt.Sprintf("supertype %s", pair.correctType), func(t *testing.T) { - t.Parallel() - _, err := ParseAndCheckAccount(t, - fmt.Sprintf(` - fun test() { - authAccount.%s(fun (path: Path, type:Type): Void {}) - } - `, pair.name), - ) + t.Parallel() - errors := RequireCheckerErrors(t, err, 1) - require.IsType(t, &sema.TypeMismatchError{}, errors[0]) - }) - } + t.Run("basic", func(t *testing.T) { + t.Parallel() - for _, pair := range nameTypePairs { - test(pair) - } + _, err := ParseAndCheck(t, ` + fun test(cap: Capability<&Int>, inbox: auth(Inbox) &Account.Inbox) { + let x: Void = inbox.publish(cap, name: "foo", recipient: 0x1) + } + `) + require.NoError(t, err) }) -} -func TestCheckAccountPublish(t *testing.T) { + t.Run("unauthorized", func(t *testing.T) { + t.Parallel() - t.Parallel() + _, err := ParseAndCheck(t, ` + fun test(cap: Capability<&Int>, inbox: &Account.Inbox) { + inbox.publish(cap, name: "foo", recipient: 0x1) + } + `) - t.Run("basic publish", func(t *testing.T) { - t.Parallel() + errors := RequireCheckerErrors(t, err, 1) - _, err := ParseAndCheckAccount(t, - `fun test(_ cap: Capability<&Int>) { - let x: Void = authAccount.inbox.publish(cap, name: "foo", recipient: 0x1) - }`, - ) - require.NoError(t, err) + require.IsType(t, &sema.InvalidAccessError{}, errors[0]) }) - t.Run("publish unlabeled name", func(t *testing.T) { + t.Run("unlabeled name", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, - `fun test(_ cap: Capability<&Int>) { - authAccount.inbox.publish(cap, "foo", recipient: 0x1) - }`, - ) - require.Error(t, err) + _, err := ParseAndCheck(t, ` + fun test(cap: Capability<&Int>, inbox: auth(Inbox) &Account.Inbox) { + inbox.publish(cap, "foo", recipient: 0x1) + } + `) + errors := RequireCheckerErrors(t, err, 1) + require.IsType(t, &sema.MissingArgumentLabelError{}, errors[0]) }) - t.Run("publish unlabeled recipient", func(t *testing.T) { + t.Run("unlabeled recipient", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, - `fun test(_ cap: Capability<&Int>) { - authAccount.inbox.publish(cap, name: "foo", 0x1) - }`, - ) - require.Error(t, err) + _, err := ParseAndCheck(t, ` + fun test(cap: Capability<&Int>, inbox: auth(Inbox) &Account.Inbox) { + inbox.publish(cap, name: "foo", 0x1) + } + `) + errors := RequireCheckerErrors(t, err, 1) + require.IsType(t, &sema.MissingArgumentLabelError{}, errors[0]) }) - t.Run("publish wrong argument types", func(t *testing.T) { + t.Run("wrong argument types", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, - `fun test() { - authAccount.inbox.publish(3, name: 3, recipient: "") - }`, - ) - require.Error(t, err) + _, err := ParseAndCheck(t, ` + fun test(inbox: auth(Inbox) &Account.Inbox) { + inbox.publish(3, name: 3, recipient: "") + } + `) + errors := RequireCheckerErrors(t, err, 3) + require.IsType(t, &sema.TypeMismatchError{}, errors[0]) require.IsType(t, &sema.TypeMismatchError{}, errors[1]) require.IsType(t, &sema.TypeMismatchError{}, errors[2]) }) - t.Run("publish non-capability", func(t *testing.T) { + t.Run("non-capability", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, - `fun test() { - authAccount.inbox.publish(fun () {}, name: "foo", recipient: 0x1) - }`, - ) - require.Error(t, err) + _, err := ParseAndCheck(t, ` + fun test(inbox: auth(Inbox) &Account.Inbox) { + inbox.publish(fun () {}, name: "foo", recipient: 0x1) + } + `) + errors := RequireCheckerErrors(t, err, 1) + require.IsType(t, &sema.TypeMismatchError{}, errors[0]) }) } -func TestCheckAccountUnpublish(t *testing.T) { +func TestCheckAccountInboxUnpublish(t *testing.T) { t.Parallel() - t.Run("basic unpublish", func(t *testing.T) { + t.Run("basic", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, - `fun test() { - let x: Capability<&Int> = authAccount.inbox.unpublish<&Int>("foo")! - }`, - ) + _, err := ParseAndCheck(t, ` + fun test(inbox: auth(Inbox) &Account.Inbox) { + let x: Capability<&Int> = inbox.unpublish<&Int>("foo")! + } + `) require.NoError(t, err) }) - t.Run("unpublish wrong argument types", func(t *testing.T) { + t.Run("unauthorized", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, - `fun test() { - authAccount.inbox.unpublish<&String>(4) - }`, - ) - require.Error(t, err) + _, err := ParseAndCheck(t, ` + fun test(inbox: &Account.Inbox) { + inbox.unpublish<&Int>("foo") + } + `) + errors := RequireCheckerErrors(t, err, 1) + + require.IsType(t, &sema.InvalidAccessError{}, errors[0]) + }) + + t.Run("wrong argument types", func(t *testing.T) { + t.Parallel() + + _, err := ParseAndCheck(t, ` + fun test(inbox: auth(Inbox) &Account.Inbox) { + inbox.unpublish<&String>(4) + } + `) + + errors := RequireCheckerErrors(t, err, 1) + require.IsType(t, &sema.TypeMismatchError{}, errors[0]) }) - t.Run("unpublish wrong return", func(t *testing.T) { + t.Run("wrong return", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, ` - resource R {} - fun test() { - let x <- authAccount.inbox.unpublish<&R>("foo") - }`, - ) - require.Error(t, err) + resource R {} + + fun test(inbox: auth(Inbox) &Account.Inbox) { + let x <- inbox.unpublish<&R>("foo") + } + `) + errors := RequireCheckerErrors(t, err, 1) + require.IsType(t, &sema.IncorrectTransferOperationError{}, errors[0]) }) t.Run("missing type params", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, - ` - resource R {} - fun test() { - let x = authAccount.inbox.unpublish("foo")! - }`, - ) - require.Error(t, err) + _, err := ParseAndCheck(t, ` + resource R {} + + fun test(inbox: auth(Inbox) &Account.Inbox) { + let x = inbox.unpublish("foo")! + } + `) + errors := RequireCheckerErrors(t, err, 1) + require.IsType(t, &sema.TypeParameterTypeInferenceError{}, errors[0]) }) } -func TestCheckAccountClaim(t *testing.T) { +func TestCheckAccountInboxClaim(t *testing.T) { t.Parallel() - t.Run("basic claim", func(t *testing.T) { + t.Run("basic", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, - `fun test() { - let x: Capability<&Int> = authAccount.inbox.claim<&Int>("foo", provider: 0x1)! - }`, - ) + _, err := ParseAndCheck(t, ` + fun test(inbox: auth(Inbox) &Account.Inbox) { + let x: Capability<&Int> = inbox.claim<&Int>("foo", provider: 0x1)! + } + `) require.NoError(t, err) }) - t.Run("claim wrong argument types", func(t *testing.T) { + t.Run("unauthorized", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, - `fun test() { - authAccount.inbox.claim<&String>(4, provider: "foo") - }`, - ) - require.Error(t, err) + _, err := ParseAndCheck(t, ` + fun test(inbox: &Account.Inbox) { + let x: Capability<&Int> = inbox.claim<&Int>("foo", provider: 0x1)! + } + `) + + errors := RequireCheckerErrors(t, err, 1) + + require.IsType(t, &sema.InvalidAccessError{}, errors[0]) + }) + + t.Run("wrong argument types", func(t *testing.T) { + t.Parallel() + + _, err := ParseAndCheck(t, ` + fun test(inbox: auth(Inbox) &Account.Inbox) { + inbox.claim<&String>(4, provider: "foo") + } + `) + errors := RequireCheckerErrors(t, err, 2) + require.IsType(t, &sema.TypeMismatchError{}, errors[0]) require.IsType(t, &sema.TypeMismatchError{}, errors[1]) }) - t.Run("claim no provider label", func(t *testing.T) { + t.Run("no provider label", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, - `fun test() { - authAccount.inbox.claim<&Int>("foo", 0x1) - }`, - ) - require.Error(t, err) + _, err := ParseAndCheck(t, ` + fun test(inbox: auth(Inbox) &Account.Inbox) { + inbox.claim<&Int>("foo", 0x1) + } + `) + errors := RequireCheckerErrors(t, err, 1) + require.IsType(t, &sema.MissingArgumentLabelError{}, errors[0]) }) - t.Run("claim wrong return", func(t *testing.T) { + t.Run("wrong return", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, - ` - resource R {} - fun test() { - let x <- authAccount.inbox.claim<&R>("foo", provider: 0x1)! - }`, - ) - require.Error(t, err) + _, err := ParseAndCheck(t, ` + resource R {} + + fun test(inbox: auth(Inbox) &Account.Inbox) { + let x <- inbox.claim<&R>("foo", provider: 0x1)! + } + `) + errors := RequireCheckerErrors(t, err, 1) + require.IsType(t, &sema.IncorrectTransferOperationError{}, errors[0]) }) - t.Run("claim no type argument", func(t *testing.T) { + t.Run("no type argument", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, - ` - resource R {} - fun test() { - authAccount.inbox.claim("foo", provider: 0x1) - }`, - ) - require.Error(t, err) + _, err := ParseAndCheck(t, ` + resource R {} + + fun test(inbox: auth(Inbox) &Account.Inbox) { + inbox.claim("foo", provider: 0x1) + } + `) + errors := RequireCheckerErrors(t, err, 1) + require.IsType(t, &sema.TypeParameterTypeInferenceError{}, errors[0]) }) } @@ -1803,13 +1616,27 @@ func TestCheckAccountCapabilities(t *testing.T) { t.Parallel() - t.Run("AuthAccount.capabilities", func(t *testing.T) { + t.Run("no authorization required", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - fun test() { - let capabilities: AuthAccount.Capabilities = authAccount.capabilities + _, err := ParseAndCheck(t, ` + fun test(capabilities: &Account.Capabilities) { + + let cap: Capability<&Int> = capabilities.get<&Int>(/public/foo)! + + let ref: &Int = capabilities.borrow<&Int>(/public/foo)! + } + `) + require.NoError(t, err) + }) + + t.Run("with authorization", func(t *testing.T) { + + t.Parallel() + + _, err := ParseAndCheck(t, ` + fun test(capabilities: auth(Capabilities) &Account.Capabilities) { let cap: Capability<&Int> = capabilities.get<&Int>(/public/foo)! @@ -1819,17 +1646,42 @@ func TestCheckAccountCapabilities(t *testing.T) { let cap2: Capability = capabilities.unpublish(/public/bar)! } - `) + `) require.NoError(t, err) }) - t.Run("AuthAccount.capabilities.storage", func(t *testing.T) { + t.Run("without authorization", func(t *testing.T) { + + t.Parallel() + + _, err := ParseAndCheck(t, ` + fun test(capabilities: &Account.Capabilities) { + + let cap: Capability<&Int> = capabilities.get<&Int>(/public/foo)! + + capabilities.publish(cap, at: /public/bar) + + let cap2: Capability = capabilities.unpublish(/public/bar)! + } + `) + + errors := RequireCheckerErrors(t, err, 2) + + require.IsType(t, &sema.InvalidAccessError{}, errors[0]) + require.IsType(t, &sema.InvalidAccessError{}, errors[1]) + }) +} + +func TestCheckAccountStorageCapabilities(t *testing.T) { + + t.Parallel() + + t.Run("with authorization", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - fun test() { - let capabilities: AuthAccount.StorageCapabilities = authAccount.capabilities.storage + _, err := ParseAndCheck(t, ` + fun test(capabilities: auth(StorageCapabilities) &Account.StorageCapabilities) { let controller: &StorageCapabilityController = capabilities.getController(byCapabilityID: 1)! @@ -1844,71 +1696,90 @@ func TestCheckAccountCapabilities(t *testing.T) { let cap2: Capability<&String> = capabilities.issue<&String>(/storage/baz) } - `) + `) require.NoError(t, err) }) - t.Run("AuthAccount.capabilities.account", func(t *testing.T) { + t.Run("without authorization", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - fun test() { - let capabilities: AuthAccount.AccountCapabilities = authAccount.capabilities.account + _, err := ParseAndCheck(t, ` + fun test(capabilities: &Account.StorageCapabilities) { - let controller: &AccountCapabilityController = capabilities.getController(byCapabilityID: 1)! + let controller: &StorageCapabilityController = capabilities.getController(byCapabilityID: 1)! - let controllers: [&AccountCapabilityController] = capabilities.getControllers() + let controllers: [&StorageCapabilityController] = capabilities.getControllers(forPath: /storage/foo) - capabilities.forEachController(fun (controller: &AccountCapabilityController): Bool { - return true - }) + capabilities.forEachController( + forPath: /storage/bar, + fun (controller: &StorageCapabilityController): Bool { + return true + } + ) - let cap: Capability<&AuthAccount> = capabilities.issue<&AuthAccount>() + let cap2: Capability<&String> = capabilities.issue<&String>(/storage/baz) } - `) - require.NoError(t, err) + `) + + errors := RequireCheckerErrors(t, err, 4) + + require.IsType(t, &sema.InvalidAccessError{}, errors[0]) + require.IsType(t, &sema.InvalidAccessError{}, errors[1]) + require.IsType(t, &sema.InvalidAccessError{}, errors[2]) + require.IsType(t, &sema.InvalidAccessError{}, errors[3]) }) +} + +func TestCheckAccountAccountCapabilities(t *testing.T) { - t.Run("PublicAccount.capabilities", func(t *testing.T) { + t.Parallel() + + t.Run("with authorization", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - fun test() { - let capabilities: PublicAccount.Capabilities = publicAccount.capabilities + _, err := ParseAndCheck(t, ` + fun test(capabilities: auth(AccountCapabilities) &Account.AccountCapabilities) { - let cap: Capability<&Int> = capabilities.get<&Int>(/public/foo)! + let controller: &AccountCapabilityController = capabilities.getController(byCapabilityID: 1)! - let ref: &Int = capabilities.borrow<&Int>(/public/foo)! + let controllers: [&AccountCapabilityController] = capabilities.getControllers() + + capabilities.forEachController(fun (controller: &AccountCapabilityController): Bool { + return true + }) + + let cap: Capability<&Account> = capabilities.issue<&Account>() } - `) + `) require.NoError(t, err) }) - t.Run("PublicAccount.capabilities.storage: invalid", func(t *testing.T) { + t.Run("without authorization", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - let capabilitiesRef: PublicAccount.StorageCapabilities = publicAccount.capabilities.storage - `) - require.Error(t, err) - errors := RequireCheckerErrors(t, err, 2) - require.IsType(t, &sema.NotDeclaredError{}, errors[0]) - require.IsType(t, &sema.NotDeclaredMemberError{}, errors[1]) - }) + _, err := ParseAndCheck(t, ` + fun test(capabilities: &Account.AccountCapabilities) { - t.Run("PublicAccount.capabilities.account: invalid", func(t *testing.T) { + let controller: &AccountCapabilityController = capabilities.getController(byCapabilityID: 1)! - t.Parallel() + let controllers: [&AccountCapabilityController] = capabilities.getControllers() - _, err := ParseAndCheckAccount(t, ` - let capabilitiesRef: PublicAccount.AccountCapabilities = publicAccount.capabilities.account - `) - require.Error(t, err) - errors := RequireCheckerErrors(t, err, 2) - require.IsType(t, &sema.NotDeclaredError{}, errors[0]) - require.IsType(t, &sema.NotDeclaredMemberError{}, errors[1]) + capabilities.forEachController(fun (controller: &AccountCapabilityController): Bool { + return true + }) + + let cap: Capability<&Account> = capabilities.issue<&Account>() + } + `) + + errors := RequireCheckerErrors(t, err, 4) + + require.IsType(t, &sema.InvalidAccessError{}, errors[0]) + require.IsType(t, &sema.InvalidAccessError{}, errors[1]) + require.IsType(t, &sema.InvalidAccessError{}, errors[2]) + require.IsType(t, &sema.InvalidAccessError{}, errors[3]) }) } diff --git a/runtime/tests/checker/arrays_dictionaries_test.go b/runtime/tests/checker/arrays_dictionaries_test.go index b25e15c787..4ed8f7ba53 100644 --- a/runtime/tests/checker/arrays_dictionaries_test.go +++ b/runtime/tests/checker/arrays_dictionaries_test.go @@ -1699,7 +1699,7 @@ func TestCheckDictionaryKeyTypesExpressions(t *testing.T) { } } -func TestNilAssignmentToDictionary(t *testing.T) { +func TestCheckNilAssignmentToDictionary(t *testing.T) { t.Parallel() @@ -1775,7 +1775,7 @@ func TestCheckArrayFunctionEntitlements(t *testing.T) { assert.ErrorAs(t, errors[1], &invalidAccessError) }) - t.Run("insertable reference", func(t *testing.T) { + t.Run("insert reference", func(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` @@ -1792,7 +1792,7 @@ func TestCheckArrayFunctionEntitlements(t *testing.T) { require.NoError(t, err) }) - t.Run("removable reference", func(t *testing.T) { + t.Run("remove reference", func(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` @@ -1857,7 +1857,7 @@ func TestCheckArrayFunctionEntitlements(t *testing.T) { assert.ErrorAs(t, errors[1], &invalidAccessError) }) - t.Run("insertable reference", func(t *testing.T) { + t.Run("insert reference", func(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` @@ -1879,7 +1879,7 @@ func TestCheckArrayFunctionEntitlements(t *testing.T) { assert.ErrorAs(t, errors[1], &invalidAccessError) }) - t.Run("removable reference", func(t *testing.T) { + t.Run("remove reference", func(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` @@ -1936,7 +1936,7 @@ func TestCheckArrayFunctionEntitlements(t *testing.T) { require.NoError(t, err) }) - t.Run("insertable reference", func(t *testing.T) { + t.Run("insert reference", func(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` @@ -1954,7 +1954,7 @@ func TestCheckArrayFunctionEntitlements(t *testing.T) { require.NoError(t, err) }) - t.Run("removable reference", func(t *testing.T) { + t.Run("remove reference", func(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` @@ -2015,7 +2015,7 @@ func TestCheckArrayFunctionEntitlements(t *testing.T) { ) }) - t.Run("insertable reference", func(t *testing.T) { + t.Run("insert reference", func(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` @@ -2039,7 +2039,7 @@ func TestCheckArrayFunctionEntitlements(t *testing.T) { ) }) - t.Run("removable reference", func(t *testing.T) { + t.Run("remove reference", func(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` @@ -2063,7 +2063,7 @@ func TestCheckArrayFunctionEntitlements(t *testing.T) { ) }) - t.Run("insertable and removable reference", func(t *testing.T) { + t.Run("insert and remove reference", func(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` @@ -2157,7 +2157,7 @@ func TestCheckDictionaryFunctionEntitlements(t *testing.T) { assert.ErrorAs(t, errors[0], &invalidAccessError) }) - t.Run("insertable reference", func(t *testing.T) { + t.Run("insert reference", func(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` @@ -2172,7 +2172,7 @@ func TestCheckDictionaryFunctionEntitlements(t *testing.T) { require.NoError(t, err) }) - t.Run("removable reference", func(t *testing.T) { + t.Run("remove reference", func(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` @@ -2227,7 +2227,7 @@ func TestCheckDictionaryFunctionEntitlements(t *testing.T) { assert.ErrorAs(t, errors[0], &invalidAccessError) }) - t.Run("insertable reference", func(t *testing.T) { + t.Run("insert reference", func(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` @@ -2245,7 +2245,7 @@ func TestCheckDictionaryFunctionEntitlements(t *testing.T) { assert.ErrorAs(t, errors[0], &invalidAccessError) }) - t.Run("removable reference", func(t *testing.T) { + t.Run("remove reference", func(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` @@ -2296,7 +2296,7 @@ func TestCheckDictionaryFunctionEntitlements(t *testing.T) { require.NoError(t, err) }) - t.Run("insertable reference", func(t *testing.T) { + t.Run("insert reference", func(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` @@ -2312,7 +2312,7 @@ func TestCheckDictionaryFunctionEntitlements(t *testing.T) { require.NoError(t, err) }) - t.Run("removable reference", func(t *testing.T) { + t.Run("remove reference", func(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` @@ -2371,7 +2371,7 @@ func TestCheckDictionaryFunctionEntitlements(t *testing.T) { ) }) - t.Run("insertable reference", func(t *testing.T) { + t.Run("insert reference", func(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` @@ -2395,7 +2395,7 @@ func TestCheckDictionaryFunctionEntitlements(t *testing.T) { ) }) - t.Run("removable reference", func(t *testing.T) { + t.Run("remove reference", func(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` @@ -2419,7 +2419,7 @@ func TestCheckDictionaryFunctionEntitlements(t *testing.T) { ) }) - t.Run("insertable and removable reference", func(t *testing.T) { + t.Run("insert and remove reference", func(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` diff --git a/runtime/tests/checker/attachments_test.go b/runtime/tests/checker/attachments_test.go index 35b0337d99..a08cc339a5 100644 --- a/runtime/tests/checker/attachments_test.go +++ b/runtime/tests/checker/attachments_test.go @@ -28,24 +28,25 @@ import ( "github.com/onflow/cadence/runtime/sema" ) -func TestCheckBasic(t *testing.T) { +func TestCheckAttachmentBasic(t *testing.T) { t.Parallel() - _, err := ParseAndCheck(t, - `attachment Test for AnyStruct {}`, - ) + _, err := ParseAndCheck(t, ` + attachment Test for AnyStruct {} + `) require.NoError(t, err) } -func TestCheckRedeclare(t *testing.T) { +func TestCheckAttachmentRedeclaration(t *testing.T) { t.Parallel() - _, err := ParseAndCheck(t, - `struct R {} - attachment R for AnyStruct {}`, + _, err := ParseAndCheck(t, ` + struct R {} + + attachment R for AnyStruct {}`, ) errs := RequireCheckerErrors(t, err, 2) @@ -55,15 +56,15 @@ func TestCheckRedeclare(t *testing.T) { assert.IsType(t, &sema.RedeclarationError{}, errs[1]) } -func TestCheckRedeclareInContract(t *testing.T) { +func TestCheckAttachmentRedeclareInContract(t *testing.T) { t.Parallel() - _, err := ParseAndCheck(t, - `contract C { - attachment C for AnyStruct {} - }`, - ) + _, err := ParseAndCheck(t, ` + contract C { + attachment C for AnyStruct {} + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -72,7 +73,7 @@ func TestCheckRedeclareInContract(t *testing.T) { assert.IsType(t, &sema.RedeclarationError{}, errs[1]) } -func TestCheckBaseType(t *testing.T) { +func TestCheckAttachmentBaseType(t *testing.T) { t.Parallel() @@ -141,7 +142,7 @@ func TestCheckBaseType(t *testing.T) { require.NoError(t, err) }) - t.Run("anystruct", func(t *testing.T) { + t.Run("AnyStruct", func(t *testing.T) { t.Parallel() @@ -153,7 +154,7 @@ func TestCheckBaseType(t *testing.T) { require.NoError(t, err) }) - t.Run("anyresource", func(t *testing.T) { + t.Run("AnyResource", func(t *testing.T) { t.Parallel() @@ -318,12 +319,12 @@ func TestCheckBaseType(t *testing.T) { }) } -func TestCheckBuiltin(t *testing.T) { +func TestCheckAttachmentBuiltin(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, - `attachment Test for AuthAccount {}`, + `attachment Test for Account {}`, ) errs := RequireCheckerErrors(t, err, 1) @@ -331,7 +332,7 @@ func TestCheckBuiltin(t *testing.T) { assert.IsType(t, &sema.InvalidBaseTypeError{}, errs[0]) } -func TestCheckNestedBaseType(t *testing.T) { +func TestCheckAttachmentNestedBaseType(t *testing.T) { t.Parallel() @@ -488,7 +489,7 @@ func TestCheckTypeRequirementsNoLongerAllowed(t *testing.T) { }) } -func TestCheckWithMembers(t *testing.T) { +func TestCheckAttachmentWithMembers(t *testing.T) { t.Parallel() @@ -663,7 +664,7 @@ func TestCheckWithMembers(t *testing.T) { }) } -func TestCheckConformance(t *testing.T) { +func TestCheckAttachmentConformance(t *testing.T) { t.Parallel() @@ -869,7 +870,7 @@ func TestCheckConformance(t *testing.T) { require.NoError(t, err) }) - t.Run("anyresource base, resource conformance", func(t *testing.T) { + t.Run("AnyResource base, resource conformance", func(t *testing.T) { t.Parallel() @@ -882,7 +883,7 @@ func TestCheckConformance(t *testing.T) { require.NoError(t, err) }) - t.Run("anystruct base, struct conformance", func(t *testing.T) { + t.Run("AnyStruct base, struct conformance", func(t *testing.T) { t.Parallel() @@ -895,7 +896,7 @@ func TestCheckConformance(t *testing.T) { require.NoError(t, err) }) - t.Run("anystruct base, resource conformance", func(t *testing.T) { + t.Run("AnyStruct base, resource conformance", func(t *testing.T) { t.Parallel() @@ -910,7 +911,7 @@ func TestCheckConformance(t *testing.T) { assert.IsType(t, &sema.CompositeKindMismatchError{}, errs[0]) }) - t.Run("anyresource base, struct conformance", func(t *testing.T) { + t.Run("AnyResource base, struct conformance", func(t *testing.T) { t.Parallel() @@ -964,7 +965,7 @@ func TestCheckConformance(t *testing.T) { }) } -func TestCheckBase(t *testing.T) { +func TestCheckAttachmentBase(t *testing.T) { t.Parallel() @@ -1139,7 +1140,7 @@ func TestCheckBase(t *testing.T) { }) } -func TestCheckBaseScoping(t *testing.T) { +func TestCheckAttachmentBaseScoping(t *testing.T) { t.Parallel() @@ -1228,7 +1229,7 @@ func TestCheckBaseScoping(t *testing.T) { }) } -func TestCheckBaseTyping(t *testing.T) { +func TestCheckAttachmentBaseTyping(t *testing.T) { t.Parallel() @@ -1303,7 +1304,7 @@ func TestCheckBaseTyping(t *testing.T) { }) } -func TestCheckSelfTyping(t *testing.T) { +func TestCheckAttachmentSelfTyping(t *testing.T) { t.Parallel() @@ -1530,7 +1531,7 @@ func TestCheckAttachmentType(t *testing.T) { }) } -func TestCheckIllegalInit(t *testing.T) { +func TestCheckAttachmentIllegalInit(t *testing.T) { t.Parallel() @@ -1568,7 +1569,7 @@ func TestCheckIllegalInit(t *testing.T) { }) } -func TestCheckAttachNonAttachment(t *testing.T) { +func TestCheckAttachmentAttachNonAttachment(t *testing.T) { t.Parallel() @@ -1683,7 +1684,7 @@ func TestCheckAttachNonAttachment(t *testing.T) { }) } -func TestCheckAttachToNonComposite(t *testing.T) { +func TestCheckAttachmentAttachToNonComposite(t *testing.T) { t.Parallel() @@ -1725,7 +1726,7 @@ func TestCheckAttachToNonComposite(t *testing.T) { assert.IsType(t, &sema.AttachToInvalidTypeError{}, errs[0]) }) - t.Run("non-composite nonresource", func(t *testing.T) { + t.Run("non-composite non-resource", func(t *testing.T) { t.Parallel() @@ -1859,7 +1860,7 @@ func TestCheckAttachToNonComposite(t *testing.T) { }) } -func TestCheckAttach(t *testing.T) { +func TestCheckAttachmentAttach(t *testing.T) { t.Parallel() @@ -1973,7 +1974,7 @@ func TestCheckAttach(t *testing.T) { require.NoError(t, err) }) - t.Run("cannot attach directly to anystruct", func(t *testing.T) { + t.Run("cannot attach directly to AnyStruct", func(t *testing.T) { t.Parallel() @@ -1992,7 +1993,7 @@ func TestCheckAttach(t *testing.T) { assert.IsType(t, &sema.AttachToInvalidTypeError{}, errs[0]) }) - t.Run("cannot attach directly to anyresource", func(t *testing.T) { + t.Run("cannot attach directly to AnyResource", func(t *testing.T) { t.Parallel() @@ -2149,7 +2150,7 @@ func TestCheckAttach(t *testing.T) { assert.IsType(t, &sema.TypeMismatchError{}, errs[0]) }) - t.Run("resource anystruct mismatch", func(t *testing.T) { + t.Run("resource AnyStruct mismatch", func(t *testing.T) { t.Parallel() @@ -2168,7 +2169,7 @@ func TestCheckAttach(t *testing.T) { assert.IsType(t, &sema.TypeMismatchError{}, errs[0]) }) - t.Run("struct anyresource mismatch", func(t *testing.T) { + t.Run("struct AnyResource mismatch", func(t *testing.T) { t.Parallel() @@ -2209,7 +2210,7 @@ func TestCheckAttach(t *testing.T) { }) } -func TestCheckAttachToIntersectionType(t *testing.T) { +func TestCheckAttachmentAttachToIntersectionType(t *testing.T) { t.Parallel() @@ -2312,7 +2313,7 @@ func TestCheckAttachToIntersectionType(t *testing.T) { assert.IsType(t, &sema.TypeMismatchError{}, errs[0]) }) - t.Run("attach anystruct interface to struct interface", func(t *testing.T) { + t.Run("attach AnyStruct interface to struct interface", func(t *testing.T) { t.Parallel() @@ -2351,7 +2352,7 @@ func TestCheckAttachToIntersectionType(t *testing.T) { require.NoError(t, err) }) - t.Run("attach anyresource interface to resource interface", func(t *testing.T) { + t.Run("attach AnyResource interface to resource interface", func(t *testing.T) { t.Parallel() @@ -2411,7 +2412,7 @@ func TestCheckAttachToIntersectionType(t *testing.T) { }) } -func TestCheckAttachWithArguments(t *testing.T) { +func TestCheckAttachmentAttachWithArguments(t *testing.T) { t.Parallel() @@ -2540,7 +2541,7 @@ func TestCheckAttachWithArguments(t *testing.T) { }) } -func TestCheckAttachInvalidType(t *testing.T) { +func TestCheckAttachmentAttachInvalidType(t *testing.T) { t.Parallel() @@ -2559,7 +2560,7 @@ func TestCheckAttachInvalidType(t *testing.T) { assert.IsType(t, &sema.TypeMismatchError{}, errs[1]) } -func TestCheckAnyAttachmentTypes(t *testing.T) { +func TestCheckAttachmentAnyAttachmentTypes(t *testing.T) { type TestCase struct { subType string @@ -2677,7 +2678,7 @@ func TestCheckAnyAttachmentTypes(t *testing.T) { }) } -func TestCheckRemove(t *testing.T) { +func TestCheckAttachmentRemove(t *testing.T) { t.Parallel() @@ -2734,7 +2735,7 @@ func TestCheckRemove(t *testing.T) { assert.IsType(t, &sema.ResourceLossError{}, errs[0]) }) - t.Run("struct with anystruct base", func(t *testing.T) { + t.Run("struct with AnyStruct base", func(t *testing.T) { t.Parallel() @@ -2788,7 +2789,7 @@ func TestCheckRemove(t *testing.T) { assert.IsType(t, &sema.InvalidAttachmentRemoveError{}, errs[0]) }) - t.Run("resource with anyresource base", func(t *testing.T) { + t.Run("resource with AnyResource base", func(t *testing.T) { t.Parallel() @@ -2864,7 +2865,7 @@ func TestCheckRemove(t *testing.T) { require.NoError(t, err) }) - t.Run("noncomposite base", func(t *testing.T) { + t.Run("non-composite base", func(t *testing.T) { t.Parallel() @@ -2882,7 +2883,7 @@ func TestCheckRemove(t *testing.T) { assert.IsType(t, &sema.InvalidAttachmentRemoveError{}, errs[0]) }) - t.Run("cannot remove from anystruct", func(t *testing.T) { + t.Run("cannot remove from AnyStruct", func(t *testing.T) { t.Parallel() @@ -2899,7 +2900,7 @@ func TestCheckRemove(t *testing.T) { assert.IsType(t, &sema.InvalidAttachmentRemoveError{}, errs[0]) }) - t.Run("cannot remove from anyresource", func(t *testing.T) { + t.Run("cannot remove from AnyResource", func(t *testing.T) { t.Parallel() @@ -2917,7 +2918,7 @@ func TestCheckRemove(t *testing.T) { assert.IsType(t, &sema.InvalidAttachmentRemoveError{}, errs[0]) }) - t.Run("noncomposite base anystruct declaration", func(t *testing.T) { + t.Run("non-composite base any-struct declaration", func(t *testing.T) { t.Parallel() @@ -2971,7 +2972,7 @@ func TestCheckRemove(t *testing.T) { assert.IsType(t, &sema.InvalidAttachmentRemoveError{}, errs[0]) }) - t.Run("remove nondeclared", func(t *testing.T) { + t.Run("remove non-declared", func(t *testing.T) { t.Parallel() @@ -3061,7 +3062,7 @@ func TestCheckRemove(t *testing.T) { assert.IsType(t, &sema.InvalidAttachmentRemoveError{}, errs[0]) }) - t.Run("remove anystruct", func(t *testing.T) { + t.Run("remove AnyStruct", func(t *testing.T) { t.Parallel() @@ -3078,7 +3079,7 @@ func TestCheckRemove(t *testing.T) { assert.IsType(t, &sema.InvalidAttachmentRemoveError{}, errs[0]) }) - t.Run("remove anyresource", func(t *testing.T) { + t.Run("remove AnyResource", func(t *testing.T) { t.Parallel() @@ -3096,7 +3097,7 @@ func TestCheckRemove(t *testing.T) { assert.IsType(t, &sema.InvalidAttachmentRemoveError{}, errs[0]) }) - t.Run("remove anystructattachment", func(t *testing.T) { + t.Run("remove AnyStructAttachment", func(t *testing.T) { t.Parallel() @@ -3113,7 +3114,7 @@ func TestCheckRemove(t *testing.T) { assert.IsType(t, &sema.InvalidAttachmentRemoveError{}, errs[0]) }) - t.Run("remove anyresourceattachment", func(t *testing.T) { + t.Run("remove AnyResourceAttachment", func(t *testing.T) { t.Parallel() @@ -3133,7 +3134,7 @@ func TestCheckRemove(t *testing.T) { } -func TestCheckRemoveFromIntersection(t *testing.T) { +func TestCheckAttachmentRemoveFromIntersection(t *testing.T) { t.Parallel() @@ -3213,7 +3214,7 @@ func TestCheckRemoveFromIntersection(t *testing.T) { require.NoError(t, err) }) - t.Run("struct base anystruct intersection", func(t *testing.T) { + t.Run("struct base AnyStruct intersection", func(t *testing.T) { t.Parallel() @@ -3232,7 +3233,7 @@ func TestCheckRemoveFromIntersection(t *testing.T) { assert.IsType(t, &sema.InvalidAttachmentRemoveError{}, errs[0]) }) - t.Run("resource base anyresource intersection", func(t *testing.T) { + t.Run("resource base AnyResource intersection", func(t *testing.T) { t.Parallel() @@ -3252,7 +3253,7 @@ func TestCheckRemoveFromIntersection(t *testing.T) { assert.IsType(t, &sema.InvalidAttachmentRemoveError{}, errs[0]) }) - t.Run("interface base anystruct intersection", func(t *testing.T) { + t.Run("interface base AnyStruct intersection", func(t *testing.T) { t.Parallel() @@ -3269,7 +3270,7 @@ func TestCheckRemoveFromIntersection(t *testing.T) { require.NoError(t, err) }) - t.Run("interface base anyresource intersection", func(t *testing.T) { + t.Run("interface base AnyResource intersection", func(t *testing.T) { t.Parallel() @@ -3306,7 +3307,7 @@ func TestCheckRemoveFromIntersection(t *testing.T) { }) } -func TestCheckAccessAttachment(t *testing.T) { +func TestCheckAttachmentAccessAttachment(t *testing.T) { t.Parallel() @@ -3630,7 +3631,7 @@ func TestCheckAccessAttachment(t *testing.T) { }) } -func TestCheckAccessAttachmentIntersection(t *testing.T) { +func TestCheckAttachmentAccessAttachmentIntersection(t *testing.T) { t.Parallel() @@ -3684,7 +3685,7 @@ func TestCheckAccessAttachmentIntersection(t *testing.T) { assert.IsType(t, &sema.InvalidTypeIndexingError{}, errs[0]) }) - t.Run("intersection anystruct base", func(t *testing.T) { + t.Run("intersection AnyStruct base", func(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, @@ -3699,7 +3700,7 @@ func TestCheckAccessAttachmentIntersection(t *testing.T) { require.NoError(t, err) }) - t.Run("intersection anystruct base interface", func(t *testing.T) { + t.Run("intersection AnyStruct base interface", func(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, @@ -3840,8 +3841,8 @@ func TestCheckAttachmentsExternalMutation(t *testing.T) { errs[0].(*sema.InvalidAccessError).RestrictingAccess, sema.NewEntitlementSetAccess( []*sema.EntitlementType{ - sema.InsertEntitlement, - sema.MutateEntitlement, + sema.InsertType, + sema.MutateType, }, sema.Disjunction, ), @@ -3920,8 +3921,8 @@ func TestCheckAttachmentsExternalMutation(t *testing.T) { errs[0].(*sema.InvalidAccessError).RestrictingAccess, sema.NewEntitlementSetAccess( []*sema.EntitlementType{ - sema.InsertEntitlement, - sema.MutateEntitlement, + sema.InsertType, + sema.MutateType, }, sema.Disjunction, ), @@ -3997,8 +3998,8 @@ func TestCheckAttachmentsExternalMutation(t *testing.T) { errs[0].(*sema.InvalidAccessError).RestrictingAccess, sema.NewEntitlementSetAccess( []*sema.EntitlementType{ - sema.InsertEntitlement, - sema.MutateEntitlement, + sema.InsertType, + sema.MutateType, }, sema.Disjunction, ), @@ -4016,7 +4017,7 @@ func TestCheckAttachmentsExternalMutation(t *testing.T) { }) } -func TestInterpretAttachmentBaseNonMember(t *testing.T) { +func TestCheckAttachmentBaseNonMember(t *testing.T) { t.Parallel() @@ -4211,7 +4212,7 @@ func TestCheckAttachmentsNotEnabled(t *testing.T) { }) } -func TestCheckForEachAttachment(t *testing.T) { +func TestCheckAttachmentForEachAttachment(t *testing.T) { t.Parallel() @@ -4340,7 +4341,7 @@ func TestCheckForEachAttachment(t *testing.T) { assert.IsType(t, &sema.TypeMismatchError{}, errs[0]) }) - t.Run("not on anystruct", func(t *testing.T) { + t.Run("not on AnyStruct", func(t *testing.T) { t.Parallel() @@ -4356,7 +4357,7 @@ func TestCheckForEachAttachment(t *testing.T) { assert.IsType(t, &sema.NotDeclaredMemberError{}, errs[0]) }) - t.Run("not on anyresource", func(t *testing.T) { + t.Run("not on AnyResource", func(t *testing.T) { t.Parallel() @@ -4373,7 +4374,7 @@ func TestCheckForEachAttachment(t *testing.T) { assert.IsType(t, &sema.NotDeclaredMemberError{}, errs[0]) }) - t.Run("not on anyresourceAttachment", func(t *testing.T) { + t.Run("not on AnyResourceAttachment", func(t *testing.T) { t.Parallel() diff --git a/runtime/tests/checker/casting_test.go b/runtime/tests/checker/casting_test.go index 7f904ac873..762d91e598 100644 --- a/runtime/tests/checker/casting_test.go +++ b/runtime/tests/checker/casting_test.go @@ -4896,7 +4896,7 @@ func TestCheckStaticCastElaboration(t *testing.T) { }) } -func TestCastResourceAsEnumAsEmptyDict(t *testing.T) { +func TestCheckCastResourceAsEnumAsEmptyDict(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, "resource foo { enum x : foo { } }") @@ -4909,7 +4909,7 @@ func TestCastResourceAsEnumAsEmptyDict(t *testing.T) { // -func TestCastNumbersManyTimesThenGetType(t *testing.T) { +func TestCheckCastNumbersManyTimesThenGetType(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, "let a = 0x0 as UInt64!as?UInt64!as?UInt64?!?.getType()") diff --git a/runtime/tests/checker/contract_test.go b/runtime/tests/checker/contract_test.go index fe05a3993b..6f4a4ea847 100644 --- a/runtime/tests/checker/contract_test.go +++ b/runtime/tests/checker/contract_test.go @@ -35,17 +35,18 @@ func TestCheckInvalidContractAccountField(t *testing.T) { _, err := ParseAndCheck(t, ` contract Test { - let account: AuthAccount + let account: &Account - init(account: AuthAccount) { + init(account: &Account) { self.account = account } } `) - errs := RequireCheckerErrors(t, err, 1) + errs := RequireCheckerErrors(t, err, 2) assert.IsType(t, &sema.InvalidDeclarationError{}, errs[0]) + assert.IsType(t, &sema.TypeMismatchError{}, errs[1]) } func TestCheckInvalidContractInterfaceAccountField(t *testing.T) { @@ -54,7 +55,7 @@ func TestCheckInvalidContractInterfaceAccountField(t *testing.T) { _, err := ParseAndCheck(t, ` contract interface Test { - let account: AuthAccount + let account: &Account } `) @@ -132,15 +133,16 @@ func TestCheckInvalidContractAccountFieldInitialization(t *testing.T) { _, err := ParseAndCheck(t, ` contract Test { - init(account: AuthAccount) { + init(account: &Account) { self.account = account } } `) - errs := RequireCheckerErrors(t, err, 1) + errs := RequireCheckerErrors(t, err, 2) assert.IsType(t, &sema.AssignmentToConstantMemberError{}, errs[0]) + assert.IsType(t, &sema.TypeMismatchError{}, errs[1]) } func TestCheckInvalidContractAccountFieldAccess(t *testing.T) { diff --git a/runtime/tests/checker/entitlements_test.go b/runtime/tests/checker/entitlements_test.go index 241afbe4ac..d92318d791 100644 --- a/runtime/tests/checker/entitlements_test.go +++ b/runtime/tests/checker/entitlements_test.go @@ -35,9 +35,10 @@ func TestCheckBasicEntitlementDeclaration(t *testing.T) { t.Run("basic", func(t *testing.T) { t.Parallel() + checker, err := ParseAndCheck(t, ` - entitlement E - `) + entitlement E + `) assert.NoError(t, err) entitlement := checker.Elaboration.EntitlementType("S.test.E") @@ -46,9 +47,10 @@ func TestCheckBasicEntitlementDeclaration(t *testing.T) { t.Run("access(self) access", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - access(self) entitlement E - `) + access(self) entitlement E + `) errs := RequireCheckerErrors(t, err, 1) @@ -62,9 +64,10 @@ func TestCheckBasicEntitlementMappingDeclaration(t *testing.T) { t.Run("basic", func(t *testing.T) { t.Parallel() + checker, err := ParseAndCheck(t, ` - entitlement mapping M {} - `) + entitlement mapping M {} + `) assert.NoError(t, err) entitlement := checker.Elaboration.EntitlementMapType("S.test.M") @@ -73,15 +76,19 @@ func TestCheckBasicEntitlementMappingDeclaration(t *testing.T) { t.Run("with mappings", func(t *testing.T) { t.Parallel() + checker, err := ParseAndCheck(t, ` - entitlement A - entitlement B - entitlement C - entitlement mapping M { - A -> B - B -> C - } - `) + entitlement A + + entitlement B + + entitlement C + + entitlement mapping M { + A -> B + B -> C + } + `) assert.NoError(t, err) entitlement := checker.Elaboration.EntitlementMapType("S.test.M") @@ -91,9 +98,10 @@ func TestCheckBasicEntitlementMappingDeclaration(t *testing.T) { t.Run("access(self) access", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - access(self) entitlement mapping M {} - `) + access(self) entitlement mapping M {} + `) errs := RequireCheckerErrors(t, err, 1) @@ -107,13 +115,16 @@ func TestCheckBasicEntitlementMappingNonEntitlements(t *testing.T) { t.Run("resource", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement A - resource B {} - entitlement mapping M { - A -> B - } - `) + entitlement A + + resource B {} + + entitlement mapping M { + A -> B + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -123,13 +134,16 @@ func TestCheckBasicEntitlementMappingNonEntitlements(t *testing.T) { t.Run("struct", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement A - struct B {} - entitlement mapping M { - A -> B - } - `) + entitlement A + + struct B {} + + entitlement mapping M { + A -> B + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -139,13 +153,16 @@ func TestCheckBasicEntitlementMappingNonEntitlements(t *testing.T) { t.Run("attachment", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement A - attachment B for AnyStruct {} - entitlement mapping M { - A -> B - } - `) + entitlement A + + attachment B for AnyStruct {} + + entitlement mapping M { + A -> B + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -155,13 +172,16 @@ func TestCheckBasicEntitlementMappingNonEntitlements(t *testing.T) { t.Run("interface", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement A - resource interface B {} - entitlement mapping M { - A -> B - } - `) + entitlement A + + resource interface B {} + + entitlement mapping M { + A -> B + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -171,13 +191,16 @@ func TestCheckBasicEntitlementMappingNonEntitlements(t *testing.T) { t.Run("contract", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement B - contract A {} - entitlement mapping M { - A -> B - } - `) + entitlement B + + contract A {} + + entitlement mapping M { + A -> B + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -187,13 +210,16 @@ func TestCheckBasicEntitlementMappingNonEntitlements(t *testing.T) { t.Run("event", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement B - event A() - entitlement mapping M { - A -> B - } - `) + entitlement B + + event A() + + entitlement mapping M { + A -> B + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -203,13 +229,16 @@ func TestCheckBasicEntitlementMappingNonEntitlements(t *testing.T) { t.Run("enum", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement B - enum A: UInt8 {} - entitlement mapping M { - A -> B - } - `) + entitlement B + + enum A: UInt8 {} + + entitlement mapping M { + A -> B + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -219,12 +248,14 @@ func TestCheckBasicEntitlementMappingNonEntitlements(t *testing.T) { t.Run("simple type", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement B - entitlement mapping M { - Int -> B - } - `) + entitlement B + + entitlement mapping M { + Int -> B + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -233,13 +264,16 @@ func TestCheckBasicEntitlementMappingNonEntitlements(t *testing.T) { t.Run("other mapping", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement B - entitlement mapping A {} - entitlement mapping M { - A -> B - } - `) + entitlement B + + entitlement mapping A {} + + entitlement mapping M { + A -> B + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -249,35 +283,39 @@ func TestCheckBasicEntitlementMappingNonEntitlements(t *testing.T) { func TestCheckEntitlementDeclarationNesting(t *testing.T) { t.Parallel() + t.Run("in contract", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - contract C { - entitlement E - } - `) + contract C { + entitlement E + } + `) assert.NoError(t, err) }) t.Run("in contract interface", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - contract interface C { - entitlement E - } - `) + contract interface C { + entitlement E + } + `) assert.NoError(t, err) }) t.Run("in resource", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - resource R { - entitlement E - } - `) + resource R { + entitlement E + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -286,11 +324,12 @@ func TestCheckEntitlementDeclarationNesting(t *testing.T) { t.Run("in resource interface", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - resource interface R { - entitlement E - } - `) + resource interface R { + entitlement E + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -299,11 +338,12 @@ func TestCheckEntitlementDeclarationNesting(t *testing.T) { t.Run("in attachment", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - attachment A for AnyStruct { - entitlement E - } - `) + attachment A for AnyStruct { + entitlement E + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -312,11 +352,12 @@ func TestCheckEntitlementDeclarationNesting(t *testing.T) { t.Run("in struct", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - struct S { - entitlement E - } - `) + struct S { + entitlement E + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -325,11 +366,12 @@ func TestCheckEntitlementDeclarationNesting(t *testing.T) { t.Run("in struct", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - struct interface S { - entitlement E - } - `) + struct interface S { + entitlement E + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -338,11 +380,12 @@ func TestCheckEntitlementDeclarationNesting(t *testing.T) { t.Run("in enum", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - enum X: UInt8 { - entitlement E - } - `) + enum X: UInt8 { + entitlement E + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -353,35 +396,39 @@ func TestCheckEntitlementDeclarationNesting(t *testing.T) { func TestCheckEntitlementMappingDeclarationNesting(t *testing.T) { t.Parallel() + t.Run("in contract", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - contract C { - entitlement mapping M {} - } - `) + contract C { + entitlement mapping M {} + } + `) assert.NoError(t, err) }) t.Run("in contract interface", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - contract interface C { - entitlement mapping M {} - } - `) + contract interface C { + entitlement mapping M {} + } + `) assert.NoError(t, err) }) t.Run("in resource", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - resource R { - entitlement mapping M {} - } - `) + resource R { + entitlement mapping M {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -390,11 +437,12 @@ func TestCheckEntitlementMappingDeclarationNesting(t *testing.T) { t.Run("in resource interface", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - resource interface R { - entitlement mapping M {} - } - `) + resource interface R { + entitlement mapping M {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -403,11 +451,12 @@ func TestCheckEntitlementMappingDeclarationNesting(t *testing.T) { t.Run("in attachment", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - attachment A for AnyStruct { - entitlement mapping M {} - } - `) + attachment A for AnyStruct { + entitlement mapping M {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -416,11 +465,12 @@ func TestCheckEntitlementMappingDeclarationNesting(t *testing.T) { t.Run("in struct", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - struct S { - entitlement mapping M {} - } - `) + struct S { + entitlement mapping M {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -429,11 +479,12 @@ func TestCheckEntitlementMappingDeclarationNesting(t *testing.T) { t.Run("in struct", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - struct interface S { - entitlement mapping M {} - } - `) + struct interface S { + entitlement mapping M {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -442,11 +493,12 @@ func TestCheckEntitlementMappingDeclarationNesting(t *testing.T) { t.Run("in enum", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - enum X: UInt8 { - entitlement mapping M {} - } - `) + enum X: UInt8 { + entitlement mapping M {} + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -458,89 +510,108 @@ func TestCheckEntitlementMappingDeclarationNesting(t *testing.T) { func TestCheckBasicEntitlementAccess(t *testing.T) { t.Parallel() + t.Run("valid", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - struct interface S { - access(E) let foo: String - } - `) + entitlement E + + struct interface S { + access(E) let foo: String + } + `) assert.NoError(t, err) }) t.Run("multiple entitlements conjunction", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement A - entitlement B - entitlement C - resource interface R { - access(A, B) let foo: String - access(B, C) fun bar() - } - `) + entitlement A + + entitlement B + + entitlement C + + resource interface R { + access(A, B) let foo: String + access(B, C) fun bar() + } + `) assert.NoError(t, err) }) t.Run("multiple entitlements disjunction", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement A - entitlement B - entitlement C - resource interface R { - access(A | B) let foo: String - access(B | C) fun bar() - } - `) + entitlement A + + entitlement B + + entitlement C + + resource interface R { + access(A | B) let foo: String + access(B | C) fun bar() + } + `) assert.NoError(t, err) }) t.Run("valid in contract", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - contract C { - entitlement E - struct interface S { - access(E) let foo: String - } - } - `) + contract C { + entitlement E + + struct interface S { + access(E) let foo: String + } + } + `) assert.NoError(t, err) }) t.Run("valid in contract interface", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - contract interface C { - entitlement E - struct interface S { - access(E) let foo: String - } - } - `) + contract interface C { + entitlement E + + struct interface S { + access(E) let foo: String + } + } + `) assert.NoError(t, err) }) t.Run("qualified", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - contract C { - entitlement E - struct interface S { - access(E) let foo: String - } - } - resource R { - access(C.E) fun bar() {} - } - `) + contract C { + + entitlement E + + struct interface S { + access(E) let foo: String + } + } + + resource R { + access(C.E) fun bar() {} + } + `) assert.NoError(t, err) }) @@ -549,38 +620,45 @@ func TestCheckBasicEntitlementAccess(t *testing.T) { func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Parallel() + t.Run("valid", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - struct interface S { - access(M) let foo: auth(M) &String - } - `) + entitlement mapping M {} + + struct interface S { + access(M) let foo: auth(M) &String + } + `) assert.NoError(t, err) }) t.Run("optional valid", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - struct interface S { - access(M) let foo: auth(M) &String? - } - `) + entitlement mapping M {} + + struct interface S { + access(M) let foo: auth(M) &String? + } + `) assert.NoError(t, err) }) t.Run("non-reference field", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - struct interface S { - access(M) let foo: String - } - `) + entitlement mapping M {} + + struct interface S { + access(M) let foo: String + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -589,12 +667,14 @@ func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Run("non-auth reference field", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - struct interface S { - access(M) let foo: &String - } - `) + entitlement mapping M {} + + struct interface S { + access(M) let foo: &String + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -603,25 +683,30 @@ func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Run("non-reference container field", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - struct interface S { - access(M) let foo: [String] - } - `) + entitlement mapping M {} + + struct interface S { + access(M) let foo: [String] + } + `) assert.NoError(t, err) }) t.Run("mismatched entitlement mapping", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - entitlement mapping N {} - struct interface S { - access(M) let foo: auth(N) &String - } - `) + entitlement mapping M {} + + entitlement mapping N {} + + struct interface S { + access(M) let foo: auth(N) &String + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -631,13 +716,16 @@ func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Run("mismatched entitlement mapping to set", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - entitlement N - struct interface S { - access(M) let foo: auth(N) &String - } - `) + entitlement mapping M {} + + entitlement N + + struct interface S { + access(M) let foo: auth(N) &String + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -646,12 +734,14 @@ func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Run("function", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - struct interface S { - access(M) fun foo() - } - `) + entitlement mapping M {} + + struct interface S { + access(M) fun foo() + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -660,12 +750,14 @@ func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Run("accessor function in contract", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - contract interface S { - access(M) fun foo(): auth(M) &Int - } - `) + entitlement mapping M {} + + contract interface S { + access(M) fun foo(): auth(M) &Int + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -674,12 +766,14 @@ func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Run("accessor function no container", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - access(M) fun foo(): auth(M) &Int { - return &1 as auth(M) &Int - } - `) + entitlement mapping M {} + + access(M) fun foo(): auth(M) &Int { + return &1 as auth(M) &Int + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -689,25 +783,30 @@ func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Run("accessor function", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - struct interface S { - access(M) fun foo(): auth(M) &Int - } - `) + entitlement mapping M {} + + struct interface S { + access(M) fun foo(): auth(M) &Int + } + `) assert.NoError(t, err) }) t.Run("accessor function non mapped return", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement mapping M {} - struct interface S { - access(M) fun foo(): auth(X) &Int - } - `) + entitlement X + + entitlement mapping M {} + + struct interface S { + access(M) fun foo(): auth(X) &Int + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -716,13 +815,16 @@ func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Run("accessor function non mapped access", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement mapping M {} - struct interface S { - access(X) fun foo(): auth(M) &Int - } - `) + entitlement X + + entitlement mapping M {} + + struct interface S { + access(X) fun foo(): auth(M) &Int + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -731,41 +833,48 @@ func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Run("accessor function optional", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - struct interface S { - access(M) fun foo(): auth(M) &Int? - } - `) + entitlement mapping M {} + + struct interface S { + access(M) fun foo(): auth(M) &Int? + } + `) assert.NoError(t, err) }) t.Run("accessor function with impl", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - struct S { - access(M) fun foo(): auth(M) &Int { - return &1 as auth(M) &Int - } - } - `) + entitlement mapping M {} + + struct S { + access(M) fun foo(): auth(M) &Int { + return &1 as auth(M) &Int + } + } + `) assert.NoError(t, err) }) t.Run("accessor function with impl wrong mapping", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - entitlement mapping N {} - struct S { - access(M) fun foo(): auth(M) &Int { - return &1 as auth(N) &Int - } - } - `) + entitlement mapping M {} + + entitlement mapping N {} + + struct S { + access(M) fun foo(): auth(M) &Int { + return &1 as auth(N) &Int + } + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -775,43 +884,54 @@ func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Run("accessor function with impl subtype", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement mapping M { - X -> Y - X -> Z - } - struct S { - access(M) fun foo(): auth(M) &Int { - return &1 as auth(Y, Z) &Int - } - } - `) + entitlement X + + entitlement Y + + entitlement Z + + entitlement mapping M { + X -> Y + X -> Z + } + + struct S { + access(M) fun foo(): auth(M) &Int { + return &1 as auth(Y, Z) &Int + } + } + `) assert.NoError(t, err) }) t.Run("accessor function with impl supertype", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement mapping M { - X -> Y - X -> Z - } - var x: [auth(Y) &Int] = [] - struct S { - access(M) fun foo(): auth(M) &Int { - let r = &1 as auth(M) &Int - x[0] = r - return r - } - } - `) + entitlement X + + entitlement Y + + entitlement Z + + entitlement mapping M { + X -> Y + X -> Z + } + + var x: [auth(Y) &Int] = [] + + struct S { + access(M) fun foo(): auth(M) &Int { + let r = &1 as auth(M) &Int + x[0] = r + return r + } + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -820,21 +940,25 @@ func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Run("accessor function with impl invalid cast", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement mapping M { - E -> F - } - struct S { - access(M) fun foo(): auth(M) &Int { - let x = &1 as auth(M) &Int - // cannot cast, because M may be access(all) - let y: auth(F) &Int = x - return y - } - } - `) + entitlement E + + entitlement F + + entitlement mapping M { + E -> F + } + + struct S { + access(M) fun foo(): auth(M) &Int { + let x = &1 as auth(M) &Int + // cannot cast, because M may be access(all) + let y: auth(F) &Int = x + return y + } + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -845,76 +969,97 @@ func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Run("accessor function with complex impl", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - var x: [AnyStruct] = [] - struct S { - access(M) fun foo(cond: Bool): auth(M) &Int { - if(cond) { - let r = x[0] - if let ref = x as? auth(M) &Int { - return ref - } else { - return &2 as auth(M) &Int - } - } else { - let r = &3 as auth(M) &Int - x.append(r) - return r - } - } - } - `) + entitlement mapping M {} + + var x: [AnyStruct] = [] + + struct S { + access(M) fun foo(cond: Bool): auth(M) &Int { + if(cond) { + let r = x[0] + if let ref = x as? auth(M) &Int { + return ref + } else { + return &2 as auth(M) &Int + } + } else { + let r = &3 as auth(M) &Int + x.append(r) + return r + } + } + } + `) assert.NoError(t, err) }) t.Run("accessor function with downcast impl", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement mapping M { - X -> Y - X -> Z - } - struct T { - access(Y) fun foo() {} - } - struct S { - access(M) fun foo(cond: Bool): auth(M) &T { - let x = &T() as auth(M) &T - if let y = x as? auth(Y) &T { - y.foo() - } - return x - } - } - `) + entitlement X + + entitlement Y + + entitlement Z + + entitlement mapping M { + X -> Y + X -> Z + } + + struct T { + access(Y) fun foo() {} + } + + struct S { + access(M) fun foo(cond: Bool): auth(M) &T { + let x = &T() as auth(M) &T + if let y = x as? auth(Y) &T { + y.foo() + } + return x + } + } + `) assert.NoError(t, err) }) t.Run("accessor function with no downcast impl", func(t *testing.T) { t.Parallel() - checker, err := ParseAndCheckWithOptions(t, ` - entitlement X - entitlement Y - entitlement mapping M { - X -> Y - } - struct T { - access(Y) fun foo() {} - } - struct S { - access(M) fun foo(cond: Bool): auth(M) &T { - let x = &T() as auth(M) &T - x.foo() - return x - } - } - `, ParseAndCheckOptions{Config: &sema.Config{SuggestionsEnabled: true}}) + + checker, err := ParseAndCheckWithOptions(t, + ` + entitlement X + + entitlement Y + + entitlement mapping M { + X -> Y + } + + struct T { + access(Y) fun foo() {} + } + + struct S { + access(M) fun foo(cond: Bool): auth(M) &T { + let x = &T() as auth(M) &T + x.foo() + return x + } + } + `, + ParseAndCheckOptions{ + Config: &sema.Config{ + SuggestionsEnabled: true, + }, + }, + ) errs := RequireCheckerErrors(t, err, 1) @@ -940,57 +1085,75 @@ func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Run("accessor function with object access impl", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M { - X -> Y - } - struct T { - access(Y) fun getRef(): auth(Y) &Int { - return &1 as auth(Y) &Int - } - } - struct S { - access(M) let t: auth(M) &T - access(M) fun foo(cond: Bool): auth(M) &Int { - // success because we have self is fully entitled to the domain of M - return self.t.getRef() - } - init() { - self.t = &T() as auth(Y) &T - } - } - `) + entitlement X + + entitlement Y + + entitlement mapping M { + X -> Y + } + + struct T { + access(Y) fun getRef(): auth(Y) &Int { + return &1 as auth(Y) &Int + } + } + + struct S { + access(M) let t: auth(M) &T + access(M) fun foo(cond: Bool): auth(M) &Int { + // success because we have self is fully entitled to the domain of M + return self.t.getRef() + } + init() { + self.t = &T() as auth(Y) &T + } + } + `) assert.NoError(t, err) }) t.Run("accessor function with invalid object access impl", func(t *testing.T) { t.Parallel() - checker, err := ParseAndCheckWithOptions(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement mapping M { - X -> Y - } - struct T { - access(Z) fun getRef(): auth(Y) &Int { - return &1 as auth(Y) &Int - } - } - struct S { - access(M) let t: auth(M) &T - access(M) fun foo(cond: Bool): auth(M) &Int { - // invalid bc we have no Z entitlement - return self.t.getRef() - } - init() { - self.t = &T() as auth(Y) &T - } - } - `, ParseAndCheckOptions{Config: &sema.Config{SuggestionsEnabled: true}}) + + checker, err := ParseAndCheckWithOptions(t, + ` + entitlement X + + entitlement Y + + entitlement Z + + entitlement mapping M { + X -> Y + } + + struct T { + access(Z) fun getRef(): auth(Y) &Int { + return &1 as auth(Y) &Int + } + } + + struct S { + access(M) let t: auth(M) &T + access(M) fun foo(cond: Bool): auth(M) &Int { + // invalid bc we have no Z entitlement + return self.t.getRef() + } + init() { + self.t = &T() as auth(Y) &T + } + } + `, + ParseAndCheckOptions{ + Config: &sema.Config{ + SuggestionsEnabled: true, + }, + }, + ) errs := RequireCheckerErrors(t, err, 1) @@ -1024,100 +1187,117 @@ func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Run("accessor function with mapped object access impl", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement mapping M { - X -> Y - } - entitlement mapping N { - Y -> Z - } - struct T { - access(N) fun getRef(): auth(N) &Int { - return &1 as auth(N) &Int - } - } - struct S { - access(M) let t: auth(M) &T - access(X) fun foo(cond: Bool): auth(Z) &Int { - return self.t.getRef() - } - init() { - self.t = &T() as auth(Y) &T - } - } - `) + entitlement X + + entitlement Y + + entitlement Z + + entitlement mapping M { + X -> Y + } + + entitlement mapping N { + Y -> Z + } + + struct T { + access(N) fun getRef(): auth(N) &Int { + return &1 as auth(N) &Int + } + } + + struct S { + access(M) let t: auth(M) &T + access(X) fun foo(cond: Bool): auth(Z) &Int { + return self.t.getRef() + } + init() { + self.t = &T() as auth(Y) &T + } + } + `) assert.NoError(t, err) }) t.Run("accessor function with composed mapping object access impl", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement mapping M { - X -> Y - } - entitlement mapping N { - Y -> Z - } - entitlement mapping NM { - X -> Z - } - struct T { - access(N) fun getRef(): auth(N) &Int { - return &1 as auth(N) &Int - } - } - struct S { - access(M) let t: auth(M) &T - access(NM) fun foo(cond: Bool): auth(NM) &Int { - return self.t.getRef() - } - init() { - self.t = &T() as auth(Y) &T - } - } - `) + entitlement X + + entitlement Y + + entitlement Z + + entitlement mapping M { + X -> Y + } + + entitlement mapping N { + Y -> Z + } + + entitlement mapping NM { + X -> Z + } + + struct T { + access(N) fun getRef(): auth(N) &Int { + return &1 as auth(N) &Int + } + } + + struct S { + access(M) let t: auth(M) &T + access(NM) fun foo(cond: Bool): auth(NM) &Int { + return self.t.getRef() + } + + init() { + self.t = &T() as auth(Y) &T + } + } + `) assert.NoError(t, err) }) t.Run("accessor function with invalid composed mapping object access impl", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement Q - entitlement mapping M { - X -> Y - } - entitlement mapping N { - Y -> Z - } - entitlement mapping NM { - X -> Q - } - struct T { - access(N) fun getRef(): auth(N) &Int { - return &1 as auth(N) &Int - } - } - struct S { - access(M) let t: auth(M) &T - access(NM) fun foo(cond: Bool): auth(NM) &Int { - return self.t.getRef() - } - init() { - self.t = &T() as auth(Y) &T - } - } - `) + entitlement X + entitlement Y + entitlement Z + entitlement Q + entitlement mapping M { + X -> Y + } + entitlement mapping N { + Y -> Z + } + entitlement mapping NM { + X -> Q + } + struct T { + access(N) fun getRef(): auth(N) &Int { + return &1 as auth(N) &Int + } + } + struct S { + access(M) let t: auth(M) &T + access(NM) fun foo(cond: Bool): auth(NM) &Int { + return self.t.getRef() + } + init() { + self.t = &T() as auth(Y) &T + } + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1128,74 +1308,76 @@ func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Run("accessor function with superset composed mapping object access input", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement A - entitlement B - entitlement mapping M { - X -> Y - A -> B - } - entitlement mapping N { - Y -> Z - } - entitlement mapping NM { - X -> Z - } - struct T { - access(N) fun getRef(): auth(N) &Int { - return &1 as auth(N) &Int - } - } - struct S { - access(M) let t: auth(M) &T - access(NM) fun foo(cond: Bool): auth(NM) &Int { - return self.t.getRef() - } - init() { - self.t = &T() as auth(Y, B) &T - } - }`) + entitlement X + entitlement Y + entitlement Z + entitlement A + entitlement B + entitlement mapping M { + X -> Y + A -> B + } + entitlement mapping N { + Y -> Z + } + entitlement mapping NM { + X -> Z + } + struct T { + access(N) fun getRef(): auth(N) &Int { + return &1 as auth(N) &Int + } + } + struct S { + access(M) let t: auth(M) &T + access(NM) fun foo(cond: Bool): auth(NM) &Int { + return self.t.getRef() + } + init() { + self.t = &T() as auth(Y, B) &T + } + }`) assert.NoError(t, err) }) t.Run("accessor function with composed mapping object access skipped step", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement A - entitlement B - entitlement mapping M { - X -> Y - A -> B - } - entitlement mapping N { - Y -> Z - } - entitlement mapping NM { - X -> Z - A -> B - } - struct T { - access(N) fun getRef(): auth(N) &Int { - return &1 as auth(N) &Int - } - } - struct S { - access(M) let t: auth(M) &T - access(NM) fun foo(cond: Bool): auth(NM) &Int { - // the B entitlement doesn't pass through the mapping N - return self.t.getRef() - } - init() { - self.t = &T() as auth(Y, B) &T - } - }`) + entitlement X + entitlement Y + entitlement Z + entitlement A + entitlement B + entitlement mapping M { + X -> Y + A -> B + } + entitlement mapping N { + Y -> Z + } + entitlement mapping NM { + X -> Z + A -> B + } + struct T { + access(N) fun getRef(): auth(N) &Int { + return &1 as auth(N) &Int + } + } + struct S { + access(M) let t: auth(M) &T + access(NM) fun foo(cond: Bool): auth(NM) &Int { + // the B entitlement doesn't pass through the mapping N + return self.t.getRef() + } + init() { + self.t = &T() as auth(Y, B) &T + } + }`) errs := RequireCheckerErrors(t, err, 1) @@ -1209,49 +1391,50 @@ func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement A - entitlement B - entitlement mapping M { - X -> Y - A -> B - } - entitlement mapping N { - Y -> Z - B -> B - } - entitlement mapping NM { - X -> Z - A -> B - } - struct T { - access(N) fun getRef(): auth(N) &Int { - return &1 as auth(N) &Int - } - } - struct S { - access(M) let t: auth(M) &T - access(NM) fun foo(cond: Bool): auth(NM) &Int { - return self.t.getRef() - } - init() { - self.t = &T() as auth(Y, B) &T - } - }`) + entitlement X + entitlement Y + entitlement Z + entitlement A + entitlement B + entitlement mapping M { + X -> Y + A -> B + } + entitlement mapping N { + Y -> Z + B -> B + } + entitlement mapping NM { + X -> Z + A -> B + } + struct T { + access(N) fun getRef(): auth(N) &Int { + return &1 as auth(N) &Int + } + } + struct S { + access(M) let t: auth(M) &T + access(NM) fun foo(cond: Bool): auth(NM) &Int { + return self.t.getRef() + } + init() { + self.t = &T() as auth(Y, B) &T + } + }`) assert.NoError(t, err) }) t.Run("accessor function array", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - struct interface S { - access(M) fun foo(): [auth(M) &Int] - } - `) + entitlement mapping M {} + struct interface S { + access(M) fun foo(): [auth(M) &Int] + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1260,12 +1443,13 @@ func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Run("accessor function with invalid mapped ref arg", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - struct interface S { - access(M) fun foo(arg: auth(M) &Int): auth(M) &Int - } - `) + entitlement mapping M {} + struct interface S { + access(M) fun foo(arg: auth(M) &Int): auth(M) &Int + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1274,13 +1458,14 @@ func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Run("multiple mappings conjunction", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - entitlement mapping N {} - resource interface R { - access(M, N) let foo: String - } - `) + entitlement mapping M {} + entitlement mapping N {} + resource interface R { + access(M, N) let foo: String + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1289,13 +1474,14 @@ func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Run("multiple mappings conjunction with regular", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - entitlement N - resource interface R { - access(M, N) let foo: String - } - `) + entitlement mapping M {} + entitlement N + resource interface R { + access(M, N) let foo: String + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1304,13 +1490,14 @@ func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Run("multiple mappings disjunction", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - entitlement mapping N {} - resource interface R { - access(M | N) let foo: String - } - `) + entitlement mapping M {} + entitlement mapping N {} + resource interface R { + access(M | N) let foo: String + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1319,13 +1506,14 @@ func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Run("multiple mappings disjunction with regular", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement M - entitlement mapping N {} - resource interface R { - access(M | N) let foo: String - } - `) + entitlement M + entitlement mapping N {} + resource interface R { + access(M | N) let foo: String + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1334,57 +1522,61 @@ func TestCheckBasicEntitlementMappingAccess(t *testing.T) { t.Run("valid in contract", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - contract C { - entitlement mapping M {} - struct interface S { - access(M) let foo: auth(M) &String - } - } - `) + contract C { + entitlement mapping M {} + struct interface S { + access(M) let foo: auth(M) &String + } + } + `) assert.NoError(t, err) }) t.Run("valid in contract interface", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - contract interface C { - entitlement mapping M {} - struct interface S { - access(M) let foo: auth(M) &String - } - } - `) + contract interface C { + entitlement mapping M {} + struct interface S { + access(M) let foo: auth(M) &String + } + } + `) assert.NoError(t, err) }) t.Run("qualified", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - contract C { - entitlement mapping M {} - struct interface S { - access(M) let foo: auth(M) &String - } - } - resource interface R { - access(C.M) let bar: auth(C.M) &String - } - `) + contract C { + entitlement mapping M {} + struct interface S { + access(M) let foo: auth(M) &String + } + } + resource interface R { + access(C.M) let bar: auth(C.M) &String + } + `) assert.NoError(t, err) }) t.Run("ref array field", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - resource interface R { - access(M) let foo: [auth(M) &Int] - } - `) + entitlement mapping M {} + resource interface R { + access(M) let foo: [auth(M) &Int] + } + `) assert.NoError(t, err) }) @@ -1396,10 +1588,11 @@ func TestCheckInvalidEntitlementAccess(t *testing.T) { t.Run("invalid variable decl", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - access(E) var x: String = "" - `) + entitlement E + access(E) var x: String = "" + `) errs := RequireCheckerErrors(t, err, 1) @@ -1408,10 +1601,11 @@ func TestCheckInvalidEntitlementAccess(t *testing.T) { t.Run("invalid fun decl", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - access(E) fun foo() {} - `) + entitlement E + access(E) fun foo() {} + `) errs := RequireCheckerErrors(t, err, 1) @@ -1420,12 +1614,13 @@ func TestCheckInvalidEntitlementAccess(t *testing.T) { t.Run("invalid contract field", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - contract C { - access(E) fun foo() {} - } - `) + entitlement E + contract C { + access(E) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1434,12 +1629,13 @@ func TestCheckInvalidEntitlementAccess(t *testing.T) { t.Run("invalid contract interface field", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - contract interface C { - access(E) fun foo() - } - `) + entitlement E + contract interface C { + access(E) fun foo() + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1448,12 +1644,13 @@ func TestCheckInvalidEntitlementAccess(t *testing.T) { t.Run("invalid event", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - resource I { - access(E) event Foo() - } - `) + entitlement E + resource I { + access(E) event Foo() + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -1463,12 +1660,13 @@ func TestCheckInvalidEntitlementAccess(t *testing.T) { t.Run("invalid enum case", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - enum X: UInt8 { - access(E) case red - } - `) + entitlement E + enum X: UInt8 { + access(E) case red + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1477,11 +1675,12 @@ func TestCheckInvalidEntitlementAccess(t *testing.T) { t.Run("missing entitlement declaration fun", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - resource R { - access(E) fun foo() {} - } - `) + resource R { + access(E) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1490,11 +1689,12 @@ func TestCheckInvalidEntitlementAccess(t *testing.T) { t.Run("missing entitlement declaration field", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - struct interface S { - access(E) let foo: String - } - `) + struct interface S { + access(E) let foo: String + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1507,10 +1707,11 @@ func TestCheckInvalidEntitlementMappingAuth(t *testing.T) { t.Run("invalid variable annot", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - let x: auth(M) &Int = 3 - `) + entitlement mapping M {} + let x: auth(M) &Int = 3 + `) errs := RequireCheckerErrors(t, err, 2) @@ -1520,12 +1721,13 @@ func TestCheckInvalidEntitlementMappingAuth(t *testing.T) { t.Run("invalid param annot", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - fun foo(x: auth(M) &Int) { + entitlement mapping M {} + fun foo(x: auth(M) &Int) { - } - `) + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1534,10 +1736,11 @@ func TestCheckInvalidEntitlementMappingAuth(t *testing.T) { t.Run("invalid return annot", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - fun foo(): auth(M) &Int {} - `) + entitlement mapping M {} + fun foo(): auth(M) &Int {} + `) errs := RequireCheckerErrors(t, err, 2) @@ -1547,10 +1750,11 @@ func TestCheckInvalidEntitlementMappingAuth(t *testing.T) { t.Run("invalid ref expr annot", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - let x = &1 as auth(M) &Int - `) + entitlement mapping M {} + let x = &1 as auth(M) &Int + `) errs := RequireCheckerErrors(t, err, 1) @@ -1559,11 +1763,12 @@ func TestCheckInvalidEntitlementMappingAuth(t *testing.T) { t.Run("invalid failable annot", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - let x = &1 as &Int - let y = x as? auth(M) &Int - `) + entitlement mapping M {} + let x = &1 as &Int + let y = x as? auth(M) &Int + `) errs := RequireCheckerErrors(t, err, 1) @@ -1572,10 +1777,11 @@ func TestCheckInvalidEntitlementMappingAuth(t *testing.T) { t.Run("invalid type param annot", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - fun foo(x: Capability) {} - `) + entitlement mapping M {} + fun foo(x: Capability) {} + `) errs := RequireCheckerErrors(t, err, 1) @@ -1584,10 +1790,14 @@ func TestCheckInvalidEntitlementMappingAuth(t *testing.T) { t.Run("invalid type argument annot", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - entitlement mapping M {} - let x = authAccount.borrow(from: /storage/foo) - `) + + _, err := ParseAndCheck(t, ` + entitlement mapping M {} + + fun test(storage: auth(Storage) &Account.Storage) { + let x = storage.borrow(from: /storage/foo) + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1596,11 +1806,12 @@ func TestCheckInvalidEntitlementMappingAuth(t *testing.T) { t.Run("invalid cast annot", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - let x = &1 as &Int - let y = x as auth(M) &Int - `) + entitlement mapping M {} + let x = &1 as &Int + let y = x as auth(M) &Int + `) errs := RequireCheckerErrors(t, err, 1) @@ -1609,12 +1820,13 @@ func TestCheckInvalidEntitlementMappingAuth(t *testing.T) { t.Run("capability field", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - resource interface R { - access(M) let foo: Capability - } - `) + entitlement mapping M {} + resource interface R { + access(M) let foo: Capability + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1623,12 +1835,13 @@ func TestCheckInvalidEntitlementMappingAuth(t *testing.T) { t.Run("optional ref field", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - resource interface R { - access(M) let foo: (auth(M) &Int)? - } - `) + entitlement mapping M {} + resource interface R { + access(M) let foo: (auth(M) &Int)? + } + `) // exception made for optional reference fields assert.NoError(t, err) @@ -1636,12 +1849,13 @@ func TestCheckInvalidEntitlementMappingAuth(t *testing.T) { t.Run("fun ref field", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - resource interface R { - access(M) let foo: fun(auth(M) &Int): auth(M) &Int - } - `) + entitlement mapping M {} + resource interface R { + access(M) let foo: fun(auth(M) &Int): auth(M) &Int + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1650,12 +1864,13 @@ func TestCheckInvalidEntitlementMappingAuth(t *testing.T) { t.Run("optional fun ref field", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - resource interface R { - access(M) let foo: fun((auth(M) &Int?)) - } - `) + entitlement mapping M {} + resource interface R { + access(M) let foo: fun((auth(M) &Int?)) + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1664,16 +1879,17 @@ func TestCheckInvalidEntitlementMappingAuth(t *testing.T) { t.Run("mapped ref unmapped field", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement mapping M { - E -> F - } - struct interface S { - access(E) var x: auth(M) &String - } - `) + entitlement E + entitlement F + entitlement mapping M { + E -> F + } + struct interface S { + access(E) var x: auth(M) &String + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1682,16 +1898,17 @@ func TestCheckInvalidEntitlementMappingAuth(t *testing.T) { t.Run("mapped nonref unmapped field", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement mapping M { - E -> F - } - struct interface S { - access(E) var x: fun(auth(M) &String): Int - } - `) + entitlement E + entitlement F + entitlement mapping M { + E -> F + } + struct interface S { + access(E) var x: fun(auth(M) &String): Int + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1700,16 +1917,17 @@ func TestCheckInvalidEntitlementMappingAuth(t *testing.T) { t.Run("mapped field unmapped ref", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement mapping M { - E -> F - } - struct interface S { - access(M) var x: auth(E) &String - } - `) + entitlement E + entitlement F + entitlement mapping M { + E -> F + } + struct interface S { + access(M) var x: auth(E) &String + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1718,19 +1936,20 @@ func TestCheckInvalidEntitlementMappingAuth(t *testing.T) { t.Run("different map", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement mapping M { - E -> F - } - entitlement mapping N { - E -> F - } - struct interface S { - access(M) var x: auth(N) &String - } - `) + entitlement E + entitlement F + entitlement mapping M { + E -> F + } + entitlement mapping N { + E -> F + } + struct interface S { + access(M) var x: auth(N) &String + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -1745,10 +1964,11 @@ func TestCheckInvalidEntitlementMappingAccess(t *testing.T) { t.Run("invalid variable decl", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - access(M) var x: String = "" - `) + entitlement mapping M {} + access(M) var x: String = "" + `) errs := RequireCheckerErrors(t, err, 1) @@ -1757,12 +1977,13 @@ func TestCheckInvalidEntitlementMappingAccess(t *testing.T) { t.Run("nonreference field", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - resource interface R { - access(M) let foo: Int - } - `) + entitlement mapping M {} + resource interface R { + access(M) let foo: Int + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1771,12 +1992,13 @@ func TestCheckInvalidEntitlementMappingAccess(t *testing.T) { t.Run("optional nonreference field", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - resource interface R { - access(M) let foo: Int? - } - `) + entitlement mapping M {} + resource interface R { + access(M) let foo: Int? + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1785,10 +2007,11 @@ func TestCheckInvalidEntitlementMappingAccess(t *testing.T) { t.Run("invalid fun decl", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - access(M) fun foo() {} - `) + entitlement mapping M {} + access(M) fun foo() {} + `) errs := RequireCheckerErrors(t, err, 1) @@ -1797,12 +2020,13 @@ func TestCheckInvalidEntitlementMappingAccess(t *testing.T) { t.Run("invalid contract field", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - contract C { - access(M) fun foo() {} - } - `) + entitlement mapping M {} + contract C { + access(M) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1811,12 +2035,13 @@ func TestCheckInvalidEntitlementMappingAccess(t *testing.T) { t.Run("invalid contract interface field", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - contract interface C { - access(M) fun foo() - } - `) + entitlement mapping M {} + contract interface C { + access(M) fun foo() + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1825,12 +2050,13 @@ func TestCheckInvalidEntitlementMappingAccess(t *testing.T) { t.Run("invalid event", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - resource I { - access(M) event Foo() - } - `) + entitlement mapping M {} + resource I { + access(M) event Foo() + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -1840,12 +2066,13 @@ func TestCheckInvalidEntitlementMappingAccess(t *testing.T) { t.Run("invalid enum case", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping M {} - enum X: UInt8 { - access(M) case red - } - `) + entitlement mapping M {} + enum X: UInt8 { + access(M) case red + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1854,11 +2081,12 @@ func TestCheckInvalidEntitlementMappingAccess(t *testing.T) { t.Run("missing entitlement mapping declaration fun", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - resource R { - access(M) fun foo() {} - } - `) + resource R { + access(M) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1867,11 +2095,12 @@ func TestCheckInvalidEntitlementMappingAccess(t *testing.T) { t.Run("missing entitlement mapping declaration field", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - struct interface S { - access(M) let foo: String - } - `) + struct interface S { + access(M) let foo: String + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1885,12 +2114,13 @@ func TestCheckNonEntitlementAccess(t *testing.T) { t.Run("resource", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - resource E {} - resource R { - access(E) fun foo() {} - } - `) + resource E {} + resource R { + access(E) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1899,12 +2129,13 @@ func TestCheckNonEntitlementAccess(t *testing.T) { t.Run("resource interface", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - resource interface E {} - resource R { - access(E) fun foo() {} - } - `) + resource interface E {} + resource R { + access(E) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1913,12 +2144,13 @@ func TestCheckNonEntitlementAccess(t *testing.T) { t.Run("attachment", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - attachment E for AnyStruct {} - resource R { - access(E) fun foo() {} - } - `) + attachment E for AnyStruct {} + resource R { + access(E) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1927,12 +2159,13 @@ func TestCheckNonEntitlementAccess(t *testing.T) { t.Run("struct", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - struct E {} - resource R { - access(E) fun foo() {} - } - `) + struct E {} + resource R { + access(E) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1941,12 +2174,13 @@ func TestCheckNonEntitlementAccess(t *testing.T) { t.Run("struct interface", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - resource E {} - resource R { - access(E) fun foo() {} - } - `) + resource E {} + resource R { + access(E) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1955,12 +2189,13 @@ func TestCheckNonEntitlementAccess(t *testing.T) { t.Run("event", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - event E() - resource R { - access(E) fun foo() {} - } - `) + event E() + resource R { + access(E) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1969,12 +2204,13 @@ func TestCheckNonEntitlementAccess(t *testing.T) { t.Run("contract", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - contract E {} - resource R { - access(E) fun foo() {} - } - `) + contract E {} + resource R { + access(E) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1983,12 +2219,13 @@ func TestCheckNonEntitlementAccess(t *testing.T) { t.Run("contract interface", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - contract interface E {} - resource R { - access(E) fun foo() {} - } - `) + contract interface E {} + resource R { + access(E) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -1997,12 +2234,13 @@ func TestCheckNonEntitlementAccess(t *testing.T) { t.Run("enum", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - enum E: UInt8 {} - resource R { - access(E) fun foo() {} - } - `) + enum E: UInt8 {} + resource R { + access(E) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2013,96 +2251,102 @@ func TestCheckNonEntitlementAccess(t *testing.T) { func TestCheckEntitlementInheritance(t *testing.T) { t.Parallel() + t.Run("valid", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - struct interface I { - access(E) fun foo() - } - struct S: I { - access(E) fun foo() {} - } - `) + entitlement E + struct interface I { + access(E) fun foo() + } + struct S: I { + access(E) fun foo() {} + } + `) assert.NoError(t, err) }) t.Run("valid interface", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - struct interface I { - access(E) fun foo() - } - struct interface S: I { - access(E) fun foo() - } - `) + entitlement E + struct interface I { + access(E) fun foo() + } + struct interface S: I { + access(E) fun foo() + } + `) assert.NoError(t, err) }) t.Run("valid mapped", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M { - X -> Y - } - struct interface I { - access(M) let x: auth(M) &String - } - struct S: I { - access(M) let x: auth(M) &String - init() { - self.x = &"foo" as auth(Y) &String - } - } - `) + entitlement X + entitlement Y + entitlement mapping M { + X -> Y + } + struct interface I { + access(M) let x: auth(M) &String + } + struct S: I { + access(M) let x: auth(M) &String + init() { + self.x = &"foo" as auth(Y) &String + } + } + `) assert.NoError(t, err) }) t.Run("valid mapped interface", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M { - X -> Y - } - struct interface I { - access(M) let x: auth(M) &String - } - struct interface S: I { - access(M) let x: auth(M) &String - } - `) + entitlement X + entitlement Y + entitlement mapping M { + X -> Y + } + struct interface I { + access(M) let x: auth(M) &String + } + struct interface S: I { + access(M) let x: auth(M) &String + } + `) assert.NoError(t, err) }) t.Run("mismatched mapped", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M {} - entitlement mapping N { - X -> Y - } - struct interface I { - access(M) let x: auth(M) &String - } - struct S: I { - access(N) let x: auth(N) &String - init() { - self.x = &"foo" as auth(Y) &String - } - } - `) + entitlement X + entitlement Y + entitlement mapping M {} + entitlement mapping N { + X -> Y + } + struct interface I { + access(M) let x: auth(M) &String + } + struct S: I { + access(N) let x: auth(N) &String + init() { + self.x = &"foo" as auth(Y) &String + } + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2111,20 +2355,21 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("mismatched mapped interfaces", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M {} - entitlement mapping N { - X -> Y - } - struct interface I { - access(M) let x: auth(M) &String - } - struct interface S: I { - access(N) let x: auth(N) &String - } - `) + entitlement X + entitlement Y + entitlement mapping M {} + entitlement mapping N { + X -> Y + } + struct interface I { + access(M) let x: auth(M) &String + } + struct interface S: I { + access(N) let x: auth(N) &String + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2133,15 +2378,16 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("access(all) subtyping invalid", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - struct interface I { - access(all) fun foo() - } - struct S: I { - access(E) fun foo() {} - } - `) + entitlement E + struct interface I { + access(all) fun foo() + } + struct S: I { + access(E) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2150,18 +2396,19 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("access(all) subtyping invalid", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - struct interface I { - access(all) var x: String - } - struct S: I { - access(E) var x: String - init() { - self.x = "" - } - } - `) + entitlement E + struct interface I { + access(all) var x: String + } + struct S: I { + access(E) var x: String + init() { + self.x = "" + } + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2170,15 +2417,16 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("access(all) supertying invalid", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - struct interface I { - access(E) fun foo() - } - struct S: I { - access(all) fun foo() {} - } - `) + entitlement E + struct interface I { + access(E) fun foo() + } + struct S: I { + access(all) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2187,18 +2435,19 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("access(all) supertyping invalid", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - struct interface I { - access(E) var x: String - } - struct S: I { - access(all) var x: String - init() { - self.x = "" - } - } - `) + entitlement E + struct interface I { + access(E) var x: String + } + struct S: I { + access(all) var x: String + init() { + self.x = "" + } + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2207,15 +2456,16 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("access contract subtyping invalid", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - struct interface I { - access(contract) fun foo() - } - struct S: I { - access(E) fun foo() {} - } - `) + entitlement E + struct interface I { + access(contract) fun foo() + } + struct S: I { + access(E) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2224,15 +2474,18 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("access account subtyping invalid", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - struct interface I { - access(account) fun foo() - } - struct S: I { - access(E) fun foo() {} - } - `) + entitlement E + + struct interface I { + access(account) fun foo() + } + + struct S: I { + access(E) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2241,15 +2494,16 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("access account supertying invalid", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - struct interface I { - access(E) fun foo() - } - struct S: I { - access(account) fun foo() {} - } - `) + entitlement E + struct interface I { + access(E) fun foo() + } + struct S: I { + access(account) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2258,15 +2512,16 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("access contract supertying invalid", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - struct interface I { - access(E) fun foo() - } - struct S: I { - access(contract) fun foo() {} - } - `) + entitlement E + struct interface I { + access(E) fun foo() + } + struct S: I { + access(contract) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2275,15 +2530,16 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("access(self) supertying invalid", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - struct interface I { - access(E) fun foo() - } - struct S: I { - access(self) fun foo() {} - } - `) + entitlement E + struct interface I { + access(E) fun foo() + } + struct S: I { + access(self) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2292,23 +2548,24 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("invalid map subtype with regular conjunction", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement mapping M { - E -> F - } - struct interface I { - access(E, F) var x: auth(E, F) &String - } - struct S: I { - access(M) var x: auth(M) &String + entitlement E + entitlement F + entitlement mapping M { + E -> F + } + struct interface I { + access(E, F) var x: auth(E, F) &String + } + struct S: I { + access(M) var x: auth(M) &String - init() { - self.x = &"foo" as auth(F) &String - } - } - `) + init() { + self.x = &"foo" as auth(F) &String + } + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2317,23 +2574,24 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("invalid map supertype with regular conjunction", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement mapping M { - E -> F - } - struct interface I { - access(M) var x: auth(M) &String - } - struct S: I { - access(E, F) var x: auth(E, F) &String + entitlement E + entitlement F + entitlement mapping M { + E -> F + } + struct interface I { + access(M) var x: auth(M) &String + } + struct S: I { + access(E, F) var x: auth(E, F) &String - init() { - self.x = &"foo" as auth(E, F) &String - } - } - `) + init() { + self.x = &"foo" as auth(E, F) &String + } + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2342,23 +2600,24 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("invalid map subtype with regular disjunction", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement mapping M { - E -> F - } - struct interface I { - access(E | F) var x: auth(E | F) &String - } - struct S: I { - access(M) var x: auth(M) &String + entitlement E + entitlement F + entitlement mapping M { + E -> F + } + struct interface I { + access(E | F) var x: auth(E | F) &String + } + struct S: I { + access(M) var x: auth(M) &String - init() { - self.x = &"foo" as auth(F) &String - } - } - `) + init() { + self.x = &"foo" as auth(F) &String + } + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2367,23 +2626,24 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("invalid map supertype with regular disjunction", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement mapping M { - E -> F - } - struct interface I { - access(M) var x: auth(M) &String - } - struct S: I { - access(E | F) var x: auth(E | F) &String + entitlement E + entitlement F + entitlement mapping M { + E -> F + } + struct interface I { + access(M) var x: auth(M) &String + } + struct S: I { + access(E | F) var x: auth(E | F) &String - init() { - self.x = &"foo" as auth(F) &String - } - } - `) + init() { + self.x = &"foo" as auth(F) &String + } + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2392,92 +2652,97 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("expanded entitlements valid in disjunction", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - struct interface I { - access(E) fun foo() - } - struct interface J { - access(F) fun foo() - } - struct S: I, J { - access(E | F) fun foo() {} - } - `) + entitlement E + entitlement F + struct interface I { + access(E) fun foo() + } + struct interface J { + access(F) fun foo() + } + struct S: I, J { + access(E | F) fun foo() {} + } + `) assert.NoError(t, err) }) t.Run("more expanded entitlements valid in disjunction", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement G - struct interface I { - access(E | G) fun foo() - } - struct S: I { - access(E | F | G) fun foo() {} - } - `) + entitlement E + entitlement F + entitlement G + struct interface I { + access(E | G) fun foo() + } + struct S: I { + access(E | F | G) fun foo() {} + } + `) assert.NoError(t, err) }) t.Run("reduced entitlements valid with conjunction", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement G - struct interface I { - access(E, G) fun foo() - } - struct interface J { - access(E, F) fun foo() - } - struct S: I, J { - access(E) fun foo() {} - } - `) + entitlement E + entitlement F + entitlement G + struct interface I { + access(E, G) fun foo() + } + struct interface J { + access(E, F) fun foo() + } + struct S: I, J { + access(E) fun foo() {} + } + `) assert.NoError(t, err) }) t.Run("more reduced entitlements valid with conjunction", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement G - struct interface I { - access(E, F, G) fun foo() - } - struct S: I { - access(E, F) fun foo() {} - } - `) + entitlement E + entitlement F + entitlement G + struct interface I { + access(E, F, G) fun foo() + } + struct S: I { + access(E, F) fun foo() {} + } + `) assert.NoError(t, err) }) t.Run("expanded entitlements invalid in conjunction", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - struct interface I { - access(E) fun foo() - } - struct interface J { - access(F) fun foo() - } - struct S: I, J { - access(E, F) fun foo() {} - } - `) + entitlement E + entitlement F + struct interface I { + access(E) fun foo() + } + struct interface J { + access(F) fun foo() + } + struct S: I, J { + access(E, F) fun foo() {} + } + `) // this conforms to neither I nor J errs := RequireCheckerErrors(t, err, 2) @@ -2488,17 +2753,18 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("more expanded entitlements invalid in conjunction", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement G - struct interface I { - access(E, F) fun foo() - } - struct S: I { - access(E, F, G) fun foo() {} - } - `) + entitlement E + entitlement F + entitlement G + struct interface I { + access(E, F) fun foo() + } + struct S: I { + access(E, F, G) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2507,19 +2773,20 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("expanded entitlements invalid", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - struct interface I { - access(E) fun foo() - } - struct interface J { - access(F) fun foo() - } - struct S: I, J { - access(E) fun foo() {} - } - `) + entitlement E + entitlement F + struct interface I { + access(E) fun foo() + } + struct interface J { + access(F) fun foo() + } + struct S: I, J { + access(E) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2528,19 +2795,20 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("reduced entitlements invalid with disjunction", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - struct interface I { - access(E) fun foo() - } - struct interface J { - access(E | F) fun foo() - } - struct S: I, J { - access(E) fun foo() {} - } - `) + entitlement E + entitlement F + struct interface I { + access(E) fun foo() + } + struct interface J { + access(E | F) fun foo() + } + struct S: I, J { + access(E) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2549,17 +2817,18 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("more reduced entitlements invalid with disjunction", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement G - struct interface I { - access(E | F | G) fun foo() - } - struct S: I { - access(E | G) fun foo() {} - } - `) + entitlement E + entitlement F + entitlement G + struct interface I { + access(E | F | G) fun foo() + } + struct S: I { + access(E | G) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2568,17 +2837,18 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("overlapped entitlements invalid with disjunction", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement G - struct interface J { - access(E | F) fun foo() - } - struct S: J { - access(E | G) fun foo() {} - } - `) + entitlement E + entitlement F + entitlement G + struct interface J { + access(E | F) fun foo() + } + struct S: J { + access(E | G) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2587,17 +2857,18 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("overlapped entitlements invalid with disjunction/conjunction subtype", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement G - struct interface J { - access(E | F) fun foo() - } - struct S: J { - access(E, G) fun foo() {} - } - `) + entitlement E + entitlement F + entitlement G + struct interface J { + access(E | F) fun foo() + } + struct S: J { + access(E, G) fun foo() {} + } + `) // implementation is more specific because it requires both, but interface only guarantees one errs := RequireCheckerErrors(t, err, 1) @@ -2607,32 +2878,34 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("disjunction/conjunction subtype valid when sets are the same", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - struct interface J { - access(E | E) fun foo() - } - struct S: J { - access(E, E) fun foo() {} - } - `) + entitlement E + struct interface J { + access(E | E) fun foo() + } + struct S: J { + access(E, E) fun foo() {} + } + `) assert.NoError(t, err) }) t.Run("overlapped entitlements valid with conjunction/disjunction subtype", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement G - struct interface J { - access(E, F) fun foo() - } - struct S: J { - access(E | G) fun foo() {} - } - `) + entitlement E + entitlement F + entitlement G + struct interface J { + access(E, F) fun foo() + } + struct S: J { + access(E | G) fun foo() {} + } + `) // implementation is less specific because it only requires one, but interface guarantees both assert.NoError(t, err) @@ -2640,20 +2913,21 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("different entitlements invalid", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement G - struct interface I { - access(E) fun foo() - } - struct interface J { - access(F) fun foo() - } - struct S: I, J { - access(E | G) fun foo() {} - } - `) + entitlement E + entitlement F + entitlement G + struct interface I { + access(E) fun foo() + } + struct interface J { + access(F) fun foo() + } + struct S: I, J { + access(E | G) fun foo() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2662,113 +2936,117 @@ func TestCheckEntitlementInheritance(t *testing.T) { t.Run("default function entitlements", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement mapping M { - E -> F - } - entitlement G - struct interface I { - access(M) fun foo(): auth(M) &Int { - return &1 as auth(M) &Int - } - } - struct S: I {} - fun test() { - let s = S() - let ref = &s as auth(E) &S - let i: auth(F) &Int = s.foo() - } - `) + entitlement E + entitlement F + entitlement mapping M { + E -> F + } + entitlement G + struct interface I { + access(M) fun foo(): auth(M) &Int { + return &1 as auth(M) &Int + } + } + struct S: I {} + fun test() { + let s = S() + let ref = &s as auth(E) &S + let i: auth(F) &Int = s.foo() + } + `) assert.NoError(t, err) }) t.Run("attachment default function entitlements", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement G - entitlement mapping M { - E -> F - } - entitlement mapping N { - G -> E - } - struct interface I { - access(M) fun foo(): auth(M) &Int { - return &1 as auth(M) &Int - } - } - struct S {} - access(N) attachment A for S: I {} - fun test() { - let s = attach A() to S() - let ref = &s as auth(G) &S - let i: auth(F) &Int = s[A]!.foo() - } - `) + entitlement E + entitlement F + entitlement G + entitlement mapping M { + E -> F + } + entitlement mapping N { + G -> E + } + struct interface I { + access(M) fun foo(): auth(M) &Int { + return &1 as auth(M) &Int + } + } + struct S {} + access(N) attachment A for S: I {} + fun test() { + let s = attach A() to S() + let ref = &s as auth(G) &S + let i: auth(F) &Int = s[A]!.foo() + } + `) assert.NoError(t, err) }) t.Run("attachment inherited default function entitlements", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement G - entitlement mapping M { - E -> F - } - entitlement mapping N { - G -> E - } - struct interface I { - access(M) fun foo(): auth(M) &Int { - return &1 as auth(M) &Int - } - } - struct interface I2: I {} - struct S {} - access(N) attachment A for S: I2 {} - fun test() { - let s = attach A() to S() - let ref = &s as auth(G) &S - let i: auth(F) &Int = s[A]!.foo() - } - `) + entitlement E + entitlement F + entitlement G + entitlement mapping M { + E -> F + } + entitlement mapping N { + G -> E + } + struct interface I { + access(M) fun foo(): auth(M) &Int { + return &1 as auth(M) &Int + } + } + struct interface I2: I {} + struct S {} + access(N) attachment A for S: I2 {} + fun test() { + let s = attach A() to S() + let ref = &s as auth(G) &S + let i: auth(F) &Int = s[A]!.foo() + } + `) assert.NoError(t, err) }) t.Run("attachment default function entitlements no attachment mapping", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement G - entitlement mapping M { - E -> F - } - entitlement mapping N { - G -> E - } - struct interface I { - access(M) fun foo(): auth(M) &Int { - return &1 as auth(M) &Int - } - } - struct S {} - attachment A for S: I {} - fun test() { - let s = attach A() to S() - let ref = &s as auth(G) &S - let i: auth(F) &Int = s[A]!.foo() // mismatch - } - `) + entitlement E + entitlement F + entitlement G + entitlement mapping M { + E -> F + } + entitlement mapping N { + G -> E + } + struct interface I { + access(M) fun foo(): auth(M) &Int { + return &1 as auth(M) &Int + } + } + struct S {} + attachment A for S: I {} + fun test() { + let s = attach A() to S() + let ref = &s as auth(G) &S + let i: auth(F) &Int = s[A]!.foo() // mismatch + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2783,10 +3061,11 @@ func TestCheckEntitlementTypeAnnotation(t *testing.T) { t.Run("invalid local annot", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - let x: E = "" - `) + entitlement E + let x: E = "" + `) errs := RequireCheckerErrors(t, err, 2) @@ -2796,10 +3075,11 @@ func TestCheckEntitlementTypeAnnotation(t *testing.T) { t.Run("invalid param annot", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - access(all) fun foo(e: E) {} - `) + entitlement E + access(all) fun foo(e: E) {} + `) errs := RequireCheckerErrors(t, err, 1) @@ -2808,12 +3088,13 @@ func TestCheckEntitlementTypeAnnotation(t *testing.T) { t.Run("invalid return annot", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - resource interface I { - access(all) fun foo(): E - } - `) + entitlement E + resource interface I { + access(all) fun foo(): E + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2822,12 +3103,13 @@ func TestCheckEntitlementTypeAnnotation(t *testing.T) { t.Run("invalid field annot", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - resource interface I { - let e: E - } - `) + entitlement E + resource interface I { + let e: E + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2836,10 +3118,11 @@ func TestCheckEntitlementTypeAnnotation(t *testing.T) { t.Run("invalid conformance annotation", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - resource R: E {} - `) + entitlement E + resource R: E {} + `) errs := RequireCheckerErrors(t, err, 1) @@ -2848,12 +3131,13 @@ func TestCheckEntitlementTypeAnnotation(t *testing.T) { t.Run("invalid array annot", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - resource interface I { - let e: [E] - } - `) + entitlement E + resource interface I { + let e: [E] + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2862,12 +3146,13 @@ func TestCheckEntitlementTypeAnnotation(t *testing.T) { t.Run("invalid fun annot", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - resource interface I { - let e: (fun (E): Void) - } - `) + entitlement E + resource interface I { + let e: (fun (E): Void) + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2876,10 +3161,11 @@ func TestCheckEntitlementTypeAnnotation(t *testing.T) { t.Run("invalid enum conformance", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - enum X: E {} - `) + entitlement E + enum X: E {} + `) errs := RequireCheckerErrors(t, err, 1) @@ -2888,12 +3174,13 @@ func TestCheckEntitlementTypeAnnotation(t *testing.T) { t.Run("invalid dict annot", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - resource interface I { - let e: {E: E} - } - `) + entitlement E + resource interface I { + let e: {E: E} + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -2905,12 +3192,13 @@ func TestCheckEntitlementTypeAnnotation(t *testing.T) { t.Run("invalid fun annot", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - resource interface I { - let e: (fun (E): Void) - } - `) + entitlement E + resource interface I { + let e: (fun (E): Void) + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2919,10 +3207,11 @@ func TestCheckEntitlementTypeAnnotation(t *testing.T) { t.Run("runtype type", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - let e = Type() - `) + entitlement E + let e = Type() + `) errs := RequireCheckerErrors(t, err, 1) @@ -2931,10 +3220,14 @@ func TestCheckEntitlementTypeAnnotation(t *testing.T) { t.Run("type arg", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - entitlement E - let e = authAccount.load(from: /storage/foo) - `) + + _, err := ParseAndCheck(t, ` + entitlement E + + fun test(storage: auth(Storage) &Account.Storage) { + let e = storage.load(from: /storage/foo) + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -2945,12 +3238,14 @@ func TestCheckEntitlementTypeAnnotation(t *testing.T) { t.Run("intersection", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - entitlement E - resource interface I { - let e: {E} - } - `) + + _, err := ParseAndCheck(t, ` + entitlement E + + resource interface I { + let e: {E} + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -2960,12 +3255,14 @@ func TestCheckEntitlementTypeAnnotation(t *testing.T) { t.Run("reference", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - entitlement E - resource interface I { - let e: &E - } - `) + + _, err := ParseAndCheck(t, ` + entitlement E + + resource interface I { + let e: &E + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -2974,12 +3271,14 @@ func TestCheckEntitlementTypeAnnotation(t *testing.T) { t.Run("capability", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - entitlement E - resource interface I { - let e: Capability<&E> - } - `) + + _, err := ParseAndCheck(t, ` + entitlement E + + resource interface I { + let e: Capability<&E> + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -2989,12 +3288,14 @@ func TestCheckEntitlementTypeAnnotation(t *testing.T) { t.Run("optional", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - entitlement E - resource interface I { - let e: E? - } - `) + + _, err := ParseAndCheck(t, ` + entitlement E + + resource interface I { + let e: E? + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -3008,10 +3309,11 @@ func TestCheckEntitlementMappingTypeAnnotation(t *testing.T) { t.Run("invalid local annot", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping E {} - let x: E = "" - `) + entitlement mapping E {} + let x: E = "" + `) errs := RequireCheckerErrors(t, err, 2) @@ -3021,10 +3323,12 @@ func TestCheckEntitlementMappingTypeAnnotation(t *testing.T) { t.Run("invalid param annot", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping E {} - access(all) fun foo(e: E) {} - `) + entitlement mapping E {} + + access(all) fun foo(e: E) {} + `) errs := RequireCheckerErrors(t, err, 1) @@ -3033,12 +3337,14 @@ func TestCheckEntitlementMappingTypeAnnotation(t *testing.T) { t.Run("invalid return annot", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping E {} - resource interface I { - access(all) fun foo(): E - } - `) + entitlement mapping E {} + + resource interface I { + access(all) fun foo(): E + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -3047,12 +3353,14 @@ func TestCheckEntitlementMappingTypeAnnotation(t *testing.T) { t.Run("invalid field annot", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping E {} - resource interface I { - let e: E - } - `) + entitlement mapping E {} + + resource interface I { + let e: E + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -3061,10 +3369,12 @@ func TestCheckEntitlementMappingTypeAnnotation(t *testing.T) { t.Run("invalid conformance annotation", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping E {} - resource R: E {} - `) + entitlement mapping E {} + + resource R: E {} + `) errs := RequireCheckerErrors(t, err, 1) @@ -3073,12 +3383,14 @@ func TestCheckEntitlementMappingTypeAnnotation(t *testing.T) { t.Run("invalid array annot", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping E {} - resource interface I { - let e: [E] - } - `) + entitlement mapping E {} + + resource interface I { + let e: [E] + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -3087,12 +3399,14 @@ func TestCheckEntitlementMappingTypeAnnotation(t *testing.T) { t.Run("invalid fun annot", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping E {} - resource interface I { - let e: (fun (E): Void) - } - `) + entitlement mapping E {} + + resource interface I { + let e: (fun (E): Void) + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -3101,10 +3415,12 @@ func TestCheckEntitlementMappingTypeAnnotation(t *testing.T) { t.Run("invalid enum conformance", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping E {} - enum X: E {} - `) + entitlement mapping E {} + + enum X: E {} + `) errs := RequireCheckerErrors(t, err, 1) @@ -3113,12 +3429,14 @@ func TestCheckEntitlementMappingTypeAnnotation(t *testing.T) { t.Run("invalid dict annot", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping E {} - resource interface I { - let e: {E: E} - } - `) + entitlement mapping E {} + + resource interface I { + let e: {E: E} + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -3128,12 +3446,14 @@ func TestCheckEntitlementMappingTypeAnnotation(t *testing.T) { require.IsType(t, &sema.DirectEntitlementAnnotationError{}, errs[1]) }) - t.Run("runtype type", func(t *testing.T) { + t.Run("runtime type", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping E {} - let e = Type() - `) + entitlement mapping E {} + + let e = Type() + `) errs := RequireCheckerErrors(t, err, 1) @@ -3142,10 +3462,14 @@ func TestCheckEntitlementMappingTypeAnnotation(t *testing.T) { t.Run("type arg", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - entitlement mapping E {} - let e = authAccount.load(from: /storage/foo) - `) + + _, err := ParseAndCheck(t, ` + entitlement mapping E {} + + fun test(storage: auth(Storage) &Account.Storage) { + let e = storage.load(from: /storage/foo) + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -3156,12 +3480,14 @@ func TestCheckEntitlementMappingTypeAnnotation(t *testing.T) { t.Run("intersection", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - entitlement mapping E {} - resource interface I { - let e: {E} - } - `) + + _, err := ParseAndCheck(t, ` + entitlement mapping E {} + + resource interface I { + let e: {E} + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -3171,12 +3497,14 @@ func TestCheckEntitlementMappingTypeAnnotation(t *testing.T) { t.Run("reference", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - entitlement mapping E {} - resource interface I { - let e: &E - } - `) + + _, err := ParseAndCheck(t, ` + entitlement mapping E {} + + resource interface I { + let e: &E + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -3185,12 +3513,14 @@ func TestCheckEntitlementMappingTypeAnnotation(t *testing.T) { t.Run("capability", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - entitlement mapping E {} - resource interface I { - let e: Capability<&E> - } - `) + + _, err := ParseAndCheck(t, ` + entitlement mapping E {} + + resource interface I { + let e: Capability<&E> + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -3200,12 +3530,13 @@ func TestCheckEntitlementMappingTypeAnnotation(t *testing.T) { t.Run("optional", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - entitlement mapping E {} - resource interface I { - let e: E? - } - `) + + _, err := ParseAndCheck(t, ` + entitlement mapping E {} + resource interface I { + let e: E? + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -3216,23 +3547,29 @@ func TestCheckEntitlementMappingTypeAnnotation(t *testing.T) { func TestCheckAttachmentEntitlementAccessAnnotation(t *testing.T) { t.Parallel() + t.Run("mapping allowed", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement mapping E {} - access(E) attachment A for AnyStruct {} - `) + entitlement mapping E {} + + access(E) attachment A for AnyStruct {} + `) assert.NoError(t, err) }) t.Run("entitlement set not allowed", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - access(E, F) attachment A for AnyStruct {} - `) + entitlement E + + entitlement F + + access(E, F) attachment A for AnyStruct {} + `) errs := RequireCheckerErrors(t, err, 1) @@ -3241,30 +3578,35 @@ func TestCheckAttachmentEntitlementAccessAnnotation(t *testing.T) { t.Run("mapping allowed in contract", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - contract C { - entitlement X - entitlement Y - entitlement mapping E { - X -> Y - } - access(E) attachment A for AnyStruct { - access(Y) fun foo() {} - } - } - `) + contract C { + entitlement X + + entitlement Y + + entitlement mapping E { + X -> Y + } + access(E) attachment A for AnyStruct { + access(Y) fun foo() {} + } + } + `) assert.NoError(t, err) }) t.Run("entitlement set not allowed in contract", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - contract C { - entitlement E - access(E) attachment A for AnyStruct {} - } - `) + contract C { + entitlement E + + access(E) attachment A for AnyStruct {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -3280,39 +3622,40 @@ func TestCheckEntitlementSetAccess(t *testing.T) { runTest := func(refType string, memberName string, valid bool) { t.Run(fmt.Sprintf("%s on %s", memberName, refType), func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, fmt.Sprintf(` - entitlement X - entitlement Y - entitlement Z - struct R { - access(all) fun p() {} + _, err := ParseAndCheck(t, fmt.Sprintf(` + entitlement X + entitlement Y + entitlement Z - access(X) fun x() {} - access(Y) fun y() {} - access(Z) fun z() {} + struct R { + access(all) fun p() {} - access(X, Y) fun xy() {} - access(Y, Z) fun yz() {} - access(X, Z) fun xz() {} - - access(X, Y, Z) fun xyz() {} + access(X) fun x() {} + access(Y) fun y() {} + access(Z) fun z() {} - access(X | Y) fun xyOr() {} - access(Y | Z) fun yzOr() {} - access(X | Z) fun xzOr() {} + access(X, Y) fun xy() {} + access(Y, Z) fun yz() {} + access(X, Z) fun xz() {} - access(X | Y | Z) fun xyzOr() {} + access(X, Y, Z) fun xyz() {} - access(self) fun private() {} - access(contract) fun c() {} - access(account) fun a() {} - } + access(X | Y) fun xyOr() {} + access(Y | Z) fun yzOr() {} + access(X | Z) fun xzOr() {} - fun test(ref: %s) { - ref.%s() - } - `, refType, memberName)) + access(X | Y | Z) fun xyzOr() {} + + access(self) fun private() {} + access(contract) fun c() {} + access(account) fun a() {} + } + + fun test(ref: %s) { + ref.%s() + } + `, refType, memberName)) if valid { assert.NoError(t, err) @@ -3422,121 +3765,127 @@ func TestCheckEntitlementSetAccess(t *testing.T) { func TestCheckEntitlementMapAccess(t *testing.T) { t.Parallel() + t.Run("basic", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M { - X -> Y - } - struct Q { - access(Y) fun foo() {} - } - struct interface S { - access(M) let x: auth(M) &Q - } - fun foo(s: auth(X) &{S}) { - s.x.foo() - } - `) + entitlement X + entitlement Y + entitlement mapping M { + X -> Y + } + struct Q { + access(Y) fun foo() {} + } + struct interface S { + access(M) let x: auth(M) &Q + } + fun foo(s: auth(X) &{S}) { + s.x.foo() + } + `) assert.NoError(t, err) }) t.Run("basic with optional access", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M { - X -> Y - } - struct Q { - access(Y) fun foo() {} - } - struct interface S { - access(M) let x: auth(M) &Q - } - fun foo(s: auth(X) &{S}?) { - s?.x?.foo() - } - `) + entitlement X + entitlement Y + entitlement mapping M { + X -> Y + } + struct Q { + access(Y) fun foo() {} + } + struct interface S { + access(M) let x: auth(M) &Q + } + fun foo(s: auth(X) &{S}?) { + s?.x?.foo() + } + `) assert.NoError(t, err) }) t.Run("basic with optional access return", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M { - X -> Y - } - struct Q {} - struct interface S { - access(M) let x: auth(M) &Q - } - fun foo(s: auth(X) &{S}?): auth(Y) &Q? { - return s?.x - } - `) + entitlement X + entitlement Y + entitlement mapping M { + X -> Y + } + struct Q {} + struct interface S { + access(M) let x: auth(M) &Q + } + fun foo(s: auth(X) &{S}?): auth(Y) &Q? { + return s?.x + } + `) assert.NoError(t, err) }) t.Run("basic with optional full entitled map", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement E - entitlement F - entitlement mapping M { - X -> Y - E -> F - } - struct S { - access(M) let foo: auth(M) &Int - init() { - self.foo = &3 as auth(F, Y) &Int - } - } - fun test(): &Int { - let s: S? = S() - let i: auth(F, Y) &Int? = s?.foo - return i! - } - `) + entitlement X + entitlement Y + entitlement E + entitlement F + entitlement mapping M { + X -> Y + E -> F + } + struct S { + access(M) let foo: auth(M) &Int + init() { + self.foo = &3 as auth(F, Y) &Int + } + } + fun test(): &Int { + let s: S? = S() + let i: auth(F, Y) &Int? = s?.foo + return i! + } + `) assert.NoError(t, err) }) t.Run("basic with optional partial map", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement E - entitlement F - entitlement mapping M { - X -> Y - E -> F - } - struct S { - access(M) let foo: auth(M) &Int - init() { - self.foo = &3 as auth(F, Y) &Int - } - } - fun test(): &Int { - let s = S() - let ref = &s as auth(X) &S? - let i: auth(F, Y) &Int? = ref?.foo - return i! - } - `) + entitlement X + entitlement Y + entitlement E + entitlement F + entitlement mapping M { + X -> Y + E -> F + } + struct S { + access(M) let foo: auth(M) &Int + init() { + self.foo = &3 as auth(F, Y) &Int + } + } + fun test(): &Int { + let s = S() + let ref = &s as auth(X) &S? + let i: auth(F, Y) &Int? = ref?.foo + return i! + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -3552,24 +3901,25 @@ func TestCheckEntitlementMapAccess(t *testing.T) { t.Run("basic with optional function call return invalid", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement E - entitlement F - entitlement mapping M { - X -> Y - E -> F - } - struct S { - access(M) fun foo(): auth(M) &Int { - return &1 as auth(M) &Int - } - } - fun foo(s: auth(X) &S?): auth(X, Y) &Int? { - return s?.foo() - } - `) + entitlement X + entitlement Y + entitlement E + entitlement F + entitlement mapping M { + X -> Y + E -> F + } + struct S { + access(M) fun foo(): auth(M) &Int { + return &1 as auth(M) &Int + } + } + fun foo(s: auth(X) &S?): auth(X, Y) &Int? { + return s?.foo() + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -3580,23 +3930,24 @@ func TestCheckEntitlementMapAccess(t *testing.T) { t.Run("multiple outputs", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement E - entitlement F - entitlement mapping M { - X -> Y - E -> F - } - struct interface S { - access(M) let x: auth(M) &Int - } - fun foo(ref: auth(X | E) &{S}) { - let x: auth(Y | F) &Int = ref.x - let x2: auth(Y, F) &Int = ref.x - } - `) + entitlement X + entitlement Y + entitlement E + entitlement F + entitlement mapping M { + X -> Y + E -> F + } + struct interface S { + access(M) let x: auth(M) &Int + } + fun foo(ref: auth(X | E) &{S}) { + let x: auth(Y | F) &Int = ref.x + let x2: auth(Y, F) &Int = ref.x + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -3607,38 +3958,40 @@ func TestCheckEntitlementMapAccess(t *testing.T) { t.Run("optional", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M { - X -> Y - } - struct interface S { - access(M) let x: auth(M) &Int? - } - fun foo(ref: auth(X) &{S}) { - let x: auth(Y) &Int? = ref.x - } - `) + entitlement X + entitlement Y + entitlement mapping M { + X -> Y + } + struct interface S { + access(M) let x: auth(M) &Int? + } + fun foo(ref: auth(X) &{S}) { + let x: auth(Y) &Int? = ref.x + } + `) assert.NoError(t, err) }) t.Run("do not retain entitlements", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M { - X -> Y - } - struct interface S { - access(M) let x: auth(M) &Int - } - fun foo(ref: auth(X) &{S}) { - let x: auth(X) &Int = ref.x - } - `) + entitlement X + entitlement Y + entitlement mapping M { + X -> Y + } + struct interface S { + access(M) let x: auth(M) &Int + } + fun foo(ref: auth(X) &{S}) { + let x: auth(X) &Int = ref.x + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -3650,22 +4003,23 @@ func TestCheckEntitlementMapAccess(t *testing.T) { t.Run("different views", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement A - entitlement B - entitlement mapping M { - X -> Y - A -> B - } - struct interface S { - access(M) let x: auth(M) &Int - } - fun foo(ref: auth(A) &{S}) { - let x: auth(Y) &Int = ref.x - } - `) + entitlement X + entitlement Y + entitlement A + entitlement B + entitlement mapping M { + X -> Y + A -> B + } + struct interface S { + access(M) let x: auth(M) &Int + } + fun foo(ref: auth(A) &{S}) { + let x: auth(Y) &Int = ref.x + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -3677,46 +4031,48 @@ func TestCheckEntitlementMapAccess(t *testing.T) { t.Run("safe disjoint", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement A - entitlement B - entitlement mapping M { - X -> Y - A -> B - } - struct interface S { - access(M) let x: auth(M) &Int - } - fun foo(ref: auth(A | X) &{S}) { - let x: auth(B | Y) &Int = ref.x - } - `) + entitlement X + entitlement Y + entitlement A + entitlement B + entitlement mapping M { + X -> Y + A -> B + } + struct interface S { + access(M) let x: auth(M) &Int + } + fun foo(ref: auth(A | X) &{S}) { + let x: auth(B | Y) &Int = ref.x + } + `) assert.NoError(t, err) }) t.Run("unrepresentable disjoint", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement A - entitlement B - entitlement C - entitlement mapping M { - X -> Y - X -> C - A -> B - } - struct interface S { - access(M) let x: auth(M) &Int - } - fun foo(ref: auth(A | X) &{S}) { - let x = ref.x - } - `) + entitlement X + entitlement Y + entitlement A + entitlement B + entitlement C + entitlement mapping M { + X -> Y + X -> C + A -> B + } + struct interface S { + access(M) let x: auth(M) &Int + } + fun foo(ref: auth(A | X) &{S}) { + let x = ref.x + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -3725,24 +4081,25 @@ func TestCheckEntitlementMapAccess(t *testing.T) { t.Run("unrepresentable disjoint with dedup", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement A - entitlement B - entitlement mapping M { - X -> Y - X -> B - A -> B - A -> Y - } - struct interface S { - access(M) let x: auth(M) &Int - } - fun foo(ref: auth(A | X) &{S}) { - let x = ref.x - } - `) + entitlement X + entitlement Y + entitlement A + entitlement B + entitlement mapping M { + X -> Y + X -> B + A -> B + A -> Y + } + struct interface S { + access(M) let x: auth(M) &Int + } + fun foo(ref: auth(A | X) &{S}) { + let x = ref.x + } + `) // theoretically this should be allowed, because ((Y & B) | (Y & B)) simplifies to // just (Y & B), but this would require us to build in a simplifier for boolean expressions, @@ -3754,43 +4111,45 @@ func TestCheckEntitlementMapAccess(t *testing.T) { t.Run("multiple output", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement mapping M { - X -> Y - X -> Z - } - struct interface S { - access(M) let x: auth(M) &Int - } - fun foo(ref: auth(X) &{S}) { - let x: auth(Y, Z) &Int = ref.x - } - `) + entitlement X + entitlement Y + entitlement Z + entitlement mapping M { + X -> Y + X -> Z + } + struct interface S { + access(M) let x: auth(M) &Int + } + fun foo(ref: auth(X) &{S}) { + let x: auth(Y, Z) &Int = ref.x + } + `) assert.NoError(t, err) }) t.Run("unmapped entitlements do not pass through map", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement D - entitlement mapping M { - X -> Y - X -> Z - } - struct interface S { - access(M) let x: auth(M) &Int - } - fun foo(ref: auth(D) &{S}) { - let x1: auth(D) &Int = ref.x - } - `) + entitlement X + entitlement Y + entitlement Z + entitlement D + entitlement mapping M { + X -> Y + X -> Z + } + struct interface S { + access(M) let x: auth(M) &Int + } + fun foo(ref: auth(D) &{S}) { + let x1: auth(D) &Int = ref.x + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -3802,101 +4161,105 @@ func TestCheckEntitlementMapAccess(t *testing.T) { t.Run("multiple output with upcasting", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement mapping M { - X -> Y - X -> Z - } - struct interface S { - access(M) let x: auth(M) &Int - } - fun foo(ref: auth(X) &{S}) { - let x: auth(Z) &Int = ref.x - } - `) + + _, err := ParseAndCheck(t, ` + entitlement X + entitlement Y + entitlement Z + entitlement mapping M { + X -> Y + X -> Z + } + struct interface S { + access(M) let x: auth(M) &Int + } + fun foo(ref: auth(X) &{S}) { + let x: auth(Z) &Int = ref.x + } + `) assert.NoError(t, err) }) t.Run("multiple inputs", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement A - entitlement B - entitlement C - entitlement X - entitlement Y - entitlement Z - entitlement mapping M { - A -> C - B -> C - } - struct interface S { - access(M) let x: auth(M) &Int - } - fun foo(ref1: auth(A) &{S}, ref2: auth(B) &{S}) { - let x1: auth(C) &Int = ref1.x - let x2: auth(C) &Int = ref2.x - } - `) + entitlement A + entitlement B + entitlement C + entitlement X + entitlement Y + entitlement Z + entitlement mapping M { + A -> C + B -> C + } + struct interface S { + access(M) let x: auth(M) &Int + } + fun foo(ref1: auth(A) &{S}, ref2: auth(B) &{S}) { + let x1: auth(C) &Int = ref1.x + let x2: auth(C) &Int = ref2.x + } + `) assert.NoError(t, err) }) t.Run("multiple inputs and outputs", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement A - entitlement B - entitlement C - entitlement X - entitlement Y - entitlement Z - entitlement mapping M { - A -> B - A -> C - X -> Y - X -> Z - } - struct interface S { - access(M) let x: auth(M) &Int - } - fun foo(ref: auth(A, X) &{S}) { - let x: auth(B, C, Y, Z) &Int = ref.x - let upRef = ref as auth(A) &{S} - let upX: auth(B, C) &Int = upRef.x - } - `) + entitlement A + entitlement B + entitlement C + entitlement X + entitlement Y + entitlement Z + entitlement mapping M { + A -> B + A -> C + X -> Y + X -> Z + } + struct interface S { + access(M) let x: auth(M) &Int + } + fun foo(ref: auth(A, X) &{S}) { + let x: auth(B, C, Y, Z) &Int = ref.x + let upRef = ref as auth(A) &{S} + let upX: auth(B, C) &Int = upRef.x + } + `) assert.NoError(t, err) }) t.Run("multiple inputs and outputs mismatch", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement A - entitlement B - entitlement C - entitlement X - entitlement Y - entitlement Z - entitlement mapping M { - A -> B - A -> C - X -> Y - X -> Z - } - struct interface S { - access(M) let x: auth(M) &Int - } - fun foo(ref: auth(A, X) &{S}) { - let upRef = ref as auth(A) &{S} - let upX: auth(X, Y) &Int = upRef.x - } - `) + entitlement A + entitlement B + entitlement C + entitlement X + entitlement Y + entitlement Z + entitlement mapping M { + A -> B + A -> C + X -> Y + X -> Z + } + struct interface S { + access(M) let x: auth(M) &Int + } + fun foo(ref: auth(A, X) &{S}) { + let upRef = ref as auth(A) &{S} + let upX: auth(X, Y) &Int = upRef.x + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -3908,38 +4271,40 @@ func TestCheckEntitlementMapAccess(t *testing.T) { t.Run("unauthorized", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M { - X -> Y - } - struct interface S { - access(M) let x: auth(M) &Int - } - fun foo(ref: &{S}) { - let x: &Int = ref.x - } - `) + entitlement X + entitlement Y + entitlement mapping M { + X -> Y + } + struct interface S { + access(M) let x: auth(M) &Int + } + fun foo(ref: &{S}) { + let x: &Int = ref.x + } + `) assert.NoError(t, err) }) t.Run("unauthorized downcast", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M { - X -> Y - } - struct interface S { - access(M) let x: auth(M) &Int - } - fun foo(ref: &{S}) { - let x: auth(Y) &Int = ref.x - } - `) + entitlement X + entitlement Y + entitlement mapping M { + X -> Y + } + struct interface S { + access(M) let x: auth(M) &Int + } + fun foo(ref: &{S}) { + let x: auth(Y) &Int = ref.x + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -3951,71 +4316,74 @@ func TestCheckEntitlementMapAccess(t *testing.T) { t.Run("basic with init", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement mapping M { - X -> Y - X -> Z - } - struct S { - access(M) let x: auth(M) &Int - init() { - self.x = &1 as auth(Y, Z) &Int - } - } - let ref = &S() as auth(X) &S - let x = ref.x - `) + entitlement X + entitlement Y + entitlement Z + entitlement mapping M { + X -> Y + X -> Z + } + struct S { + access(M) let x: auth(M) &Int + init() { + self.x = &1 as auth(Y, Z) &Int + } + } + let ref = &S() as auth(X) &S + let x = ref.x + `) assert.NoError(t, err) }) t.Run("basic with update", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement mapping M { - X -> Y - X -> Z - } - struct S { - access(M) var x: auth(M) &Int - init() { - self.x = &1 as auth(Y, Z) &Int - } - fun updateX(x: auth(Y, Z) &Int) { - self.x = x - } - } - `) + entitlement X + entitlement Y + entitlement Z + entitlement mapping M { + X -> Y + X -> Z + } + struct S { + access(M) var x: auth(M) &Int + init() { + self.x = &1 as auth(Y, Z) &Int + } + fun updateX(x: auth(Y, Z) &Int) { + self.x = x + } + } + `) assert.NoError(t, err) }) t.Run("basic with update error", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement mapping M { - X -> Y - X -> Z - } - struct S { - access(M) var x: auth(M) &Int - init() { - self.x = &1 as auth(Y, Z) &Int - } - fun updateX(x: auth(Z) &Int) { - self.x = x - } - } - `) + entitlement X + entitlement Y + entitlement Z + entitlement mapping M { + X -> Y + X -> Z + } + struct S { + access(M) var x: auth(M) &Int + init() { + self.x = &1 as auth(Y, Z) &Int + } + fun updateX(x: auth(Z) &Int) { + self.x = x + } + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -4025,21 +4393,22 @@ func TestCheckEntitlementMapAccess(t *testing.T) { t.Run("basic with unauthorized init", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M { - X -> Y - } - struct S { - access(M) let x: auth(M) &Int - init() { - self.x = &1 as &Int - } - } - let ref = &S() as auth(X) &S - let x = ref.x - `) + entitlement X + entitlement Y + entitlement mapping M { + X -> Y + } + struct S { + access(M) let x: auth(M) &Int + init() { + self.x = &1 as &Int + } + } + let ref = &S() as auth(X) &S + let x = ref.x + `) errs := RequireCheckerErrors(t, err, 1) @@ -4049,23 +4418,24 @@ func TestCheckEntitlementMapAccess(t *testing.T) { t.Run("basic with underauthorized init", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement mapping M { - X -> Y - X -> Z - } - struct S { - access(M) let x: auth(M) &Int - init() { - self.x = &1 as auth(Y) &Int - } - } - let ref = &S() as auth(X) &S - let x = ref.x - `) + entitlement X + entitlement Y + entitlement Z + entitlement mapping M { + X -> Y + X -> Z + } + struct S { + access(M) let x: auth(M) &Int + init() { + self.x = &1 as auth(Y) &Int + } + } + let ref = &S() as auth(X) &S + let x = ref.x + `) errs := RequireCheckerErrors(t, err, 1) @@ -4075,23 +4445,24 @@ func TestCheckEntitlementMapAccess(t *testing.T) { t.Run("basic with underauthorized disjunction init", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement mapping M { - X -> Y - X -> Z - } - struct S { - access(M) let x: auth(M) &Int - init() { - self.x = (&1 as auth(Y) &Int) as auth(Y | Z) &Int - } - } - let ref = &S() as auth(X) &S - let x = ref.x - `) + entitlement X + entitlement Y + entitlement Z + entitlement mapping M { + X -> Y + X -> Z + } + struct S { + access(M) let x: auth(M) &Int + init() { + self.x = (&1 as auth(Y) &Int) as auth(Y | Z) &Int + } + } + let ref = &S() as auth(X) &S + let x = ref.x + `) errs := RequireCheckerErrors(t, err, 1) @@ -4101,23 +4472,24 @@ func TestCheckEntitlementMapAccess(t *testing.T) { t.Run("basic with non-reference init", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement mapping M { - X -> Y - X -> Z - } - struct S { - access(M) let x: auth(M) &Int - init() { - self.x = 1 - } - } - let ref = &S() as auth(X) &S - let x = ref.x - `) + entitlement X + entitlement Y + entitlement Z + entitlement mapping M { + X -> Y + X -> Z + } + struct S { + access(M) let x: auth(M) &Int + init() { + self.x = 1 + } + } + let ref = &S() as auth(X) &S + let x = ref.x + `) errs := RequireCheckerErrors(t, err, 1) @@ -4129,26 +4501,28 @@ func TestCheckEntitlementMapAccess(t *testing.T) { func TestCheckAttachmentEntitlements(t *testing.T) { t.Parallel() + t.Run("basic", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M { - X -> Y - } - struct S {} - access(M) attachment A for S { - access(Y) fun entitled() { - let a: auth(Y) &A = self - let b: &S = base - } - access(all) fun unentitled() { - let a: auth(X, Y) &A = self // err - let b: auth(X) &S = base // err - } - } - `) + entitlement X + entitlement Y + entitlement mapping M { + X -> Y + } + struct S {} + access(M) attachment A for S { + access(Y) fun entitled() { + let a: auth(Y) &A = self + let b: &S = base + } + access(all) fun unentitled() { + let a: auth(X, Y) &A = self // err + let b: auth(X) &S = base // err + } + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -4162,23 +4536,24 @@ func TestCheckAttachmentEntitlements(t *testing.T) { t.Run("base type with too few requirements", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M { - X -> Y - } - struct S {} - access(M) attachment A for S { - require entitlement X - access(all) fun unentitled() { - let b: &S = base - } - access(all) fun entitled() { - let b: auth(X, Y) &S = base - } - } - `) + entitlement X + entitlement Y + entitlement mapping M { + X -> Y + } + struct S {} + access(M) attachment A for S { + require entitlement X + access(all) fun unentitled() { + let b: &S = base + } + access(all) fun entitled() { + let b: auth(X, Y) &S = base + } + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -4189,22 +4564,23 @@ func TestCheckAttachmentEntitlements(t *testing.T) { t.Run("base type with no requirements", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M { - X -> Y - } - struct S {} - access(M) attachment A for S { - access(all) fun unentitled() { - let b: &S = base - } - access(all) fun entitled() { - let b: auth(X) &S = base - } - } - `) + entitlement X + entitlement Y + entitlement mapping M { + X -> Y + } + struct S {} + access(M) attachment A for S { + access(all) fun unentitled() { + let b: &S = base + } + access(all) fun entitled() { + let b: auth(X) &S = base + } + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -4215,51 +4591,53 @@ func TestCheckAttachmentEntitlements(t *testing.T) { t.Run("base type", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M { - X -> Y - } - struct S {} - access(M) attachment A for S { - require entitlement X - require entitlement Y - access(all) fun unentitled() { - let b: &S = base - } - access(all) fun entitled() { - let b: auth(X, Y) &S = base - } - } - `) + entitlement X + entitlement Y + entitlement mapping M { + X -> Y + } + struct S {} + access(M) attachment A for S { + require entitlement X + require entitlement Y + access(all) fun unentitled() { + let b: &S = base + } + access(all) fun entitled() { + let b: auth(X, Y) &S = base + } + } + `) assert.NoError(t, err) }) t.Run("multiple mappings", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement E - entitlement F - entitlement mapping M { - X -> Y - E -> F - } - struct S { - access(E, X) fun foo() {} - } - access(M) attachment A for S { - access(F, Y) fun entitled() { - let a: auth(F, Y) &A = self - } - access(all) fun unentitled() { - let a: auth(F, Y, E) &A = self // err - } - } - `) + entitlement X + entitlement Y + entitlement E + entitlement F + entitlement mapping M { + X -> Y + E -> F + } + struct S { + access(E, X) fun foo() {} + } + access(M) attachment A for S { + access(F, Y) fun entitled() { + let a: auth(F, Y) &A = self + } + access(all) fun unentitled() { + let a: auth(F, Y, E) &A = self // err + } + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -4270,20 +4648,21 @@ func TestCheckAttachmentEntitlements(t *testing.T) { t.Run("missing in codomain", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement E - entitlement mapping M { - X -> Y - X -> Z - } - struct S {} - access(M) attachment A for S { - access(E) fun entitled() {} - } - `) + entitlement X + entitlement Y + entitlement Z + entitlement E + entitlement mapping M { + X -> Y + X -> Z + } + struct S {} + access(M) attachment A for S { + access(E) fun entitled() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -4293,20 +4672,21 @@ func TestCheckAttachmentEntitlements(t *testing.T) { t.Run("missing in codomain in set", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement E - entitlement mapping M { - X -> Y - X -> Z - } - struct S {} - access(M) attachment A for S { - access(Y | E | Z) fun entitled() {} - } - `) + entitlement X + entitlement Y + entitlement Z + entitlement E + entitlement mapping M { + X -> Y + X -> Z + } + struct S {} + access(M) attachment A for S { + access(Y | E | Z) fun entitled() {} + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -4316,18 +4696,19 @@ func TestCheckAttachmentEntitlements(t *testing.T) { t.Run("multiple missing in codomain", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement E - entitlement F - entitlement mapping M { - E -> F - } - struct S {} - access(M) attachment A for S { - access(F, X, E) fun entitled() {} - } - `) + entitlement X + entitlement E + entitlement F + entitlement mapping M { + E -> F + } + struct S {} + access(M) attachment A for S { + access(F, X, E) fun entitled() {} + } + `) errs := RequireCheckerErrors(t, err, 2) @@ -4339,44 +4720,46 @@ func TestCheckAttachmentEntitlements(t *testing.T) { t.Run("mapped field", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M { - X -> Y - } - struct S { - access(Y) fun foo() {} - } - access(M) attachment A for S { - access(M) let x: auth(M) &S - init() { - self.x = &S() as auth(Y) &S - } - } - `) + entitlement X + entitlement Y + entitlement mapping M { + X -> Y + } + struct S { + access(Y) fun foo() {} + } + access(M) attachment A for S { + access(M) let x: auth(M) &S + init() { + self.x = &S() as auth(Y) &S + } + } + `) assert.NoError(t, err) }) t.Run("access(all) decl", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - struct S {} - attachment A for S { - access(Y) fun entitled() {} - access(Y) let entitledField: Int - access(all) fun unentitled() { - let a: auth(Y) &A = self // err - let b: auth(X) &S = base // err - } - init() { - self.entitledField = 3 - } - } - `) + entitlement X + entitlement Y + struct S {} + attachment A for S { + access(Y) fun entitled() {} + access(Y) let entitledField: Int + access(all) fun unentitled() { + let a: auth(Y) &A = self // err + let b: auth(X) &S = base // err + } + init() { + self.entitledField = 3 + } + } + `) errs := RequireCheckerErrors(t, err, 4) @@ -4392,14 +4775,15 @@ func TestCheckAttachmentEntitlements(t *testing.T) { t.Run("non mapped entitlement decl", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - struct S {} - access(X) attachment A for S { - - } - `) + entitlement X + entitlement Y + struct S {} + access(X) attachment A for S { + + } + `) errs := RequireCheckerErrors(t, err, 1) require.IsType(t, &sema.InvalidEntitlementAccessError{}, errs[0]) @@ -4410,76 +4794,80 @@ func TestCheckAttachmentEntitlements(t *testing.T) { func TestCheckAttachmentAccessEntitlements(t *testing.T) { t.Parallel() + t.Run("basic owned fully entitled", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement mapping M { - X -> Y - X -> Z - } - struct S {} - access(M) attachment A for S { - access(Y, Z) fun foo() {} - } - let s = attach A() to S() - let a: auth(Y, Z) &A = s[A]! - `) + entitlement X + entitlement Y + entitlement Z + entitlement mapping M { + X -> Y + X -> Z + } + struct S {} + access(M) attachment A for S { + access(Y, Z) fun foo() {} + } + let s = attach A() to S() + let a: auth(Y, Z) &A = s[A]! + `) assert.NoError(t, err) }) t.Run("basic owned intersection fully entitled", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement mapping M { - X -> Y - X -> Z - } - struct interface I {} - struct S: I {} - access(M) attachment A for I { - access(Y, Z) fun foo() {} - } - let s: {I} = attach A() to S() - let a: auth(Y, Z) &A = s[A]! - `) + entitlement X + entitlement Y + entitlement Z + entitlement mapping M { + X -> Y + X -> Z + } + struct interface I {} + struct S: I {} + access(M) attachment A for I { + access(Y, Z) fun foo() {} + } + let s: {I} = attach A() to S() + let a: auth(Y, Z) &A = s[A]! + `) assert.NoError(t, err) }) t.Run("basic reference mapping", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement E - entitlement F - entitlement mapping M { - X -> Y - E -> F - } - struct S { - access(X, E) fun foo() {} - } - access(M) attachment A for S { - access(Y, F) fun foo() {} - } - let s = attach A() to S() - let yRef = &s as auth(X) &S - let fRef = &s as auth(E) &S - let bothRef = &s as auth(X, E) &S - let a1: auth(Y) &A = yRef[A]! - let a2: auth(F) &A = fRef[A]! - let a3: auth(F) &A = yRef[A]! // err - let a4: auth(Y) &A = fRef[A]! // err - let a5: auth(Y, F) &A = bothRef[A]! - `) + entitlement X + entitlement Y + entitlement E + entitlement F + entitlement mapping M { + X -> Y + E -> F + } + struct S { + access(X, E) fun foo() {} + } + access(M) attachment A for S { + access(Y, F) fun foo() {} + } + let s = attach A() to S() + let yRef = &s as auth(X) &S + let fRef = &s as auth(E) &S + let bothRef = &s as auth(X, E) &S + let a1: auth(Y) &A = yRef[A]! + let a2: auth(F) &A = fRef[A]! + let a3: auth(F) &A = yRef[A]! // err + let a4: auth(Y) &A = fRef[A]! // err + let a5: auth(Y, F) &A = bothRef[A]! + `) errs := RequireCheckerErrors(t, err, 2) @@ -4494,20 +4882,21 @@ func TestCheckAttachmentAccessEntitlements(t *testing.T) { t.Run("access(all) access entitled attachment", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M { - X -> Y - } - struct S {} - access(M) attachment A for S { - access(Y) fun foo() {} - } - let s = attach A() to S() - let ref = &s as &S - let a1: auth(Y) &A = ref[A]! - `) + entitlement X + entitlement Y + entitlement mapping M { + X -> Y + } + struct S {} + access(M) attachment A for S { + access(Y) fun foo() {} + } + let s = attach A() to S() + let ref = &s as &S + let a1: auth(Y) &A = ref[A]! + `) errs := RequireCheckerErrors(t, err, 1) @@ -4518,22 +4907,23 @@ func TestCheckAttachmentAccessEntitlements(t *testing.T) { t.Run("entitled access access(all) attachment", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M { - X -> Y - } - struct S { - access(X) fun foo() {} - } - access(all) attachment A for S { - access(all) fun foo() {} - } - let s = attach A() to S() - let ref = &s as auth(X) &S - let a1: auth(Y) &A = ref[A]! - `) + entitlement X + entitlement Y + entitlement mapping M { + X -> Y + } + struct S { + access(X) fun foo() {} + } + access(all) attachment A for S { + access(all) fun foo() {} + } + let s = attach A() to S() + let ref = &s as auth(X) &S + let a1: auth(Y) &A = ref[A]! + `) errs := RequireCheckerErrors(t, err, 1) @@ -4544,18 +4934,24 @@ func TestCheckAttachmentAccessEntitlements(t *testing.T) { t.Run("access(all) access access(all) attachment", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M { - X -> Y - } - struct S {} - access(all) attachment A for S {} - let s = attach A() to S() - let ref = &s as &S - let a1: auth(Y) &A = ref[A]! - `) + entitlement X + + entitlement Y + + entitlement mapping M { + X -> Y + } + + struct S {} + + access(all) attachment A for S {} + + let s = attach A() to S() + let ref = &s as &S + let a1: auth(Y) &A = ref[A]! + `) errs := RequireCheckerErrors(t, err, 1) @@ -4566,29 +4962,34 @@ func TestCheckAttachmentAccessEntitlements(t *testing.T) { t.Run("unrepresentable access mapping", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement E - entitlement F - entitlement G - entitlement mapping M { - X -> Y - X -> Z - E -> F - E -> G - } - struct S { - access(X, E) fun foo() {} - } - access(M) attachment A for S { - access(Y, Z, F, G) fun foo() {} - } - let s = attach A() to S() - let ref = (&s as auth(X) &S) as auth(X | E) &S - let a1 = ref[A]! - `) + entitlement X + entitlement Y + entitlement Z + entitlement E + entitlement F + entitlement G + + entitlement mapping M { + X -> Y + X -> Z + E -> F + E -> G + } + + struct S { + access(X, E) fun foo() {} + } + + access(M) attachment A for S { + access(Y, Z, F, G) fun foo() {} + } + + let s = attach A() to S() + let ref = (&s as auth(X) &S) as auth(X | E) &S + let a1 = ref[A]! + `) errs := RequireCheckerErrors(t, err, 2) @@ -4602,69 +5003,85 @@ func TestCheckEntitlementConditions(t *testing.T) { t.Run("use of function on owned value", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - struct S { - view access(X) fun foo(): Bool { - return true - } - } - fun bar(r: S) { - pre { - r.foo(): "" - } - post { - r.foo(): "" - } - r.foo() - } - `) + entitlement X + + struct S { + view access(X) fun foo(): Bool { + return true + } + } + + fun bar(r: S) { + pre { + r.foo(): "" + } + post { + r.foo(): "" + } + r.foo() + } + `) assert.NoError(t, err) }) t.Run("use of function on entitled referenced value", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - struct S { - view access(X) fun foo(): Bool { - return true - } - } - fun bar(r: auth(X) &S) { - pre { - r.foo(): "" - } - post { - r.foo(): "" - } - r.foo() - } - `) + entitlement X + + struct S { + view access(X) fun foo(): Bool { + return true + } + } + + fun bar(r: auth(X) &S) { + pre { + r.foo(): "" + } + post { + r.foo(): "" + } + r.foo() + } + `) assert.NoError(t, err) }) t.Run("use of function on unentitled referenced value", func(t *testing.T) { t.Parallel() - checker, err := ParseAndCheckWithOptions(t, ` - entitlement X - struct S { - view access(X) fun foo(): Bool { - return true - } - } - fun bar(r: &S) { - pre { - r.foo(): "" - } - post { - r.foo(): "" - } - r.foo() - } - `, ParseAndCheckOptions{Config: &sema.Config{SuggestionsEnabled: true}}) + + checker, err := ParseAndCheckWithOptions(t, + ` + entitlement X + + struct S { + view access(X) fun foo(): Bool { + return true + } + } + + fun bar(r: &S) { + pre { + r.foo(): "" + } + post { + r.foo(): "" + } + r.foo() + } + `, + ParseAndCheckOptions{ + Config: &sema.Config{ + SuggestionsEnabled: true, + }, + }, + ) errs := RequireCheckerErrors(t, err, 3) require.IsType(t, &sema.InvalidAccessError{}, errs[0]) @@ -4695,40 +5112,53 @@ func TestCheckEntitlementConditions(t *testing.T) { t.Run("result value usage struct", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - struct S { - view access(X) fun foo(): Bool { - return true - } - } - fun bar(r: S): S { - post { - result.foo(): "" - } - return r - } - `) + entitlement X + + struct S { + view access(X) fun foo(): Bool { + return true + } + } + + fun bar(r: S): S { + post { + result.foo(): "" + } + return r + } + `) assert.NoError(t, err) }) t.Run("result value usage reference", func(t *testing.T) { t.Parallel() - checker, err := ParseAndCheckWithOptions(t, ` - entitlement X - struct S { - view access(X) fun foo(): Bool { - return true - } - } - fun bar(r: S): &S { - post { - result.foo(): "" - } - return &r as auth(X) &S - } - `, ParseAndCheckOptions{Config: &sema.Config{SuggestionsEnabled: true}}) + + checker, err := ParseAndCheckWithOptions(t, + ` + entitlement X + + struct S { + view access(X) fun foo(): Bool { + return true + } + } + + fun bar(r: S): &S { + post { + result.foo(): "" + } + return &r as auth(X) &S + } + `, + ParseAndCheckOptions{ + Config: &sema.Config{ + SuggestionsEnabled: true, + }, + }, + ) errs := RequireCheckerErrors(t, err, 1) require.IsType(t, &sema.InvalidAccessError{}, errs[0]) @@ -4756,111 +5186,116 @@ func TestCheckEntitlementConditions(t *testing.T) { t.Run("result value usage reference authorized", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - struct S { - view access(X) fun foo(): Bool { - return true - } - } - fun bar(r: S): auth(X) &S { - post { - result.foo(): "" - } - return &r as auth(X) &S - } - `) + entitlement X + struct S { + view access(X) fun foo(): Bool { + return true + } + } + fun bar(r: S): auth(X) &S { + post { + result.foo(): "" + } + return &r as auth(X) &S + } + `) assert.NoError(t, err) }) t.Run("result value usage resource", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - resource R { - view access(X) fun foo(): Bool { - return true - } - view access(X, Y) fun bar(): Bool { - return true - } - } - fun bar(r: @R): @R { - post { - result.foo(): "" - result.bar(): "" - } - return <-r - } - `) + entitlement X + entitlement Y + resource R { + view access(X) fun foo(): Bool { + return true + } + view access(X, Y) fun bar(): Bool { + return true + } + } + fun bar(r: @R): @R { + post { + result.foo(): "" + result.bar(): "" + } + return <-r + } + `) assert.NoError(t, err) }) t.Run("optional result value usage resource", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - resource R { - view access(X) fun foo(): Bool { - return true - } - view access(X, Y) fun bar(): Bool { - return true - } - } - fun bar(r: @R): @R? { - post { - result?.foo()!: "" - result?.bar()!: "" - } - return <-r - } - `) + entitlement X + entitlement Y + resource R { + view access(X) fun foo(): Bool { + return true + } + view access(X, Y) fun bar(): Bool { + return true + } + } + fun bar(r: @R): @R? { + post { + result?.foo()!: "" + result?.bar()!: "" + } + return <-r + } + `) assert.NoError(t, err) }) t.Run("result value inherited entitlement resource", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - resource interface I { - access(X, Y) view fun foo(): Bool { - return true - } - } - resource R: I {} - fun bar(r: @R): @R { - post { - result.foo(): "" - } - return <-r - } - `) + entitlement X + entitlement Y + resource interface I { + access(X, Y) view fun foo(): Bool { + return true + } + } + resource R: I {} + fun bar(r: @R): @R { + post { + result.foo(): "" + } + return <-r + } + `) assert.NoError(t, err) }) t.Run("result value usage unentitled resource", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - resource R { - view fun foo(): Bool { - return true - } - } - fun bar(r: @R): @R { - post { - result.foo(): "" - } - return <-r - } - `) + resource R { + view fun foo(): Bool { + return true + } + } + fun bar(r: @R): @R { + post { + result.foo(): "" + } + return <-r + } + `) assert.NoError(t, err) }) @@ -4869,20 +5304,20 @@ func TestCheckEntitlementConditions(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` - resource R {} + resource R {} - fun foo(r: @[R]): @[R] { - post { - bar(result): "" - } - return <-r - } + fun foo(r: @[R]): @[R] { + post { + bar(result): "" + } + return <-r + } - // 'result' variable should have all the entitlements available for arrays. - view fun bar(_ r: auth(Mutate, Insert, Remove) &[R]): Bool { - return true - } - `) + // 'result' variable should have all the entitlements available for arrays. + view fun bar(_ r: auth(Mutate, Insert, Remove) &[R]): Bool { + return true + } + `) assert.NoError(t, err) }) @@ -4891,20 +5326,20 @@ func TestCheckEntitlementConditions(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` - resource R {} + resource R {} - fun foo(r: @[R; 5]): @[R; 5] { - post { - bar(result): "" - } - return <-r - } + fun foo(r: @[R; 5]): @[R; 5] { + post { + bar(result): "" + } + return <-r + } - // 'result' variable should have all the entitlements available for arrays. - view fun bar(_ r: auth(Mutate, Insert, Remove) &[R; 5]): Bool { - return true - } - `) + // 'result' variable should have all the entitlements available for arrays. + view fun bar(_ r: auth(Mutate, Insert, Remove) &[R; 5]): Bool { + return true + } + `) assert.NoError(t, err) }) @@ -4913,20 +5348,20 @@ func TestCheckEntitlementConditions(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` - resource R {} + resource R {} - fun foo(r: @{String:R}): @{String:R} { - post { - bar(result): "" - } - return <-r - } + fun foo(r: @{String:R}): @{String:R} { + post { + bar(result): "" + } + return <-r + } - // 'result' variable should have all the entitlements available for dictionaries. - view fun bar(_ r: auth(Mutate, Insert, Remove) &{String:R}): Bool { - return true - } - `) + // 'result' variable should have all the entitlements available for dictionaries. + view fun bar(_ r: auth(Mutate, Insert, Remove) &{String:R}): Bool { + return true + } + `) assert.NoError(t, err) }) @@ -4938,19 +5373,20 @@ func TestCheckEntitledWriteAndMutateNotAllowed(t *testing.T) { t.Run("basic owned", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - struct S { - access(E) var x: Int - init() { - self.x = 1 - } - } - fun foo() { - let s = S() - s.x = 3 - } - `) + entitlement E + struct S { + access(E) var x: Int + init() { + self.x = 1 + } + } + fun foo() { + let s = S() + s.x = 3 + } + `) errs := RequireCheckerErrors(t, err, 1) require.IsType(t, &sema.InvalidAssignmentAccessError{}, errs[0]) @@ -4958,20 +5394,21 @@ func TestCheckEntitledWriteAndMutateNotAllowed(t *testing.T) { t.Run("basic authorized", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - struct S { - access(E) var x: Int - init() { - self.x = 1 - } - } - fun foo() { - let s = S() - let ref = &s as auth(E) &S - ref.x = 3 - } - `) + entitlement E + struct S { + access(E) var x: Int + init() { + self.x = 1 + } + } + fun foo() { + let s = S() + let ref = &s as auth(E) &S + ref.x = 3 + } + `) errs := RequireCheckerErrors(t, err, 1) require.IsType(t, &sema.InvalidAssignmentAccessError{}, errs[0]) @@ -4979,23 +5416,24 @@ func TestCheckEntitledWriteAndMutateNotAllowed(t *testing.T) { t.Run("mapped owned", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M { - X -> Y - } - struct S { - access(M) var x: auth(M) &Int - init() { - self.x = &1 as auth(Y) &Int - } - } - fun foo() { - let s = S() - s.x = &1 as auth(Y) &Int - } - `) + entitlement X + entitlement Y + entitlement mapping M { + X -> Y + } + struct S { + access(M) var x: auth(M) &Int + init() { + self.x = &1 as auth(Y) &Int + } + } + fun foo() { + let s = S() + s.x = &1 as auth(Y) &Int + } + `) errs := RequireCheckerErrors(t, err, 1) require.IsType(t, &sema.InvalidAssignmentAccessError{}, errs[0]) @@ -5003,24 +5441,25 @@ func TestCheckEntitledWriteAndMutateNotAllowed(t *testing.T) { t.Run("mapped authorized", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement X - entitlement Y - entitlement mapping M { - X -> Y - } - struct S { - access(M) var x: auth(M) &Int - init() { - self.x = &1 as auth(Y) &Int - } - } - fun foo() { - let s = S() - let ref = &s as auth(X) &S - ref.x = &1 as auth(Y) &Int - } - `) + entitlement X + entitlement Y + entitlement mapping M { + X -> Y + } + struct S { + access(M) var x: auth(M) &Int + init() { + self.x = &1 as auth(Y) &Int + } + } + fun foo() { + let s = S() + let ref = &s as auth(X) &S + ref.x = &1 as auth(Y) &Int + } + `) errs := RequireCheckerErrors(t, err, 1) require.IsType(t, &sema.InvalidAssignmentAccessError{}, errs[0]) @@ -5028,39 +5467,50 @@ func TestCheckEntitledWriteAndMutateNotAllowed(t *testing.T) { t.Run("basic mutate", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - struct S { - access(E) var x: [Int] - init() { - self.x = [1] - } - } - fun foo() { - let s = S() - s.x.append(3) - } - `) + entitlement E + struct S { + access(E) var x: [Int] + init() { + self.x = [1] + } + } + fun foo() { + let s = S() + s.x.append(3) + } + `) assert.NoError(t, err) }) t.Run("basic authorized", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckWithOptions(t, ` - entitlement E - struct S { - access(E) var x: [Int] - init() { - self.x = [1] - } - } - fun foo() { - let s = S() - let ref = &s as auth(E) &S - ref.x.append(3) - } - `, ParseAndCheckOptions{Config: &sema.Config{SuggestionsEnabled: true}}) + + _, err := ParseAndCheckWithOptions(t, + ` + entitlement E + + struct S { + access(E) var x: [Int] + init() { + self.x = [1] + } + } + + fun foo() { + let s = S() + let ref = &s as auth(E) &S + ref.x.append(3) + } + `, + ParseAndCheckOptions{ + Config: &sema.Config{ + SuggestionsEnabled: true, + }, + }, + ) errs := RequireCheckerErrors(t, err, 1) require.IsType(t, &sema.InvalidAccessError{}, errs[0]) @@ -5069,8 +5519,8 @@ func TestCheckEntitledWriteAndMutateNotAllowed(t *testing.T) { errs[0].(*sema.InvalidAccessError).RestrictingAccess, sema.NewEntitlementSetAccess( []*sema.EntitlementType{ - sema.InsertEntitlement, - sema.MutateEntitlement, + sema.InsertType, + sema.MutateType, }, sema.Disjunction, ), @@ -5090,30 +5540,33 @@ func TestCheckEntitledWriteAndMutateNotAllowed(t *testing.T) { func TestCheckAttachmentRequireEntitlements(t *testing.T) { t.Parallel() + t.Run("entitlements allowed", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - attachment A for AnyStruct { - require entitlement E - require entitlement F - } - `) + entitlement E + entitlement F + attachment A for AnyStruct { + require entitlement E + require entitlement F + } + `) assert.NoError(t, err) }) t.Run("entitlement mapping disallowed", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement mapping M {} - attachment A for AnyStruct { - require entitlement E - require entitlement M - } - `) + entitlement E + entitlement mapping M {} + attachment A for AnyStruct { + require entitlement E + require entitlement M + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -5122,14 +5575,15 @@ func TestCheckAttachmentRequireEntitlements(t *testing.T) { t.Run("event disallowed", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - event M() - attachment A for AnyStruct { - require entitlement E - require entitlement M - } - `) + entitlement E + event M() + attachment A for AnyStruct { + require entitlement E + require entitlement M + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -5138,14 +5592,15 @@ func TestCheckAttachmentRequireEntitlements(t *testing.T) { t.Run("struct disallowed", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - struct M {} - attachment A for AnyStruct { - require entitlement E - require entitlement M - } - `) + entitlement E + struct M {} + attachment A for AnyStruct { + require entitlement E + require entitlement M + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -5154,14 +5609,15 @@ func TestCheckAttachmentRequireEntitlements(t *testing.T) { t.Run("struct interface disallowed", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - struct interface M {} - attachment A for AnyStruct { - require entitlement E - require entitlement M - } - `) + entitlement E + struct interface M {} + attachment A for AnyStruct { + require entitlement E + require entitlement M + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -5170,14 +5626,15 @@ func TestCheckAttachmentRequireEntitlements(t *testing.T) { t.Run("resource disallowed", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - resource M {} - attachment A for AnyStruct { - require entitlement E - require entitlement M - } - `) + entitlement E + resource M {} + attachment A for AnyStruct { + require entitlement E + require entitlement M + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -5186,14 +5643,15 @@ func TestCheckAttachmentRequireEntitlements(t *testing.T) { t.Run("resource interface disallowed", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - resource interface M {} - attachment A for AnyStruct { - require entitlement E - require entitlement M - } - `) + entitlement E + resource interface M {} + attachment A for AnyStruct { + require entitlement E + require entitlement M + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -5202,14 +5660,15 @@ func TestCheckAttachmentRequireEntitlements(t *testing.T) { t.Run("attachment disallowed", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - attachment M for AnyResource {} - attachment A for AnyStruct { - require entitlement E - require entitlement M - } - `) + entitlement E + attachment M for AnyResource {} + attachment A for AnyStruct { + require entitlement E + require entitlement M + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -5218,14 +5677,15 @@ func TestCheckAttachmentRequireEntitlements(t *testing.T) { t.Run("enum disallowed", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - enum M: UInt8 {} - attachment A for AnyStruct { - require entitlement E - require entitlement M - } - `) + entitlement E + enum M: UInt8 {} + attachment A for AnyStruct { + require entitlement E + require entitlement M + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -5234,13 +5694,14 @@ func TestCheckAttachmentRequireEntitlements(t *testing.T) { t.Run("int disallowed", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - attachment A for AnyStruct { - require entitlement E - require entitlement Int - } - `) + entitlement E + attachment A for AnyStruct { + require entitlement E + require entitlement Int + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -5249,13 +5710,14 @@ func TestCheckAttachmentRequireEntitlements(t *testing.T) { t.Run("duplicates disallowed", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - attachment A for AnyStruct { - require entitlement E - require entitlement E - } - `) + entitlement E + attachment A for AnyStruct { + require entitlement E + require entitlement E + } + `) errs := RequireCheckerErrors(t, err, 1) @@ -5265,58 +5727,62 @@ func TestCheckAttachmentRequireEntitlements(t *testing.T) { func TestCheckAttachProvidedEntitlements(t *testing.T) { t.Parallel() + t.Run("all provided", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - struct S {} - attachment A for S { - require entitlement E - require entitlement F - } - fun foo() { - let s = attach A() to S() with (E, F) - } + entitlement E + entitlement F + struct S {} + attachment A for S { + require entitlement E + require entitlement F + } + fun foo() { + let s = attach A() to S() with (E, F) + } - `) + `) assert.NoError(t, err) }) t.Run("extra provided", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement G - struct S {} - attachment A for S { - require entitlement E - require entitlement F - } - fun foo() { - let s = attach A() to S() with (E, F, G) - } + entitlement E + entitlement F + entitlement G + struct S {} + attachment A for S { + require entitlement E + require entitlement F + } + fun foo() { + let s = attach A() to S() with (E, F, G) + } - `) + `) assert.NoError(t, err) }) t.Run("one missing", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - struct S {} - attachment A for S { - require entitlement E - require entitlement F - } - fun foo() { - let s = attach A() to S() with (E) - } + entitlement E + entitlement F + struct S {} + attachment A for S { + require entitlement E + require entitlement F + } + fun foo() { + let s = attach A() to S() with (E) + } - `) + `) errs := RequireCheckerErrors(t, err, 1) require.IsType(t, &sema.RequiredEntitlementNotProvidedError{}, errs[0]) @@ -5325,20 +5791,21 @@ func TestCheckAttachProvidedEntitlements(t *testing.T) { t.Run("one missing with extra provided", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - entitlement G - struct S {} - attachment A for S { - require entitlement E - require entitlement F - } - fun foo() { - let s = attach A() to S() with (E, G) - } + entitlement E + entitlement F + entitlement G + struct S {} + attachment A for S { + require entitlement E + require entitlement F + } + fun foo() { + let s = attach A() to S() with (E, G) + } - `) + `) errs := RequireCheckerErrors(t, err, 1) require.IsType(t, &sema.RequiredEntitlementNotProvidedError{}, errs[0]) @@ -5347,19 +5814,20 @@ func TestCheckAttachProvidedEntitlements(t *testing.T) { t.Run("two missing", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement F - struct S {} - attachment A for S { - require entitlement E - require entitlement F - } - fun foo() { - let s = attach A() to S() - } + entitlement E + entitlement F + struct S {} + attachment A for S { + require entitlement E + require entitlement F + } + fun foo() { + let s = attach A() to S() + } - `) + `) errs := RequireCheckerErrors(t, err, 2) require.IsType(t, &sema.RequiredEntitlementNotProvidedError{}, errs[0]) @@ -5371,18 +5839,19 @@ func TestCheckAttachProvidedEntitlements(t *testing.T) { t.Run("mapping provided", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - entitlement mapping M {} - struct S {} - attachment A for S { - require entitlement E - } - fun foo() { - let s = attach A() to S() with (M) - } + entitlement E + entitlement mapping M {} + struct S {} + attachment A for S { + require entitlement E + } + fun foo() { + let s = attach A() to S() with (M) + } - `) + `) errs := RequireCheckerErrors(t, err, 2) require.IsType(t, &sema.InvalidNonEntitlementProvidedError{}, errs[0]) @@ -5393,17 +5862,18 @@ func TestCheckAttachProvidedEntitlements(t *testing.T) { t.Run("int provided", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - struct S {} - attachment A for S { - require entitlement E - } - fun foo() { - let s = attach A() to S() with (UInt8) - } + entitlement E + struct S {} + attachment A for S { + require entitlement E + } + fun foo() { + let s = attach A() to S() with (UInt8) + } - `) + `) errs := RequireCheckerErrors(t, err, 2) require.IsType(t, &sema.InvalidNonEntitlementProvidedError{}, errs[0]) @@ -5414,17 +5884,18 @@ func TestCheckAttachProvidedEntitlements(t *testing.T) { t.Run("struct provided", func(t *testing.T) { t.Parallel() + _, err := ParseAndCheck(t, ` - entitlement E - struct S {} - attachment A for S { - require entitlement E - } - fun foo() { - let s = attach A() to S() with (S) - } + entitlement E + struct S {} + attachment A for S { + require entitlement E + } + fun foo() { + let s = attach A() to S() with (S) + } - `) + `) errs := RequireCheckerErrors(t, err, 2) require.IsType(t, &sema.InvalidNonEntitlementProvidedError{}, errs[0]) @@ -6281,22 +6752,22 @@ func TestCheckEntitlementErrorReporting(t *testing.T) { t.Run("three or more conjunction", func(t *testing.T) { t.Parallel() checker, err := ParseAndCheckWithOptions(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement A - entitlement B - - struct S { - view access(X, Y, Z) fun foo(): Bool { - return true - } - } + entitlement X + entitlement Y + entitlement Z + entitlement A + entitlement B + + struct S { + view access(X, Y, Z) fun foo(): Bool { + return true + } + } - fun bar(r: auth(A, B) &S) { - r.foo() - } - `, + fun bar(r: auth(A, B) &S) { + r.foo() + } + `, ParseAndCheckOptions{ Config: &sema.Config{ SuggestionsEnabled: true, @@ -6339,22 +6810,22 @@ func TestCheckEntitlementErrorReporting(t *testing.T) { t.Run("has one entitlement of three", func(t *testing.T) { t.Parallel() checker, err := ParseAndCheckWithOptions(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement A - entitlement B - - struct S { - view access(X, Y, Z) fun foo(): Bool { - return true - } - } + entitlement X + entitlement Y + entitlement Z + entitlement A + entitlement B + + struct S { + view access(X, Y, Z) fun foo(): Bool { + return true + } + } - fun bar(r: auth(A, B, Y) &S) { - r.foo() - } - `, + fun bar(r: auth(A, B, Y) &S) { + r.foo() + } + `, ParseAndCheckOptions{ Config: &sema.Config{ SuggestionsEnabled: true, @@ -6398,22 +6869,22 @@ func TestCheckEntitlementErrorReporting(t *testing.T) { t.Run("has one entitlement of three", func(t *testing.T) { t.Parallel() checker, err := ParseAndCheckWithOptions(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement A - entitlement B - - struct S { - view access(X | Y | Z) fun foo(): Bool { - return true - } - } + entitlement X + entitlement Y + entitlement Z + entitlement A + entitlement B + + struct S { + view access(X | Y | Z) fun foo(): Bool { + return true + } + } - fun bar(r: auth(A, B) &S) { - r.foo() - } - `, + fun bar(r: auth(A, B) &S) { + r.foo() + } + `, ParseAndCheckOptions{ Config: &sema.Config{ SuggestionsEnabled: true, @@ -6456,22 +6927,22 @@ func TestCheckEntitlementErrorReporting(t *testing.T) { t.Run("no suggestion for disjoint possession set", func(t *testing.T) { t.Parallel() checker, err := ParseAndCheckWithOptions(t, ` - entitlement X - entitlement Y - entitlement Z - entitlement A - entitlement B - - struct S { - view access(X | Y | Z) fun foo(): Bool { - return true - } - } + entitlement X + entitlement Y + entitlement Z + entitlement A + entitlement B + + struct S { + view access(X | Y | Z) fun foo(): Bool { + return true + } + } - fun bar(r: auth(A | B) &S) { - r.foo() - } - `, + fun bar(r: auth(A | B) &S) { + r.foo() + } + `, ParseAndCheckOptions{ Config: &sema.Config{ SuggestionsEnabled: true, @@ -6514,19 +6985,19 @@ func TestCheckEntitlementErrorReporting(t *testing.T) { t.Run("no suggestion for self access requirement", func(t *testing.T) { t.Parallel() _, err := ParseAndCheckWithOptions(t, ` - entitlement A - entitlement B - - struct S { - view access(self) fun foo(): Bool { - return true - } - } + entitlement A + entitlement B + + struct S { + view access(self) fun foo(): Bool { + return true + } + } - fun bar(r: auth(A, B) &S) { - r.foo() - } - `, + fun bar(r: auth(A, B) &S) { + r.foo() + } + `, ParseAndCheckOptions{ Config: &sema.Config{ SuggestionsEnabled: true, diff --git a/runtime/tests/checker/entrypoint_test.go b/runtime/tests/checker/entrypoint_test.go index 4bea123456..9fb5798b27 100644 --- a/runtime/tests/checker/entrypoint_test.go +++ b/runtime/tests/checker/entrypoint_test.go @@ -26,7 +26,7 @@ import ( "github.com/onflow/cadence/runtime/sema" ) -func TestEntryPointParameters(t *testing.T) { +func TestCheckEntryPointParameters(t *testing.T) { t.Parallel() diff --git a/runtime/tests/checker/events_test.go b/runtime/tests/checker/events_test.go index 887bfb0578..62d6428648 100644 --- a/runtime/tests/checker/events_test.go +++ b/runtime/tests/checker/events_test.go @@ -297,30 +297,12 @@ func TestCheckAccountEventParameter(t *testing.T) { t.Parallel() - t.Run("AuthAccount", func(t *testing.T) { - - t.Parallel() - - _, err := ParseAndCheck(t, ` - contract Test { - event Account(account: AuthAccount) - } - `) - require.NoError(t, err) - }) - - t.Run("PublicAccount", func(t *testing.T) { - - t.Parallel() - - _, err := ParseAndCheck(t, ` - contract Test { - event Account(account: PublicAccount) - } - `) - require.NoError(t, err) - }) - + _, err := ParseAndCheck(t, ` + contract Test { + event AccountEvent(account: &Account) + } + `) + require.NoError(t, err) } func TestCheckDeclareEventInInterface(t *testing.T) { diff --git a/runtime/tests/checker/interface_test.go b/runtime/tests/checker/interface_test.go index 8d99d7c8d6..3fcd079df7 100644 --- a/runtime/tests/checker/interface_test.go +++ b/runtime/tests/checker/interface_test.go @@ -1987,7 +1987,7 @@ func TestCheckInterfaceDefaultImplementationOverriden(t *testing.T) { }) } -func TestSpecialFunctionDefaultImplementationUsage(t *testing.T) { +func TestCheckSpecialFunctionDefaultImplementationUsage(t *testing.T) { t.Parallel() @@ -3449,7 +3449,7 @@ func TestCheckInterfaceTypeDefinitionInheritance(t *testing.T) { } -func TestInheritedInterfaceMembers(t *testing.T) { +func TestCheckInheritedInterfaceMembers(t *testing.T) { t.Parallel() t.Run("inherited interface field", func(t *testing.T) { @@ -3808,7 +3808,7 @@ func TestCheckInheritedInterfacesSubtyping(t *testing.T) { }) } -func TestNestedInterfaceInheritance(t *testing.T) { +func TestCheckNestedInterfaceInheritance(t *testing.T) { t.Parallel() diff --git a/runtime/tests/checker/member_test.go b/runtime/tests/checker/member_test.go index 6d35d7b4c2..92715d07c9 100644 --- a/runtime/tests/checker/member_test.go +++ b/runtime/tests/checker/member_test.go @@ -906,7 +906,7 @@ func TestCheckMemberAccess(t *testing.T) { t.Run("all member types", func(t *testing.T) { t.Parallel() - test := func(tt *testing.T, typeName string) { + test := func(t *testing.T, typeName string) { code := fmt.Sprintf(` struct Foo { var a: %[1]s? @@ -936,13 +936,29 @@ func TestCheckMemberAccess(t *testing.T) { types := []string{ "Bar", "{I}", - "AnyStruct", - "Block", } // Test all built-in composite types - for i := interpreter.PrimitiveStaticTypeAuthAccount; i < interpreter.PrimitiveStaticType_Count; i++ { - semaType := i.SemaType() + for ty := interpreter.PrimitiveStaticType(1); ty < interpreter.PrimitiveStaticType_Count; ty++ { + if !ty.IsDefined() { + continue + } + + semaType := ty.SemaType() + + // Some primitive static types are deprecated, + // and only exist for migration purposes, + // so do not have an equivalent sema type + if semaType == nil { + continue + } + + if !semaType.ContainFieldsOrElements() || + semaType.IsResourceType() { + + continue + } + types = append(types, semaType.QualifiedString()) } diff --git a/runtime/tests/checker/never_test.go b/runtime/tests/checker/never_test.go index ef5cfc2a33..3216389d7b 100644 --- a/runtime/tests/checker/never_test.go +++ b/runtime/tests/checker/never_test.go @@ -36,7 +36,7 @@ func TestCheckNever(t *testing.T) { _, err := ParseAndCheckWithPanic(t, ` - access(all) fun test(): Int { + fun test(): Int { return panic("XXX") } `, @@ -50,7 +50,7 @@ func TestCheckNever(t *testing.T) { _, err := ParseAndCheck(t, ` - access(all) fun test() { + fun test() { var x: Never = 5 } `, @@ -58,8 +58,8 @@ func TestCheckNever(t *testing.T) { errors := RequireCheckerErrors(t, err, 1) - require.IsType(t, &sema.TypeMismatchError{}, errors[0]) - typeMismatchErr := errors[0].(*sema.TypeMismatchError) + var typeMismatchErr *sema.TypeMismatchError + require.ErrorAs(t, errors[0], &typeMismatchErr) assert.Equal(t, sema.NeverType, typeMismatchErr.ExpectedType) assert.Equal(t, sema.IntType, typeMismatchErr.ActualType) @@ -70,7 +70,7 @@ func TestCheckNever(t *testing.T) { _, err := ParseAndCheck(t, ` - access(all) fun test() { + fun test() { var x: Never = "c" } `, @@ -78,8 +78,8 @@ func TestCheckNever(t *testing.T) { errors := RequireCheckerErrors(t, err, 1) - require.IsType(t, &sema.TypeMismatchError{}, errors[0]) - typeMismatchErr := errors[0].(*sema.TypeMismatchError) + var typeMismatchErr *sema.TypeMismatchError + require.ErrorAs(t, errors[0], &typeMismatchErr) assert.Equal(t, sema.NeverType, typeMismatchErr.ExpectedType) assert.Equal(t, sema.StringType, typeMismatchErr.ActualType) @@ -90,7 +90,7 @@ func TestCheckNever(t *testing.T) { _, err := ParseAndCheck(t, ` - access(all) fun test() { + fun test() { var x: Never = "hello" } `, @@ -98,8 +98,8 @@ func TestCheckNever(t *testing.T) { errors := RequireCheckerErrors(t, err, 1) - require.IsType(t, &sema.TypeMismatchError{}, errors[0]) - typeMismatchErr := errors[0].(*sema.TypeMismatchError) + var typeMismatchErr *sema.TypeMismatchError + require.ErrorAs(t, errors[0], &typeMismatchErr) assert.Equal(t, sema.NeverType, typeMismatchErr.ExpectedType) assert.Equal(t, sema.StringType, typeMismatchErr.ActualType) @@ -110,15 +110,16 @@ func TestCheckNever(t *testing.T) { _, err := ParseAndCheck(t, ` - access(all) fun test(a: Never, b: Never) { + fun test(a: Never, b: Never) { var x: Int = a + b } `, ) errors := RequireCheckerErrors(t, err, 1) - require.IsType(t, &sema.InvalidBinaryOperandsError{}, errors[0]) - binaryOpErr := errors[0].(*sema.InvalidBinaryOperandsError) + + var binaryOpErr *sema.InvalidBinaryOperandsError + require.ErrorAs(t, errors[0], &binaryOpErr) assert.Equal(t, sema.NeverType, binaryOpErr.LeftType) assert.Equal(t, sema.NeverType, binaryOpErr.RightType) @@ -129,15 +130,16 @@ func TestCheckNever(t *testing.T) { _, err := ParseAndCheck(t, ` - access(all) fun test(a: Never) { + fun test(a: Never) { var x: Bool = !a } `, ) errors := RequireCheckerErrors(t, err, 1) - require.IsType(t, &sema.InvalidUnaryOperandError{}, errors[0]) - unaryOpErr := errors[0].(*sema.InvalidUnaryOperandError) + + var unaryOpErr *sema.InvalidUnaryOperandError + require.ErrorAs(t, errors[0], &unaryOpErr) assert.Equal(t, sema.BoolType, unaryOpErr.ExpectedType) assert.Equal(t, sema.NeverType, unaryOpErr.ActualType) @@ -148,7 +150,7 @@ func TestCheckNever(t *testing.T) { _, err := ParseAndCheck(t, ` - access(all) fun test(a: Never?) { + fun test(a: Never?) { var x: Int = a ?? 4 } `, @@ -162,17 +164,16 @@ func TestCheckNever(t *testing.T) { _, err := ParseAndCheck(t, ` - enum Foo: Never { - } + enum Foo: Never {} `, ) errors := RequireCheckerErrors(t, err, 1) - require.IsType(t, &sema.InvalidEnumRawTypeError{}, errors[0]) - typeMismatchErr := errors[0].(*sema.InvalidEnumRawTypeError) + var invalidEnumRawTypeErr *sema.InvalidEnumRawTypeError + require.ErrorAs(t, errors[0], &invalidEnumRawTypeErr) - assert.Equal(t, sema.NeverType, typeMismatchErr.Type) + assert.Equal(t, sema.NeverType, invalidEnumRawTypeErr.Type) }) t.Run("tx prepare arg", func(t *testing.T) { @@ -185,12 +186,7 @@ func TestCheckNever(t *testing.T) { } `, ) - - errors := RequireCheckerErrors(t, err, 1) - - require.IsType(t, &sema.InvalidTransactionPrepareParameterTypeError{}, errors[0]) - typeMismatchErr := errors[0].(*sema.InvalidTransactionPrepareParameterTypeError) - - assert.Equal(t, sema.NeverType, typeMismatchErr.Type) + // Useless, but not an error + require.NoError(t, err) }) } diff --git a/runtime/tests/checker/nft_test.go b/runtime/tests/checker/nft_test.go index a32cd6a324..6be756487c 100644 --- a/runtime/tests/checker/nft_test.go +++ b/runtime/tests/checker/nft_test.go @@ -953,14 +953,14 @@ access(all) contract TopShot: NonFungibleToken { self.totalSupply = 0 // Put a new Collection in storage - self.account.save<@Collection>(<- create Collection(), to: /storage/MomentCollection) + self.account.storage.save<@Collection>(<- create Collection(), to: /storage/MomentCollection) // Create a public capability for the Collection let cap = self.account.capabilities.storage.issue<&{MomentCollectionPublic}>(/storage/MomentCollection) self.account.capabilities.publish(cap, at: /public/MomentCollection) // Put the Minter in storage - self.account.save<@Admin>(<- create Admin(), to: /storage/TopShotAdmin) + self.account.storage.save<@Admin>(<- create Admin(), to: /storage/TopShotAdmin) emit ContractInitialized() } diff --git a/runtime/tests/checker/purity_test.go b/runtime/tests/checker/purity_test.go index fa3f0362c8..3cb43d7214 100644 --- a/runtime/tests/checker/purity_test.go +++ b/runtime/tests/checker/purity_test.go @@ -706,7 +706,7 @@ func TestCheckPurityEnforcement(t *testing.T) { t.Run("bound function", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` + _, err := ParseAndCheck(t, ` struct S { fun f() {} } @@ -733,7 +733,7 @@ func TestCheckPurityEnforcement(t *testing.T) { t.Run("bound function, view", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` + _, err := ParseAndCheck(t, ` struct S { view fun f() {} } @@ -1417,167 +1417,148 @@ func TestCheckConditionPurity(t *testing.T) { }) } -func TestCheckAuthAccountPurity(t *testing.T) { +func TestCheckAccountPurity(t *testing.T) { t.Parallel() - t.Run("save", func(t *testing.T) { - t.Parallel() - - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.save(3, to: /storage/foo) - } - `) - - errs := RequireCheckerErrors(t, err, 1) - - require.IsType(t, &sema.PurityError{}, errs[0]) - assert.Equal( - t, - ast.Range{ - StartPos: ast.Position{Offset: 42, Line: 3, Column: 14}, - EndPos: ast.Position{Offset: 78, Line: 3, Column: 50}, - }, - errs[0].(*sema.PurityError).Range, - ) - }) + t.Run("storage", func(t *testing.T) { - t.Run("type", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.type(at: /storage/foo) - } - `) - require.NoError(t, err) - }) + t.Run("save", func(t *testing.T) { + t.Parallel() - t.Run("load", func(t *testing.T) { - t.Parallel() + _, err := ParseAndCheck(t, ` + view fun foo(storage: auth(Storage) &Account.Storage) { + storage.save(3, to: /storage/foo) + } + `) - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.load(from: /storage/foo) - } - `) + errs := RequireCheckerErrors(t, err, 1) - errs := RequireCheckerErrors(t, err, 1) + require.IsType(t, &sema.PurityError{}, errs[0]) + assert.Equal( + t, + ast.Range{ + StartPos: ast.Position{Offset: 89, Line: 3, Column: 18}, + EndPos: ast.Position{Offset: 121, Line: 3, Column: 50}, + }, + errs[0].(*sema.PurityError).Range, + ) + }) - require.IsType(t, &sema.PurityError{}, errs[0]) - assert.Equal( - t, - ast.Range{ - StartPos: ast.Position{Offset: 42, Line: 3, Column: 14}, - EndPos: ast.Position{Offset: 82, Line: 3, Column: 54}, - }, - errs[0].(*sema.PurityError).Range, - ) - }) + t.Run("type", func(t *testing.T) { + t.Parallel() - t.Run("copy", func(t *testing.T) { - t.Parallel() + _, err := ParseAndCheck(t, ` + view fun foo(storage: auth(Storage) &Account.Storage) { + storage.type(at: /storage/foo) + } + `) + require.NoError(t, err) + }) - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.copy(from: /storage/foo) - } - `) - require.NoError(t, err) - }) + t.Run("load", func(t *testing.T) { + t.Parallel() - t.Run("borrow", func(t *testing.T) { - t.Parallel() + _, err := ParseAndCheck(t, ` + view fun foo(storage: auth(Storage) &Account.Storage) { + storage.load(from: /storage/foo) + } + `) - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.borrow<&Int>(from: /storage/foo) - } - `) - require.NoError(t, err) - }) + errs := RequireCheckerErrors(t, err, 1) - t.Run("check", func(t *testing.T) { - t.Parallel() + require.IsType(t, &sema.PurityError{}, errs[0]) + assert.Equal( + t, + ast.Range{ + StartPos: ast.Position{Offset: 89, Line: 3, Column: 18}, + EndPos: ast.Position{Offset: 125, Line: 3, Column: 54}, + }, + errs[0].(*sema.PurityError).Range, + ) + }) - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.check(from: /storage/foo) - } - `) - require.NoError(t, err) - }) + t.Run("copy", func(t *testing.T) { + t.Parallel() - t.Run("forEachPublic", func(t *testing.T) { - t.Parallel() + _, err := ParseAndCheck(t, ` + view fun foo(storage: auth(Storage) &Account.Storage) { + storage.copy(from: /storage/foo) + } + `) + require.NoError(t, err) + }) - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.forEachPublic(fun (path: PublicPath, type: Type): Bool { - return true - }) - } - `) + t.Run("borrow", func(t *testing.T) { + t.Parallel() - errs := RequireCheckerErrors(t, err, 1) + _, err := ParseAndCheck(t, ` + view fun foo(storage: auth(Storage) &Account.Storage) { + storage.borrow<&Int>(from: /storage/foo) + } + `) + require.NoError(t, err) + }) - require.IsType(t, &sema.PurityError{}, errs[0]) - assert.Equal( - t, - ast.Range{ - StartPos: ast.Position{Offset: 42, Line: 3, Column: 14}, - EndPos: ast.Position{Offset: 156, Line: 5, Column: 15}, - }, - errs[0].(*sema.PurityError).Range, - ) - }) + t.Run("check", func(t *testing.T) { + t.Parallel() - t.Run("forEachPrivate", func(t *testing.T) { - t.Parallel() + _, err := ParseAndCheck(t, ` + view fun foo(storage: &Account.Storage) { + storage.check(from: /storage/foo) + } + `) + require.NoError(t, err) + }) - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.forEachPrivate(fun (path: PrivatePath, type: Type): Bool { - return true - }) - } - `) + t.Run("forEachPublic", func(t *testing.T) { + t.Parallel() - errs := RequireCheckerErrors(t, err, 1) + _, err := ParseAndCheck(t, ` + view fun foo(storage: &Account.Storage) { + storage.forEachPublic(fun (path: PublicPath, type: Type): Bool { + return true + }) + } + `) - require.IsType(t, &sema.PurityError{}, errs[0]) - assert.Equal( - t, - ast.Range{ - StartPos: ast.Position{Offset: 42, Line: 3, Column: 14}, - EndPos: ast.Position{Offset: 158, Line: 5, Column: 15}, - }, - errs[0].(*sema.PurityError).Range, - ) - }) + errs := RequireCheckerErrors(t, err, 1) - t.Run("forEachStored", func(t *testing.T) { - t.Parallel() + require.IsType(t, &sema.PurityError{}, errs[0]) + assert.Equal( + t, + ast.Range{ + StartPos: ast.Position{Offset: 75, Line: 3, Column: 18}, + EndPos: ast.Position{Offset: 193, Line: 5, Column: 19}, + }, + errs[0].(*sema.PurityError).Range, + ) + }) - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.forEachStored(fun (path: StoragePath, type: Type): Bool { - return true - }) - } - `) + t.Run("forEachStored", func(t *testing.T) { + t.Parallel() - errs := RequireCheckerErrors(t, err, 1) + _, err := ParseAndCheck(t, ` + view fun foo(storage: &Account.Storage) { + storage.forEachStored(fun (path: StoragePath, type: Type): Bool { + return true + }) + } + `) - require.IsType(t, &sema.PurityError{}, errs[0]) - assert.Equal( - t, - ast.Range{ - StartPos: ast.Position{Offset: 42, Line: 3, Column: 14}, - EndPos: ast.Position{Offset: 157, Line: 5, Column: 15}, - }, - errs[0].(*sema.PurityError).Range, - ) + errs := RequireCheckerErrors(t, err, 1) + + require.IsType(t, &sema.PurityError{}, errs[0]) + assert.Equal( + t, + ast.Range{ + StartPos: ast.Position{Offset: 75, Line: 3, Column: 18}, + EndPos: ast.Position{Offset: 194, Line: 5, Column: 19}, + }, + errs[0].(*sema.PurityError).Range, + ) + }) }) t.Run("contracts", func(t *testing.T) { @@ -1586,9 +1567,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("add", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.contracts.add(name: "", code: []) + _, err := ParseAndCheck(t, ` + view fun foo(contracts: auth(Contracts) &Account.Contracts) { + contracts.add(name: "", code: []) } `) @@ -1598,19 +1579,19 @@ func TestCheckAuthAccountPurity(t *testing.T) { assert.Equal( t, ast.Range{ - StartPos: ast.Position{Offset: 50, Line: 3, Column: 18}, - EndPos: ast.Position{Offset: 94, Line: 3, Column: 62}, + StartPos: ast.Position{Offset: 95, Line: 3, Column: 18}, + EndPos: ast.Position{Offset: 127, Line: 3, Column: 50}, }, errs[0].(*sema.PurityError).Range, ) }) - t.Run("update__experimental", func(t *testing.T) { + t.Run("update", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.contracts.update__experimental(name: "", code: []) + _, err := ParseAndCheck(t, ` + view fun foo(contracts: auth(Contracts) &Account.Contracts) { + contracts.update(name: "", code: []) } `) @@ -1620,8 +1601,8 @@ func TestCheckAuthAccountPurity(t *testing.T) { assert.Equal( t, ast.Range{ - StartPos: ast.Position{Offset: 50, Line: 3, Column: 18}, - EndPos: ast.Position{Offset: 111, Line: 3, Column: 79}, + StartPos: ast.Position{Offset: 95, Line: 3, Column: 18}, + EndPos: ast.Position{Offset: 130, Line: 3, Column: 53}, }, errs[0].(*sema.PurityError).Range, ) @@ -1630,9 +1611,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("get", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.contracts.get(name: "") + _, err := ParseAndCheck(t, ` + view fun foo(contracts: &Account.Contracts) { + contracts.get(name: "") } `) @@ -1642,9 +1623,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("remove", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.contracts.remove(name: "") + _, err := ParseAndCheck(t, ` + view fun foo(contracts: auth(Contracts) &Account.Contracts) { + contracts.remove(name: "") } `) @@ -1654,8 +1635,8 @@ func TestCheckAuthAccountPurity(t *testing.T) { assert.Equal( t, ast.Range{ - StartPos: ast.Position{Offset: 50, Line: 3, Column: 18}, - EndPos: ast.Position{Offset: 87, Line: 3, Column: 55}, + StartPos: ast.Position{Offset: 95, Line: 3, Column: 18}, + EndPos: ast.Position{Offset: 120, Line: 3, Column: 43}, }, errs[0].(*sema.PurityError).Range, ) @@ -1664,9 +1645,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("borrow", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.contracts.borrow<&Int>(name: "") + _, err := ParseAndCheck(t, ` + view fun foo(contracts: &Account.Contracts) { + contracts.borrow<&Int>(name: "") } `) require.NoError(t, err) @@ -1679,9 +1660,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("add", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.keys.add( + _, err := ParseAndCheck(t, ` + view fun foo(keys: auth(Keys) &Account.Keys) { + keys.add( publicKey: key, hashAlgorithm: algo, weight: 100.0 @@ -1695,8 +1676,8 @@ func TestCheckAuthAccountPurity(t *testing.T) { assert.Equal( t, ast.Range{ - StartPos: ast.Position{Offset: 50, Line: 3, Column: 18}, - EndPos: ast.Position{Offset: 207, Line: 7, Column: 18}, + StartPos: ast.Position{Offset: 80, Line: 3, Column: 18}, + EndPos: ast.Position{Offset: 225, Line: 7, Column: 18}, }, errs[0].(*sema.PurityError).Range, ) @@ -1707,9 +1688,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("get", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.keys.get(keyIndex: 0) + _, err := ParseAndCheck(t, ` + view fun foo(keys: &Account.Keys) { + keys.get(keyIndex: 0) } `) require.NoError(t, err) @@ -1718,9 +1699,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("revoke", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.keys.revoke(keyIndex: 0) + _, err := ParseAndCheck(t, ` + view fun foo(keys: auth(Keys) &Account.Keys) { + keys.revoke(keyIndex: 0) } `) @@ -1730,8 +1711,8 @@ func TestCheckAuthAccountPurity(t *testing.T) { assert.Equal( t, ast.Range{ - StartPos: ast.Position{Offset: 50, Line: 3, Column: 18}, - EndPos: ast.Position{Offset: 85, Line: 3, Column: 53}, + StartPos: ast.Position{Offset: 80, Line: 3, Column: 18}, + EndPos: ast.Position{Offset: 103, Line: 3, Column: 41}, }, errs[0].(*sema.PurityError).Range, ) @@ -1740,9 +1721,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("forEach", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.keys.forEach(fun(key: AccountKey): Bool { + _, err := ParseAndCheck(t, ` + view fun foo(keys: &Account.Keys) { + keys.forEach(fun(key: AccountKey): Bool { return true }) } @@ -1754,8 +1735,8 @@ func TestCheckAuthAccountPurity(t *testing.T) { assert.Equal( t, ast.Range{ - StartPos: ast.Position{Offset: 50, Line: 3, Column: 18}, - EndPos: ast.Position{Offset: 157, Line: 5, Column: 19}, + StartPos: ast.Position{Offset: 69, Line: 3, Column: 18}, + EndPos: ast.Position{Offset: 164, Line: 5, Column: 19}, }, errs[0].(*sema.PurityError).Range, ) @@ -1768,9 +1749,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("publish", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.inbox.publish( + _, err := ParseAndCheck(t, ` + view fun foo(inbox: auth(Inbox) &Account.Inbox) { + inbox.publish( cap, name: "cap", recipient: 0x1 @@ -1784,8 +1765,8 @@ func TestCheckAuthAccountPurity(t *testing.T) { assert.Equal( t, ast.Range{ - StartPos: ast.Position{Offset: 50, Line: 3, Column: 18}, - EndPos: ast.Position{Offset: 194, Line: 7, Column: 18}, + StartPos: ast.Position{Offset: 83, Line: 3, Column: 18}, + EndPos: ast.Position{Offset: 215, Line: 7, Column: 18}, }, errs[0].(*sema.PurityError).Range, ) @@ -1795,9 +1776,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("unpublish", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.inbox.unpublish<&Int>("cap") + _, err := ParseAndCheck(t, ` + view fun foo(inbox: auth(Inbox) &Account.Inbox) { + inbox.unpublish<&Int>("cap") } `) @@ -1807,8 +1788,8 @@ func TestCheckAuthAccountPurity(t *testing.T) { assert.Equal( t, ast.Range{ - StartPos: ast.Position{Offset: 50, Line: 3, Column: 18}, - EndPos: ast.Position{Offset: 89, Line: 3, Column: 57}, + StartPos: ast.Position{Offset: 83, Line: 3, Column: 18}, + EndPos: ast.Position{Offset: 110, Line: 3, Column: 45}, }, errs[0].(*sema.PurityError).Range, ) @@ -1817,9 +1798,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("claim", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.inbox.claim<&Int>("cap", provider: 0x1) + _, err := ParseAndCheck(t, ` + view fun foo(inbox: auth(Inbox) &Account.Inbox) { + inbox.claim<&Int>("cap", provider: 0x1) } `) @@ -1829,8 +1810,8 @@ func TestCheckAuthAccountPurity(t *testing.T) { assert.Equal( t, ast.Range{ - StartPos: ast.Position{Offset: 50, Line: 3, Column: 18}, - EndPos: ast.Position{Offset: 100, Line: 3, Column: 68}, + StartPos: ast.Position{Offset: 83, Line: 3, Column: 18}, + EndPos: ast.Position{Offset: 121, Line: 3, Column: 56}, }, errs[0].(*sema.PurityError).Range, ) @@ -1843,9 +1824,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("get", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.capabilities.get<&Int>(/public/foo) + _, err := ParseAndCheck(t, ` + view fun foo(capabilities: &Account.Capabilities) { + capabilities.get<&Int>(/public/foo) } `) require.NoError(t, err) @@ -1854,9 +1835,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("borrow", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.capabilities.borrow<&Int>(/public/foo) + _, err := ParseAndCheck(t, ` + view fun foo(capabilities: &Account.Capabilities) { + capabilities.borrow<&Int>(/public/foo) } `) require.NoError(t, err) @@ -1865,9 +1846,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("publish", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.capabilities.publish( + _, err := ParseAndCheck(t, ` + view fun foo(capabilities: auth(Capabilities) &Account.Capabilities) { + capabilities.publish( cap, at: /public/foo ) @@ -1880,8 +1861,8 @@ func TestCheckAuthAccountPurity(t *testing.T) { assert.Equal( t, ast.Range{ - StartPos: ast.Position{Offset: 50, Line: 3, Column: 18}, - EndPos: ast.Position{Offset: 167, Line: 6, Column: 18}, + StartPos: ast.Position{Offset: 104, Line: 3, Column: 18}, + EndPos: ast.Position{Offset: 209, Line: 6, Column: 18}, }, errs[0].(*sema.PurityError).Range, ) @@ -1891,9 +1872,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("unpublish", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.capabilities.unpublish(/public/foo) + _, err := ParseAndCheck(t, ` + view fun foo(capabilities: auth(Capabilities) &Account.Capabilities) { + capabilities.unpublish(/public/foo) } `) @@ -1903,8 +1884,8 @@ func TestCheckAuthAccountPurity(t *testing.T) { assert.Equal( t, ast.Range{ - StartPos: ast.Position{Offset: 50, Line: 3, Column: 18}, - EndPos: ast.Position{Offset: 96, Line: 3, Column: 64}, + StartPos: ast.Position{Offset: 104, Line: 3, Column: 18}, + EndPos: ast.Position{Offset: 138, Line: 3, Column: 52}, }, errs[0].(*sema.PurityError).Range, ) @@ -1917,9 +1898,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("getController", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.capabilities.storage.getController(byCapabilityID: 1) + _, err := ParseAndCheck(t, ` + view fun foo(storage: auth(StorageCapabilities) &Account.StorageCapabilities) { + storage.getController(byCapabilityID: 1) } `) require.NoError(t, err) @@ -1928,9 +1909,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("getControllers", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.capabilities.storage.getControllers(forPath: /storage/foo) + _, err := ParseAndCheck(t, ` + view fun foo(storage: auth(StorageCapabilities) &Account.StorageCapabilities) { + storage.getControllers(forPath: /storage/foo) } `) require.NoError(t, err) @@ -1939,9 +1920,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("forEachController", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.capabilities.storage.forEachController( + _, err := ParseAndCheck(t, ` + view fun foo(storage: auth(StorageCapabilities) &Account.StorageCapabilities) { + storage.forEachController( forPath: /storage/foo, fun (controller: &StorageCapabilityController): Bool { return true @@ -1956,8 +1937,8 @@ func TestCheckAuthAccountPurity(t *testing.T) { assert.Equal( t, ast.Range{ - StartPos: ast.Position{Offset: 50, Line: 3, Column: 18}, - EndPos: ast.Position{Offset: 304, Line: 8, Column: 18}, + StartPos: ast.Position{Offset: 113, Line: 3, Column: 18}, + EndPos: ast.Position{Offset: 342, Line: 8, Column: 18}, }, errs[0].(*sema.PurityError).Range, ) @@ -1966,9 +1947,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("issue", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.capabilities.storage.issue<&Int>(/storage/foo) + _, err := ParseAndCheck(t, ` + view fun foo(storage: auth(StorageCapabilities) &Account.StorageCapabilities) { + storage.issue<&Int>(/storage/foo) } `) @@ -1978,8 +1959,8 @@ func TestCheckAuthAccountPurity(t *testing.T) { assert.Equal( t, ast.Range{ - StartPos: ast.Position{Offset: 50, Line: 3, Column: 18}, - EndPos: ast.Position{Offset: 107, Line: 3, Column: 75}, + StartPos: ast.Position{Offset: 113, Line: 3, Column: 18}, + EndPos: ast.Position{Offset: 145, Line: 3, Column: 50}, }, errs[0].(*sema.PurityError).Range, ) @@ -1992,9 +1973,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("getController", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.capabilities.account.getController(byCapabilityID: 1) + _, err := ParseAndCheck(t, ` + view fun foo(account: auth(AccountCapabilities) &Account.AccountCapabilities) { + account.getController(byCapabilityID: 1) } `) require.NoError(t, err) @@ -2003,9 +1984,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("getControllers", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.capabilities.account.getControllers() + _, err := ParseAndCheck(t, ` + view fun foo(account: auth(AccountCapabilities) &Account.AccountCapabilities) { + account.getControllers() } `) require.NoError(t, err) @@ -2014,9 +1995,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("forEachController", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.capabilities.account.forEachController( + _, err := ParseAndCheck(t, ` + view fun foo(account: auth(AccountCapabilities) &Account.AccountCapabilities) { + account.forEachController( fun (controller: &AccountCapabilityController): Bool { return true } @@ -2030,8 +2011,8 @@ func TestCheckAuthAccountPurity(t *testing.T) { assert.Equal( t, ast.Range{ - StartPos: ast.Position{Offset: 50, Line: 3, Column: 18}, - EndPos: ast.Position{Offset: 259, Line: 7, Column: 18}, + StartPos: ast.Position{Offset: 113, Line: 3, Column: 18}, + EndPos: ast.Position{Offset: 297, Line: 7, Column: 18}, }, errs[0].(*sema.PurityError).Range, ) @@ -2040,103 +2021,9 @@ func TestCheckAuthAccountPurity(t *testing.T) { t.Run("issue", func(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - authAccount.capabilities.account.issue<&AuthAccount>() - } - `) - - errs := RequireCheckerErrors(t, err, 1) - - require.IsType(t, &sema.PurityError{}, errs[0]) - assert.Equal( - t, - ast.Range{ - StartPos: ast.Position{Offset: 50, Line: 3, Column: 18}, - EndPos: ast.Position{Offset: 103, Line: 3, Column: 71}, - }, - errs[0].(*sema.PurityError).Range, - ) - }) - }) -} - -func TestCheckPublicAccountPurity(t *testing.T) { - t.Parallel() - - t.Run("forEachPublic", func(t *testing.T) { - t.Parallel() - - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - publicAccount.forEachPublic(fun (path: PublicPath, type: Type): Bool { - return true - }) - } - `) - - errs := RequireCheckerErrors(t, err, 1) - - require.IsType(t, &sema.PurityError{}, errs[0]) - assert.Equal( - t, - ast.Range{ - StartPos: ast.Position{Offset: 42, Line: 3, Column: 14}, - EndPos: ast.Position{Offset: 158, Line: 5, Column: 15}, - }, - errs[0].(*sema.PurityError).Range, - ) - }) - - t.Run("contracts", func(t *testing.T) { - t.Parallel() - - t.Run("get", func(t *testing.T) { - t.Parallel() - - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - publicAccount.contracts.get(name: "") - } - `) - - require.NoError(t, err) - }) - - t.Run("borrow", func(t *testing.T) { - t.Parallel() - - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - publicAccount.contracts.borrow<&Int>(name: "") - } - `) - require.NoError(t, err) - }) - }) - - t.Run("keys", func(t *testing.T) { - t.Parallel() - - t.Run("get", func(t *testing.T) { - t.Parallel() - - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - publicAccount.keys.get(keyIndex: 0) - } - `) - require.NoError(t, err) - }) - - t.Run("forEach", func(t *testing.T) { - t.Parallel() - - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - publicAccount.keys.forEach(fun(key: AccountKey): Bool { - return true - }) + _, err := ParseAndCheck(t, ` + view fun foo(account: auth(AccountCapabilities) &Account.AccountCapabilities) { + account.issue<&Account>() } `) @@ -2146,37 +2033,11 @@ func TestCheckPublicAccountPurity(t *testing.T) { assert.Equal( t, ast.Range{ - StartPos: ast.Position{Offset: 50, Line: 3, Column: 18}, - EndPos: ast.Position{Offset: 159, Line: 5, Column: 19}, + StartPos: ast.Position{Offset: 113, Line: 3, Column: 18}, + EndPos: ast.Position{Offset: 137, Line: 3, Column: 42}, }, errs[0].(*sema.PurityError).Range, ) }) }) - - t.Run("capabilities", func(t *testing.T) { - t.Parallel() - - t.Run("get", func(t *testing.T) { - t.Parallel() - - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - publicAccount.capabilities.get<&Int>(/public/foo) - } - `) - require.NoError(t, err) - }) - - t.Run("borrow", func(t *testing.T) { - t.Parallel() - - _, err := ParseAndCheckAccount(t, ` - view fun foo() { - publicAccount.capabilities.borrow<&Int>(/public/foo) - } - `) - require.NoError(t, err) - }) - }) } diff --git a/runtime/tests/checker/reference_test.go b/runtime/tests/checker/reference_test.go index 5b5909ffe9..ff9a3d9853 100644 --- a/runtime/tests/checker/reference_test.go +++ b/runtime/tests/checker/reference_test.go @@ -1648,16 +1648,16 @@ func TestCheckInvalidatedReferenceUse(t *testing.T) { t.Parallel() - _, err := ParseAndCheckAccount(t, + _, err := ParseAndCheck(t, ` - access(all) fun test() { - authAccount.save(<-[<-create R()], to: /storage/a) + access(all) fun test(storage: auth(Storage) &Account.Storage) { + storage.save(<-[<-create R()], to: /storage/a) - let collectionRef = authAccount.borrow<&[R]>(from: /storage/a)! + let collectionRef = storage.borrow<&[R]>(from: /storage/a)! let ref = collectionRef[0] - let collection <- authAccount.load<@[R]>(from: /storage/a)! - authAccount.save(<- collection, to: /storage/b) + let collection <- storage.load<@[R]>(from: /storage/a)! + storage.save(<- collection, to: /storage/b) ref.setA(2) } diff --git a/runtime/tests/checker/resources_test.go b/runtime/tests/checker/resources_test.go index a00f7df1f7..f814147eee 100644 --- a/runtime/tests/checker/resources_test.go +++ b/runtime/tests/checker/resources_test.go @@ -3977,7 +3977,7 @@ func TestCheckInvalidResourceDictionaryKeysForeach(t *testing.T) { xs.forEachKey(fun (x: @X): Bool { destroy x return true - }) + }) destroy xs } `) @@ -5064,9 +5064,9 @@ func TestCheckInvalidResourceOwnerField(t *testing.T) { _, err := ParseAndCheck(t, ` resource Test { - let owner: PublicAccount + let owner: &Account - init(owner: PublicAccount) { + init(owner: &Account) { self.owner = owner } } @@ -5083,7 +5083,7 @@ func TestCheckInvalidResourceInterfaceOwnerField(t *testing.T) { _, err := ParseAndCheck(t, ` resource interface Test { - let owner: PublicAccount + let owner: &Account } `) @@ -5129,7 +5129,7 @@ func TestCheckResourceOwnerFieldUse(t *testing.T) { _, err := ParseAndCheck(t, ` resource Test { - fun test(): PublicAccount? { + fun test(): &Account? { return self.owner } } @@ -5154,6 +5154,45 @@ func TestCheckResourceInterfaceOwnerFieldUse(t *testing.T) { require.NoError(t, err) } +func TestCheckResourceOwnerFieldType(t *testing.T) { + + t.Parallel() + + _, err := ParseAndCheck(t, ` + var owner: &Account? = nil + + resource Test { + + init() { + owner = self.owner + } + } + `) + + require.NoError(t, err) +} + +func TestCheckResourceOwnerFieldTypeAccess(t *testing.T) { + + t.Parallel() + + checker, err := ParseAndCheck(t, ` + + resource Test {} + + let r <- create Test() + let owner = r.owner + `) + + require.NoError(t, err) + + ownerType := RequireGlobalValue(t, checker.Elaboration, "owner") + require.Equal(t, + sema.NewOptionalType(nil, sema.AccountReferenceType), + ownerType, + ) +} + func TestCheckInvalidResourceOwnerFieldInitialization(t *testing.T) { t.Parallel() @@ -5161,7 +5200,7 @@ func TestCheckInvalidResourceOwnerFieldInitialization(t *testing.T) { _, err := ParseAndCheck(t, ` resource Test { - init(owner: PublicAccount) { + init(owner: &Account) { self.owner = owner } } diff --git a/runtime/tests/checker/storable_test.go b/runtime/tests/checker/storable_test.go index b3f9f01a84..1126507fee 100644 --- a/runtime/tests/checker/storable_test.go +++ b/runtime/tests/checker/storable_test.go @@ -133,8 +133,7 @@ func TestCheckStorable(t *testing.T) { }, sema.NeverType, sema.VoidType, - sema.AuthAccountType, - sema.PublicAccountType, + sema.AccountType, } // Capabilities of non-storable types are storable diff --git a/runtime/tests/checker/transactions_test.go b/runtime/tests/checker/transactions_test.go index f348d67e13..7262162c33 100644 --- a/runtime/tests/checker/transactions_test.go +++ b/runtime/tests/checker/transactions_test.go @@ -86,7 +86,7 @@ func TestCheckTransactions(t *testing.T) { ` transaction { - prepare(x: AuthAccount, y: AuthAccount) {} + prepare(x: &Account, y: &Account) {} } `, nil, diff --git a/runtime/tests/checker/type_inference_test.go b/runtime/tests/checker/type_inference_test.go index dee22a8101..8d0ef43450 100644 --- a/runtime/tests/checker/type_inference_test.go +++ b/runtime/tests/checker/type_inference_test.go @@ -659,7 +659,7 @@ func TestCheckForceExpressionTypeInference(t *testing.T) { }) } -func TestCastExpressionTypeInference(t *testing.T) { +func TestCheckCastExpressionTypeInference(t *testing.T) { t.Parallel() diff --git a/runtime/tests/interpreter/account_test.go b/runtime/tests/interpreter/account_test.go index 0d62e0edf4..e0f83103be 100644 --- a/runtime/tests/interpreter/account_test.go +++ b/runtime/tests/interpreter/account_test.go @@ -25,6 +25,7 @@ import ( "github.com/onflow/atree" "github.com/onflow/cadence/runtime/activations" + "github.com/onflow/cadence/runtime/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -46,6 +47,7 @@ func testAccount( t *testing.T, address interpreter.AddressValue, auth bool, + handler stdlib.AccountHandler, code string, checkerConfig sema.Config, ) ( @@ -56,43 +58,354 @@ func testAccount( t, address, auth, + handler, code, checkerConfig, nil, ) } +type testAccountHandler struct { + accountIDs map[common.Address]uint64 + generateAccountID func(address common.Address) (uint64, error) + getAccountBalance func(address common.Address) (uint64, error) + getAccountAvailableBalance func(address common.Address) (uint64, error) + commitStorageTemporarily func(inter *interpreter.Interpreter) error + getStorageUsed func(address common.Address) (uint64, error) + getStorageCapacity func(address common.Address) (uint64, error) + validatePublicKey func(key *stdlib.PublicKey) error + verifySignature func( + signature []byte, + tag string, + signedData []byte, + publicKey []byte, + signatureAlgorithm sema.SignatureAlgorithm, + hashAlgorithm sema.HashAlgorithm, + ) ( + bool, + error, + ) + blsVerifyPOP func(publicKey *stdlib.PublicKey, signature []byte) (bool, error) + hash func(data []byte, tag string, algorithm sema.HashAlgorithm) ([]byte, error) + getAccountKey func(address common.Address, index int) (*stdlib.AccountKey, error) + accountKeysCount func(address common.Address) (uint64, error) + emitEvent func( + inter *interpreter.Interpreter, + eventType *sema.CompositeType, + values []interpreter.Value, + locationRange interpreter.LocationRange, + ) + addAccountKey func( + address common.Address, + key *stdlib.PublicKey, + algo sema.HashAlgorithm, + weight int, + ) ( + *stdlib.AccountKey, + error, + ) + revokeAccountKey func(address common.Address, index int) (*stdlib.AccountKey, error) + getAccountContractCode func(location common.AddressLocation) ([]byte, error) + parseAndCheckProgram func( + code []byte, + location common.Location, + getAndSetProgram bool, + ) ( + *interpreter.Program, + error, + ) + updateAccountContractCode func(location common.AddressLocation, code []byte) error + recordContractUpdate func(location common.AddressLocation, value *interpreter.CompositeValue) + interpretContract func( + location common.AddressLocation, + program *interpreter.Program, + name string, + invocation stdlib.DeployedContractConstructorInvocation, + ) ( + *interpreter.CompositeValue, + error, + ) + temporarilyRecordCode func(location common.AddressLocation, code []byte) + removeAccountContractCode func(location common.AddressLocation) error + recordContractRemoval func(location common.AddressLocation) + getAccountContractNames func(address common.Address) ([]string, error) +} + +var _ stdlib.AccountHandler = &testAccountHandler{} + +func (t *testAccountHandler) GenerateAccountID(address common.Address) (uint64, error) { + if t.generateAccountID == nil { + if t.accountIDs == nil { + t.accountIDs = map[common.Address]uint64{} + } + t.accountIDs[address]++ + return t.accountIDs[address], nil + } + return t.generateAccountID(address) +} + +func (t *testAccountHandler) GetAccountBalance(address common.Address) (uint64, error) { + if t.getAccountBalance == nil { + panic(errors.NewUnexpectedError("unexpected call to GetAccountBalance")) + } + return t.getAccountBalance(address) +} + +func (t *testAccountHandler) GetAccountAvailableBalance(address common.Address) (uint64, error) { + if t.getAccountAvailableBalance == nil { + panic(errors.NewUnexpectedError("unexpected call to GetAccountAvailableBalance")) + } + return t.getAccountAvailableBalance(address) +} + +func (t *testAccountHandler) CommitStorageTemporarily(inter *interpreter.Interpreter) error { + if t.commitStorageTemporarily == nil { + panic(errors.NewUnexpectedError("unexpected call to CommitStorageTemporarily")) + } + return t.commitStorageTemporarily(inter) +} + +func (t *testAccountHandler) GetStorageUsed(address common.Address) (uint64, error) { + if t.getStorageUsed == nil { + panic(errors.NewUnexpectedError("unexpected call to GetStorageUsed")) + } + return t.getStorageUsed(address) +} + +func (t *testAccountHandler) GetStorageCapacity(address common.Address) (uint64, error) { + if t.getStorageCapacity == nil { + panic(errors.NewUnexpectedError("unexpected call to GetStorageCapacity")) + } + return t.getStorageCapacity(address) +} + +func (t *testAccountHandler) ValidatePublicKey(key *stdlib.PublicKey) error { + if t.validatePublicKey == nil { + panic(errors.NewUnexpectedError("unexpected call to ValidatePublicKey")) + } + return t.validatePublicKey(key) +} + +func (t *testAccountHandler) VerifySignature( + signature []byte, + tag string, + signedData []byte, + publicKey []byte, + signatureAlgorithm sema.SignatureAlgorithm, + hashAlgorithm sema.HashAlgorithm, +) ( + bool, + error, +) { + if t.verifySignature == nil { + panic(errors.NewUnexpectedError("unexpected call to VerifySignature")) + } + return t.verifySignature( + signature, + tag, + signedData, + publicKey, + signatureAlgorithm, + hashAlgorithm, + ) +} + +func (t *testAccountHandler) BLSVerifyPOP(publicKey *stdlib.PublicKey, signature []byte) (bool, error) { + if t.blsVerifyPOP == nil { + panic(errors.NewUnexpectedError("unexpected call to BLSVerifyPOP")) + } + return t.blsVerifyPOP(publicKey, signature) +} + +func (t *testAccountHandler) Hash(data []byte, tag string, algorithm sema.HashAlgorithm) ([]byte, error) { + if t.hash == nil { + panic(errors.NewUnexpectedError("unexpected call to Hash")) + } + return t.hash(data, tag, algorithm) +} + +func (t *testAccountHandler) GetAccountKey(address common.Address, index int) (*stdlib.AccountKey, error) { + if t.getAccountKey == nil { + panic(errors.NewUnexpectedError("unexpected call to GetAccountKey")) + } + return t.getAccountKey(address, index) +} + +func (t *testAccountHandler) AccountKeysCount(address common.Address) (uint64, error) { + if t.accountKeysCount == nil { + panic(errors.NewUnexpectedError("unexpected call to AccountKeysCount")) + } + return t.accountKeysCount(address) +} + +func (t *testAccountHandler) EmitEvent( + inter *interpreter.Interpreter, + eventType *sema.CompositeType, + values []interpreter.Value, + locationRange interpreter.LocationRange, +) { + if t.emitEvent == nil { + panic(errors.NewUnexpectedError("unexpected call to EmitEvent")) + } + t.emitEvent( + inter, + eventType, + values, + locationRange, + ) +} + +func (t *testAccountHandler) AddAccountKey( + address common.Address, + key *stdlib.PublicKey, + algo sema.HashAlgorithm, + weight int, +) ( + *stdlib.AccountKey, + error, +) { + if t.addAccountKey == nil { + panic(errors.NewUnexpectedError("unexpected call to AddAccountKey")) + } + return t.addAccountKey( + address, + key, + algo, + weight, + ) +} + +func (t *testAccountHandler) RevokeAccountKey(address common.Address, index int) (*stdlib.AccountKey, error) { + if t.revokeAccountKey == nil { + panic(errors.NewUnexpectedError("unexpected call to RevokeAccountKey")) + } + return t.revokeAccountKey(address, index) +} + +func (t *testAccountHandler) GetAccountContractCode(location common.AddressLocation) ([]byte, error) { + if t.getAccountContractCode == nil { + panic(errors.NewUnexpectedError("unexpected call to GetAccountContractCode")) + } + return t.getAccountContractCode(location) +} + +func (t *testAccountHandler) ParseAndCheckProgram( + code []byte, + location common.Location, + getAndSetProgram bool, +) ( + *interpreter.Program, + error, +) { + if t.parseAndCheckProgram == nil { + panic(errors.NewUnexpectedError("unexpected call to ParseAndCheckProgram")) + } + return t.parseAndCheckProgram(code, location, getAndSetProgram) +} + +func (t *testAccountHandler) UpdateAccountContractCode(location common.AddressLocation, code []byte) error { + if t.updateAccountContractCode == nil { + panic(errors.NewUnexpectedError("unexpected call to UpdateAccountContractCode")) + } + return t.updateAccountContractCode(location, code) +} + +func (t *testAccountHandler) RecordContractUpdate(location common.AddressLocation, value *interpreter.CompositeValue) { + if t.recordContractUpdate == nil { + panic(errors.NewUnexpectedError("unexpected call to RecordContractUpdate")) + } + t.recordContractUpdate(location, value) +} + +func (t *testAccountHandler) InterpretContract( + location common.AddressLocation, + program *interpreter.Program, + name string, + invocation stdlib.DeployedContractConstructorInvocation, +) ( + *interpreter.CompositeValue, + error, +) { + if t.interpretContract == nil { + panic(errors.NewUnexpectedError("unexpected call to InterpretContract")) + } + return t.interpretContract( + location, + program, + name, + invocation, + ) +} + +func (t *testAccountHandler) TemporarilyRecordCode(location common.AddressLocation, code []byte) { + if t.temporarilyRecordCode == nil { + panic(errors.NewUnexpectedError("unexpected call to TemporarilyRecordCode")) + } + t.temporarilyRecordCode(location, code) +} + +func (t *testAccountHandler) RemoveAccountContractCode(location common.AddressLocation) error { + if t.removeAccountContractCode == nil { + panic(errors.NewUnexpectedError("unexpected call to RemoveAccountContractCode")) + } + return t.removeAccountContractCode(location) +} + +func (t *testAccountHandler) RecordContractRemoval(location common.AddressLocation) { + if t.recordContractRemoval == nil { + panic(errors.NewUnexpectedError("unexpected call to RecordContractRemoval")) + } + t.recordContractRemoval(location) +} + +func (t *testAccountHandler) GetAccountContractNames(address common.Address) ([]string, error) { + if t.getAccountContractNames == nil { + panic(errors.NewUnexpectedError("unexpected call to GetAccountContractNames")) + } + return t.getAccountContractNames(address) +} + func testAccountWithErrorHandler( t *testing.T, address interpreter.AddressValue, auth bool, + handler stdlib.AccountHandler, code string, checkerConfig sema.Config, checkerErrorHandler func(error), -) ( - *interpreter.Interpreter, - func() map[storageKey]interpreter.Value, -) { +) (*interpreter.Interpreter, func() map[storageKey]interpreter.Value) { + + account := stdlib.NewAccountValue(nil, handler, address) var valueDeclarations []stdlib.StandardLibraryValue // `authAccount` authAccountValueDeclaration := stdlib.StandardLibraryValue{ - Name: "authAccount", - Type: sema.AuthAccountType, - Value: newTestAuthAccountValue(nil, address), - Kind: common.DeclarationKindConstant, + Name: "authAccount", + Type: sema.FullyEntitledAccountReferenceType, + Value: interpreter.NewEphemeralReferenceValue( + nil, + interpreter.FullyEntitledAccountAccess, + account, + sema.AccountType, + ), + Kind: common.DeclarationKindConstant, } valueDeclarations = append(valueDeclarations, authAccountValueDeclaration) // `pubAccount` pubAccountValueDeclaration := stdlib.StandardLibraryValue{ - Name: "pubAccount", - Type: sema.PublicAccountType, - Value: newTestPublicAccountValue(nil, address), - Kind: common.DeclarationKindConstant, + Name: "pubAccount", + Type: sema.AccountReferenceType, + Value: interpreter.NewEphemeralReferenceValue( + nil, + interpreter.UnauthorizedAccess, + account, + sema.AccountType, + ), + Kind: common.DeclarationKindConstant, } valueDeclarations = append(valueDeclarations, pubAccountValueDeclaration) @@ -130,8 +443,8 @@ func testAccountWithErrorHandler( BaseActivation: baseActivation, ContractValueHandler: makeContractValueHandler(nil, nil, nil), InvalidatedResourceValidationEnabled: true, - AuthAccountHandler: func(address interpreter.AddressValue) interpreter.Value { - return newTestAuthAccountValue(nil, address) + AccountHandler: func(address interpreter.AddressValue) interpreter.Value { + return stdlib.NewAccountValue(nil, nil, address) }, }, HandleCheckerError: checkerErrorHandler, @@ -163,15 +476,7 @@ func testAccountWithErrorHandler( return inter, getAccountValues } -func returnZeroUInt64(_ *interpreter.Interpreter) interpreter.UInt64Value { - return interpreter.NewUnmeteredUInt64Value(0) -} - -func returnZeroUFix64() interpreter.UFix64Value { - return interpreter.NewUnmeteredUFix64Value(0) -} - -func TestInterpretAuthAccount_save(t *testing.T) { +func TestInterpretAccountStorageSave(t *testing.T) { t.Parallel() @@ -181,20 +486,14 @@ func TestInterpretAuthAccount_save(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, getAccountValues := testAccount( - t, - address, - true, - ` + inter, getAccountValues := testAccount(t, address, true, nil, ` resource R {} fun test() { let r <- create R() - account.save(<-r, to: /storage/r) + account.storage.save(<-r, to: /storage/r) } - `, - sema.Config{}, - ) + `, sema.Config{}) // Save first value @@ -227,20 +526,14 @@ func TestInterpretAuthAccount_save(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, getAccountValues := testAccount( - t, - address, - true, - ` + inter, getAccountValues := testAccount(t, address, true, nil, ` struct S {} fun test() { let s = S() - account.save(s, to: /storage/s) + account.storage.save(s, to: /storage/s) } - `, - sema.Config{}, - ) + `, sema.Config{}) // Save first value @@ -269,7 +562,7 @@ func TestInterpretAuthAccount_save(t *testing.T) { }) } -func TestInterpretAuthAccount_type(t *testing.T) { +func TestInterpretAccountStorageType(t *testing.T) { t.Parallel() @@ -279,32 +572,26 @@ func TestInterpretAuthAccount_type(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, getAccountStorables := testAccount( - t, - address, - true, - ` + inter, getAccountStorables := testAccount(t, address, true, nil, ` struct S {} resource R {} fun saveR() { let r <- create R() - account.save(<-r, to: /storage/x) + account.storage.save(<-r, to: /storage/x) } fun saveS() { let s = S() - destroy account.load<@R>(from: /storage/x) - account.save(s, to: /storage/x) + destroy account.storage.load<@R>(from: /storage/x) + account.storage.save(s, to: /storage/x) } fun typeAt(): AnyStruct { - return account.type(at: /storage/x) + return account.storage.type(at: /storage/x) } - `, - sema.Config{}, - ) + `, sema.Config{}) // type empty path is nil @@ -353,7 +640,7 @@ func TestInterpretAuthAccount_type(t *testing.T) { }) } -func TestInterpretAuthAccount_load(t *testing.T) { +func TestInterpretAccountStorageLoad(t *testing.T) { t.Parallel() @@ -363,30 +650,24 @@ func TestInterpretAuthAccount_load(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, getAccountValues := testAccount( - t, - address, - true, - ` + inter, getAccountValues := testAccount(t, address, true, nil, ` resource R {} resource R2 {} fun save() { let r <- create R() - account.save(<-r, to: /storage/r) + account.storage.save(<-r, to: /storage/r) } fun loadR(): @R? { - return <-account.load<@R>(from: /storage/r) + return <-account.storage.load<@R>(from: /storage/r) } fun loadR2(): @R2? { - return <-account.load<@R2>(from: /storage/r) + return <-account.storage.load<@R2>(from: /storage/r) } - `, - sema.Config{}, - ) + `, sema.Config{}) t.Run("save R and load R ", func(t *testing.T) { @@ -446,30 +727,24 @@ func TestInterpretAuthAccount_load(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, getAccountValues := testAccount( - t, - address, - true, - ` + inter, getAccountValues := testAccount(t, address, true, nil, ` struct S {} struct S2 {} fun save() { let s = S() - account.save(s, to: /storage/s) + account.storage.save(s, to: /storage/s) } fun loadS(): S? { - return account.load(from: /storage/s) + return account.storage.load(from: /storage/s) } fun loadS2(): S2? { - return account.load(from: /storage/s) + return account.storage.load(from: /storage/s) } - `, - sema.Config{}, - ) + `, sema.Config{}) t.Run("save S and load S", func(t *testing.T) { @@ -524,7 +799,7 @@ func TestInterpretAuthAccount_load(t *testing.T) { }) } -func TestInterpretAuthAccount_copy(t *testing.T) { +func TestInterpretAccountStorageCopy(t *testing.T) { t.Parallel() @@ -535,15 +810,15 @@ func TestInterpretAuthAccount_copy(t *testing.T) { fun save() { let s = S() - account.save(s, to: /storage/s) + account.storage.save(s, to: /storage/s) } fun copyS(): S? { - return account.copy(from: /storage/s) + return account.storage.copy(from: /storage/s) } fun copyS2(): S2? { - return account.copy(from: /storage/s) + return account.storage.copy(from: /storage/s) } ` @@ -553,13 +828,7 @@ func TestInterpretAuthAccount_copy(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, getAccountValues := testAccount( - t, - address, - true, - code, - sema.Config{}, - ) + inter, getAccountValues := testAccount(t, address, true, nil, code, sema.Config{}) // save @@ -594,13 +863,7 @@ func TestInterpretAuthAccount_copy(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, getAccountValues := testAccount( - t, - address, - true, - code, - sema.Config{}, - ) + inter, getAccountValues := testAccount(t, address, true, nil, code, sema.Config{}) // save @@ -621,7 +884,7 @@ func TestInterpretAuthAccount_copy(t *testing.T) { }) } -func TestInterpretAuthAccount_borrow(t *testing.T) { +func TestInterpretAccountStorageBorrow(t *testing.T) { t.Parallel() @@ -631,11 +894,7 @@ func TestInterpretAuthAccount_borrow(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, getAccountValues := testAccount( - t, - address, - true, - ` + inter, getAccountValues := testAccount(t, address, true, nil, ` resource R { let foo: Int @@ -654,47 +913,45 @@ func TestInterpretAuthAccount_borrow(t *testing.T) { fun save() { let r <- create R() - account.save(<-r, to: /storage/r) + account.storage.save(<-r, to: /storage/r) } fun checkR(): Bool { - return account.check<@R>(from: /storage/r) + return account.storage.check<@R>(from: /storage/r) } fun borrowR(): &R? { - return account.borrow<&R>(from: /storage/r) + return account.storage.borrow<&R>(from: /storage/r) } fun foo(): Int { - return account.borrow<&R>(from: /storage/r)!.foo + return account.storage.borrow<&R>(from: /storage/r)!.foo } fun checkR2(): Bool { - return account.check<@R2>(from: /storage/r) + return account.storage.check<@R2>(from: /storage/r) } fun borrowR2(): &R2? { - return account.borrow<&R2>(from: /storage/r) + return account.storage.borrow<&R2>(from: /storage/r) } fun checkR2WithInvalidPath(): Bool { - return account.check<@R2>(from: /storage/wrongpath) + return account.storage.check<@R2>(from: /storage/wrongpath) } fun changeAfterBorrow(): Int { - let ref = account.borrow<&R>(from: /storage/r)! + let ref = account.storage.borrow<&R>(from: /storage/r)! - let r <- account.load<@R>(from: /storage/r) + let r <- account.storage.load<@R>(from: /storage/r) destroy r let r2 <- create R2() - account.save(<-r2, to: /storage/r) + account.storage.save(<-r2, to: /storage/r) return ref.foo } - `, - sema.Config{}, - ) + `, sema.Config{}) // save @@ -812,11 +1069,7 @@ func TestInterpretAuthAccount_borrow(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, getAccountValues := testAccount( - t, - address, - true, - ` + inter, getAccountValues := testAccount(t, address, true, nil, ` struct S { let foo: Int @@ -835,50 +1088,48 @@ func TestInterpretAuthAccount_borrow(t *testing.T) { fun save() { let s = S() - account.save(s, to: /storage/s) + account.storage.save(s, to: /storage/s) } fun checkS(): Bool { - return account.check(from: /storage/s) + return account.storage.check(from: /storage/s) } fun borrowS(): &S? { - return account.borrow<&S>(from: /storage/s) + return account.storage.borrow<&S>(from: /storage/s) } fun foo(): Int { - return account.borrow<&S>(from: /storage/s)!.foo + return account.storage.borrow<&S>(from: /storage/s)!.foo } fun checkS2(): Bool { - return account.check(from: /storage/s) + return account.storage.check(from: /storage/s) } fun borrowS2(): &S2? { - return account.borrow<&S2>(from: /storage/s) + return account.storage.borrow<&S2>(from: /storage/s) } fun changeAfterBorrow(): Int { - let ref = account.borrow<&S>(from: /storage/s)! + let ref = account.storage.borrow<&S>(from: /storage/s)! // remove stored value - account.load(from: /storage/s) + account.storage.load(from: /storage/s) let s2 = S2() - account.save(s2, to: /storage/s) + account.storage.save(s2, to: /storage/s) return ref.foo } fun invalidBorrowS(): &S2? { let s = S() - account.save(s, to: /storage/another_s) - let borrowedS = account.borrow<&AnyStruct>(from: /storage/another_s) + account.storage.save(s, to: /storage/another_s) + let borrowedS = account.storage.borrow<&AnyStruct>(from: /storage/another_s) return borrowedS as! &S2? } - `, - sema.Config{}, - ) + `, sema.Config{}) // save @@ -990,38 +1241,45 @@ func TestInterpretAuthAccount_borrow(t *testing.T) { func TestInterpretAccountBalanceFields(t *testing.T) { t.Parallel() - for accountType, auth := range map[string]bool{ - "AuthAccount": true, - "PublicAccount": false, - } { + const availableBalance = 42 + const balance = 43 + + handler := &testAccountHandler{ + + getAccountAvailableBalance: func(_ common.Address) (uint64, error) { + return availableBalance, nil + }, + getAccountBalance: func(_ common.Address) (uint64, error) { + return balance, nil + }, + } - for _, fieldName := range []string{ - "balance", - "availableBalance", + for _, auth := range []bool{true, false} { + + for fieldName, expected := range map[string]uint64{ + "balance": balance, + "availableBalance": availableBalance, } { - testName := fmt.Sprintf( - "%s.%s", - accountType, - fieldName, - ) + testName := fmt.Sprintf("%s, auth: %v", fieldName, auth) t.Run(testName, func(t *testing.T) { - address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) + address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{0x1}) code := fmt.Sprintf( ` - fun test(): UFix64 { - return account.%s - } - `, + fun test(): UFix64 { + return account.%s + } + `, fieldName, ) inter, _ := testAccount( t, address, auth, + handler, code, sema.Config{}, ) @@ -1032,7 +1290,7 @@ func TestInterpretAccountBalanceFields(t *testing.T) { AssertValuesEqual( t, inter, - interpreter.NewUnmeteredUFix64Value(0), + interpreter.NewUnmeteredUFix64Value(expected), value, ) }) @@ -1040,45 +1298,47 @@ func TestInterpretAccountBalanceFields(t *testing.T) { } } -func TestInterpretAccount_StorageFields(t *testing.T) { +func TestInterpretAccountStorageFields(t *testing.T) { t.Parallel() - for accountType, auth := range map[string]bool{ - "AuthAccount": true, - "PublicAccount": false, - } { + const storageUsed = 42 + const storageCapacity = 43 + + handler := &testAccountHandler{ + commitStorageTemporarily: func(_ *interpreter.Interpreter) error { + return nil + }, + getStorageUsed: func(_ common.Address) (uint64, error) { + return storageUsed, nil + }, + getStorageCapacity: func(address common.Address) (uint64, error) { + return storageCapacity, nil + }, + } + + for _, auth := range []bool{true, false} { - for _, fieldName := range []string{ - "storageUsed", - "storageCapacity", + for fieldName, expected := range map[string]uint64{ + "used": storageUsed, + "capacity": storageCapacity, } { - testName := fmt.Sprintf( - "%s.%s", - accountType, - fieldName, - ) + testName := fmt.Sprintf("%s, auth: %v", fieldName, auth) t.Run(testName, func(t *testing.T) { code := fmt.Sprintf( ` - fun test(): UInt64 { - return account.%s - } - `, + fun test(): UInt64 { + return account.storage.%s + } + `, fieldName, ) - address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) + address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{0x1}) - inter, _ := testAccount( - t, - address, - auth, - code, - sema.Config{}, - ) + inter, _ := testAccount(t, address, auth, handler, code, sema.Config{}) value, err := inter.Invoke("test") require.NoError(t, err) @@ -1086,7 +1346,7 @@ func TestInterpretAccount_StorageFields(t *testing.T) { AssertValuesEqual( t, inter, - interpreter.NewUnmeteredUInt64Value(0), + interpreter.NewUnmeteredUInt64Value(expected), value, ) }) diff --git a/runtime/tests/interpreter/array_test.go b/runtime/tests/interpreter/array_test.go index 165872c980..88e65f20d9 100644 --- a/runtime/tests/interpreter/array_test.go +++ b/runtime/tests/interpreter/array_test.go @@ -43,12 +43,12 @@ func TestInterpretArrayFunctionEntitlements(t *testing.T) { arrayRef.slice(from: 1, upTo: 1) arrayRef.concat(["hello"]) - // Insertable functions + // Insert functions arrayRef.append("baz") arrayRef.appendAll(["baz"]) arrayRef.insert(at:0, "baz") - // Removable functions + // Remove functions arrayRef.remove(at: 1) arrayRef.removeFirst() arrayRef.removeLast() @@ -80,7 +80,7 @@ func TestInterpretArrayFunctionEntitlements(t *testing.T) { require.NoError(t, err) }) - t.Run("insertable reference", func(t *testing.T) { + t.Run("insert reference", func(t *testing.T) { t.Parallel() inter := parseCheckAndInterpret(t, ` @@ -95,7 +95,7 @@ func TestInterpretArrayFunctionEntitlements(t *testing.T) { arrayRef.slice(from: 1, upTo: 1) arrayRef.concat(["hello"]) - // Insertable functions + // Insert functions arrayRef.append("baz") arrayRef.appendAll(["baz"]) arrayRef.insert(at:0, "baz") @@ -106,7 +106,7 @@ func TestInterpretArrayFunctionEntitlements(t *testing.T) { require.NoError(t, err) }) - t.Run("removable reference", func(t *testing.T) { + t.Run("remove reference", func(t *testing.T) { t.Parallel() inter := parseCheckAndInterpret(t, ` @@ -121,7 +121,7 @@ func TestInterpretArrayFunctionEntitlements(t *testing.T) { arrayRef.slice(from: 1, upTo: 1) arrayRef.concat(["hello"]) - // Removable functions + // Remove functions arrayRef.remove(at: 1) arrayRef.removeFirst() arrayRef.removeLast() diff --git a/runtime/tests/interpreter/attachments_test.go b/runtime/tests/interpreter/attachments_test.go index 7a16074e3b..27d1b89818 100644 --- a/runtime/tests/interpreter/attachments_test.go +++ b/runtime/tests/interpreter/attachments_test.go @@ -470,7 +470,7 @@ func TestInterpretAttachmentResource(t *testing.T) { }) } -func TestAttachExecutionOrdering(t *testing.T) { +func TestInterpretAttachExecutionOrdering(t *testing.T) { t.Parallel() t.Run("basic", func(t *testing.T) { @@ -1441,7 +1441,7 @@ func TestInterpretAttachmentResourceReferenceInvalidation(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, address, true, ` + inter, _ := testAccount(t, address, true, nil, ` resource R {} attachment A for R { access(all) var id: UInt8 @@ -1465,7 +1465,7 @@ func TestInterpretAttachmentResourceReferenceInvalidation(t *testing.T) { var r3 <- r2 let a2 = r3[A]! a2.setID(5) - authAccount.save(<-r3, to: /storage/foo) + authAccount.storage.save(<-r3, to: /storage/foo) // Access the attachment filed from the previous reference. return a.id @@ -1473,11 +1473,9 @@ func TestInterpretAttachmentResourceReferenceInvalidation(t *testing.T) { access(all) fun returnSameRef(_ ref: &A): &A { return ref - }`, - sema.Config{ - AttachmentsEnabled: true, - }, - ) + }`, sema.Config{ + AttachmentsEnabled: true, + }) _, err := inter.Invoke("test") require.ErrorAs(t, err, &interpreter.InvalidatedResourceReferenceError{}) @@ -1489,7 +1487,7 @@ func TestInterpretAttachmentResourceReferenceInvalidation(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, address, true, ` + inter, _ := testAccount(t, address, true, nil, ` resource R {} attachment A for R { fun foo(): Int { return 3 } @@ -1504,11 +1502,9 @@ func TestInterpretAttachmentResourceReferenceInvalidation(t *testing.T) { access(all) fun returnSameRef(_ ref: &A): &A { return ref - }`, - sema.Config{ - AttachmentsEnabled: true, - }, - ) + }`, sema.Config{ + AttachmentsEnabled: true, + }) _, err := inter.Invoke("test") require.ErrorAs(t, err, &interpreter.DestroyedResourceError{}) @@ -1520,7 +1516,7 @@ func TestInterpretAttachmentResourceReferenceInvalidation(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, address, true, ` + inter, _ := testAccount(t, address, true, nil, ` resource R {} resource R2 { let r: @R @@ -1551,7 +1547,7 @@ func TestInterpretAttachmentResourceReferenceInvalidation(t *testing.T) { var r3 <- r2 let a2 = r3.r[A]! a2.setID(5) - authAccount.save(<-r3, to: /storage/foo) + authAccount.storage.save(<-r3, to: /storage/foo) // Access the attachment filed from the previous reference. return a.id @@ -1559,11 +1555,9 @@ func TestInterpretAttachmentResourceReferenceInvalidation(t *testing.T) { access(all) fun returnSameRef(_ ref: &A): &A { return ref - }`, - sema.Config{ - AttachmentsEnabled: true, - }, - ) + }`, sema.Config{ + AttachmentsEnabled: true, + }) _, err := inter.Invoke("test") require.ErrorAs(t, err, &interpreter.InvalidatedResourceReferenceError{}) @@ -1575,7 +1569,7 @@ func TestInterpretAttachmentResourceReferenceInvalidation(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, address, true, ` + inter, _ := testAccount(t, address, true, nil, ` access(all) resource R { access(all) var id: UInt8 @@ -1604,13 +1598,11 @@ func TestInterpretAttachmentResourceReferenceInvalidation(t *testing.T) { var r2 <- r r2.setID(5) - authAccount.save(<-r2, to: /storage/foo) + authAccount.storage.save(<-r2, to: /storage/foo) return ref!.id - }`, - sema.Config{ - AttachmentsEnabled: true, - }, - ) + }`, sema.Config{ + AttachmentsEnabled: true, + }) _, err := inter.Invoke("test") require.ErrorAs(t, err, &interpreter.InvalidatedResourceReferenceError{}) @@ -1622,7 +1614,7 @@ func TestInterpretAttachmentResourceReferenceInvalidation(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, address, true, ` + inter, _ := testAccount(t, address, true, nil, ` resource R {} resource R2 { let r: @R @@ -1645,11 +1637,9 @@ func TestInterpretAttachmentResourceReferenceInvalidation(t *testing.T) { access(all) fun returnSameRef(_ ref: &A): &A { return ref - }`, - sema.Config{ - AttachmentsEnabled: true, - }, - ) + }`, sema.Config{ + AttachmentsEnabled: true, + }) _, err := inter.Invoke("test") require.ErrorAs(t, err, &interpreter.DestroyedResourceError{}) @@ -1661,7 +1651,7 @@ func TestInterpretAttachmentResourceReferenceInvalidation(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, address, true, ` + inter, _ := testAccount(t, address, true, nil, ` access(all) resource R {} var ref: &A? = nil @@ -1689,13 +1679,11 @@ func TestInterpretAttachmentResourceReferenceInvalidation(t *testing.T) { var r2 <- r let a = r2[A]! a.setID(5) - authAccount.save(<-r2, to: /storage/foo) + authAccount.storage.save(<-r2, to: /storage/foo) return ref!.id - }`, - sema.Config{ - AttachmentsEnabled: true, - }, - ) + }`, sema.Config{ + AttachmentsEnabled: true, + }) _, err := inter.Invoke("test") require.ErrorAs(t, err, &interpreter.InvalidatedResourceReferenceError{}) diff --git a/runtime/tests/interpreter/composite_value_test.go b/runtime/tests/interpreter/composite_value_test.go index 228fa02e10..97c824fd46 100644 --- a/runtime/tests/interpreter/composite_value_test.go +++ b/runtime/tests/interpreter/composite_value_test.go @@ -183,18 +183,12 @@ func TestInterpretContractTransfer(t *testing.T) { contract C {} fun test() { - authAccount.save(%s, to: /storage/c) + authAccount.storage.save(%s, to: /storage/c) } `, value, ) - inter, _ := testAccount( - t, - address, - true, - code, - sema.Config{}, - ) + inter, _ := testAccount(t, address, true, nil, code, sema.Config{}) _, err := inter.Invoke("test") RequireError(t, err) diff --git a/runtime/tests/interpreter/container_mutation_test.go b/runtime/tests/interpreter/container_mutation_test.go index cd1ebe151e..1f3a0043cc 100644 --- a/runtime/tests/interpreter/container_mutation_test.go +++ b/runtime/tests/interpreter/container_mutation_test.go @@ -34,7 +34,7 @@ import ( "github.com/onflow/cadence/runtime/stdlib" ) -func TestArrayMutation(t *testing.T) { +func TestInterpetArrayMutation(t *testing.T) { t.Parallel() @@ -510,7 +510,7 @@ func TestArrayMutation(t *testing.T) { }) } -func TestDictionaryMutation(t *testing.T) { +func TestInterpretDictionaryMutation(t *testing.T) { t.Parallel() @@ -909,23 +909,24 @@ func TestDictionaryMutation(t *testing.T) { inter := parseCheckAndInterpret(t, ` struct S {} - fun test(owner: PublicAccount) { - let funcs: {String: fun(PublicAccount, [UInt64]): [S]} = {} + fun test(owner: &Account) { + let funcs: {String: fun(&Account, [UInt64]): [S]} = {} - funcs["test"] = fun (owner: PublicAccount, ids: [UInt64]): [S] { return [] } + funcs["test"] = fun (owner: &Account, ids: [UInt64]): [S] { return [] } funcs["test"]!(owner: owner, ids: [1]) } `) - owner := newTestPublicAccountValue( - inter, - interpreter.NewUnmeteredAddressValueFromBytes(common.Address{0x1}.Bytes()), + owner := stdlib.NewAccountReferenceValue( + nil, + nil, + interpreter.AddressValue{1}, + interpreter.UnauthorizedAccess, ) _, err := inter.Invoke("test", owner) require.NoError(t, err) - }) } diff --git a/runtime/tests/interpreter/dictionary_test.go b/runtime/tests/interpreter/dictionary_test.go index dd07b40234..8186aae9ec 100644 --- a/runtime/tests/interpreter/dictionary_test.go +++ b/runtime/tests/interpreter/dictionary_test.go @@ -41,10 +41,10 @@ func TestInterpretDictionaryFunctionEntitlements(t *testing.T) { dictionaryRef.containsKey("foo") dictionaryRef.forEachKey(fun(key: String): Bool {return true} ) - // Insertable functions + // Insert functions dictionaryRef.insert(key: "three", "baz") - // Removable functions + // Remove functions dictionaryRef.remove(key: "foo") } `) @@ -72,7 +72,7 @@ func TestInterpretDictionaryFunctionEntitlements(t *testing.T) { require.NoError(t, err) }) - t.Run("insertable reference", func(t *testing.T) { + t.Run("insert reference", func(t *testing.T) { t.Parallel() inter := parseCheckAndInterpret(t, ` @@ -85,7 +85,7 @@ func TestInterpretDictionaryFunctionEntitlements(t *testing.T) { dictionaryRef.containsKey("foo") dictionaryRef.forEachKey(fun(key: String): Bool {return true} ) - // Insertable functions + // Insert functions dictionaryRef.insert(key: "three", "baz") } `) @@ -94,7 +94,7 @@ func TestInterpretDictionaryFunctionEntitlements(t *testing.T) { require.NoError(t, err) }) - t.Run("removable reference", func(t *testing.T) { + t.Run("remove reference", func(t *testing.T) { t.Parallel() inter := parseCheckAndInterpret(t, ` @@ -107,7 +107,7 @@ func TestInterpretDictionaryFunctionEntitlements(t *testing.T) { dictionaryRef.containsKey("foo") dictionaryRef.forEachKey(fun(key: String): Bool {return true} ) - // Removable functions + // Remove functions dictionaryRef.remove(key: "foo") } `) diff --git a/runtime/tests/interpreter/entitlements_test.go b/runtime/tests/interpreter/entitlements_test.go index 1814f9df81..42e7c57f60 100644 --- a/runtime/tests/interpreter/entitlements_test.go +++ b/runtime/tests/interpreter/entitlements_test.go @@ -382,21 +382,16 @@ func TestInterpretEntitledReferences(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, - address, - true, - ` + inter, _ := testAccount(t, address, true, nil, ` entitlement X entitlement Y resource R {} fun test(): auth(X) &R { let r <- create R() - account.save(<-r, to: /storage/foo) - return account.borrow(from: /storage/foo)! + account.storage.save(<-r, to: /storage/foo) + return account.storage.borrow(from: /storage/foo)! } - `, - sema.Config{}, - ) + `, sema.Config{}) value, err := inter.Invoke("test") require.NoError(t, err) @@ -418,10 +413,7 @@ func TestInterpretEntitledReferences(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, - address, - true, - ` + inter, _ := testAccount(t, address, true, nil, ` entitlement X access(all) fun test(): Bool { let ref = &1 as auth(X) &Int @@ -430,9 +422,7 @@ func TestInterpretEntitledReferences(t *testing.T) { let downDownRef = downRef as? auth(X) &Int return downDownRef == nil } - `, - sema.Config{}, - ) + `, sema.Config{}) value, err := inter.Invoke("test") require.NoError(t, err) @@ -729,10 +719,7 @@ func TestInterpretEntitledReferenceCasting(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, - address, - true, - ` + inter, _ := testAccount(t, address, true, nil, ` entitlement X entitlement Y @@ -740,9 +727,7 @@ func TestInterpretEntitledReferenceCasting(t *testing.T) { let upCap = capXY as Capability return upCap as? Capability == nil } - `, - sema.Config{}, - ) + `, sema.Config{}) capXY := interpreter.NewCapabilityValue( nil, @@ -777,19 +762,14 @@ func TestInterpretEntitledReferenceCasting(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, - address, - true, - ` + inter, _ := testAccount(t, address, true, nil, ` entitlement X fun test(capX: Capability): Capability { let upCap = capX as Capability return (upCap as? Capability)! } - `, - sema.Config{}, - ) + `, sema.Config{}) capX := interpreter.NewCapabilityValue( nil, @@ -822,10 +802,7 @@ func TestInterpretEntitledReferenceCasting(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, - address, - true, - ` + inter, _ := testAccount(t, address, true, nil, ` entitlement X fun test(): Bool { @@ -833,8 +810,7 @@ func TestInterpretEntitledReferenceCasting(t *testing.T) { let upArr = arr as &Int return upArr as? auth(X) &Int == nil } - `, - sema.Config{}) + `, sema.Config{}) value, err := inter.Invoke("test") require.NoError(t, err) @@ -853,10 +829,7 @@ func TestInterpretEntitledReferenceCasting(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, - address, - true, - ` + inter, _ := testAccount(t, address, true, nil, ` entitlement X fun test(): Bool { @@ -865,8 +838,7 @@ func TestInterpretEntitledReferenceCasting(t *testing.T) { let upArr = arr as &Int? return upArr as? auth(X) &Int? == nil } - `, - sema.Config{}) + `, sema.Config{}) value, err := inter.Invoke("test") require.NoError(t, err) @@ -885,10 +857,7 @@ func TestInterpretEntitledReferenceCasting(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, - address, - true, - ` + inter, _ := testAccount(t, address, true, nil, ` entitlement X fun test(): Bool { @@ -896,8 +865,7 @@ func TestInterpretEntitledReferenceCasting(t *testing.T) { let upArr = arr as [&Int] return upArr as? [auth(X) &Int] == nil } - `, - sema.Config{}) + `, sema.Config{}) value, err := inter.Invoke("test") require.NoError(t, err) @@ -916,10 +884,7 @@ func TestInterpretEntitledReferenceCasting(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, - address, - true, - ` + inter, _ := testAccount(t, address, true, nil, ` entitlement X fun test(): Bool { @@ -927,8 +892,7 @@ func TestInterpretEntitledReferenceCasting(t *testing.T) { let upArr = arr as [∬ 2] return upArr as? [auth(X) ∬ 2] == nil } - `, - sema.Config{}) + `, sema.Config{}) value, err := inter.Invoke("test") require.NoError(t, err) @@ -947,10 +911,7 @@ func TestInterpretEntitledReferenceCasting(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, - address, - true, - ` + inter, _ := testAccount(t, address, true, nil, ` entitlement X fun test(): Bool { @@ -958,8 +919,7 @@ func TestInterpretEntitledReferenceCasting(t *testing.T) { let upArr = arr as [auth(X) ∬ 2] return upArr as? [auth(X) ∬ 2] == nil } - `, - sema.Config{}) + `, sema.Config{}) value, err := inter.Invoke("test") require.NoError(t, err) @@ -978,10 +938,7 @@ func TestInterpretEntitledReferenceCasting(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, - address, - true, - ` + inter, _ := testAccount(t, address, true, nil, ` entitlement X fun test(): Bool { @@ -989,8 +946,7 @@ func TestInterpretEntitledReferenceCasting(t *testing.T) { let upArr = arr as [&Int] return upArr[0] as? auth(X) &Int == nil } - `, - sema.Config{}) + `, sema.Config{}) value, err := inter.Invoke("test") require.NoError(t, err) @@ -1009,10 +965,7 @@ func TestInterpretEntitledReferenceCasting(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, - address, - true, - ` + inter, _ := testAccount(t, address, true, nil, ` entitlement X fun test(): Bool { @@ -1020,8 +973,7 @@ func TestInterpretEntitledReferenceCasting(t *testing.T) { let upArr = arr as [∬ 2] return upArr[0] as? auth(X) &Int == nil } - `, - sema.Config{}) + `, sema.Config{}) value, err := inter.Invoke("test") require.NoError(t, err) @@ -1040,10 +992,7 @@ func TestInterpretEntitledReferenceCasting(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, - address, - true, - ` + inter, _ := testAccount(t, address, true, nil, ` entitlement X fun test(): Bool { @@ -1051,8 +1000,7 @@ func TestInterpretEntitledReferenceCasting(t *testing.T) { let upDict = dict as {String: &Int} return upDict as? {String: auth(X) &Int} == nil } - `, - sema.Config{}) + `, sema.Config{}) value, err := inter.Invoke("test") require.NoError(t, err) @@ -1071,10 +1019,7 @@ func TestInterpretEntitledReferenceCasting(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, - address, - true, - ` + inter, _ := testAccount(t, address, true, nil, ` entitlement X fun test(): Bool { @@ -1082,8 +1027,7 @@ func TestInterpretEntitledReferenceCasting(t *testing.T) { let upDict = dict as {String: &Int} return upDict["foo"]! as? auth(X) &Int == nil } - `, - sema.Config{}) + `, sema.Config{}) value, err := inter.Invoke("test") require.NoError(t, err) @@ -1472,7 +1416,7 @@ func TestInterpretEntitlementMappingFields(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, address, true, ` + inter, _ := testAccount(t, address, true, nil, ` entitlement X entitlement Y entitlement E @@ -1492,8 +1436,8 @@ func TestInterpretEntitlementMappingFields(t *testing.T) { } fun test(): auth(Y) &Int { let s = S() - account.save(s, to: /storage/foo) - let ref = account.borrow(from: /storage/foo) + account.storage.save(s, to: /storage/foo) + let ref = account.storage.borrow(from: /storage/foo) let i = ref?.foo() return i! } @@ -2504,7 +2448,7 @@ func TestInterpretEntitledAttachments(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, address, true, ` + inter, _ := testAccount(t, address, true, nil, ` entitlement X entitlement Y entitlement Z @@ -2522,8 +2466,8 @@ func TestInterpretEntitledAttachments(t *testing.T) { access(M) attachment A for R {} fun test(): auth(F, G) &A { let r <- attach A() to <-create R() - account.save(<-r, to: /storage/foo) - let ref = account.borrow(from: /storage/foo)! + account.storage.save(<-r, to: /storage/foo) + let ref = account.storage.borrow(from: /storage/foo)! return ref[A]! } `, sema.Config{ @@ -2550,7 +2494,7 @@ func TestInterpretEntitledAttachments(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, address, true, ` + inter, _ := testAccount(t, address, true, nil, ` entitlement X entitlement Y entitlement Z @@ -2572,8 +2516,8 @@ func TestInterpretEntitledAttachments(t *testing.T) { } fun test(): auth(F, G, Y, Z) &A { let r <- attach A() to <-create R() - account.save(<-r, to: /storage/foo) - let ref = account.borrow(from: /storage/foo)! + account.storage.save(<-r, to: /storage/foo) + let ref = account.storage.borrow(from: /storage/foo)! return ref[A]!.entitled() } `, sema.Config{ @@ -2600,7 +2544,7 @@ func TestInterpretEntitledAttachments(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount(t, address, true, ` + inter, _ := testAccount(t, address, true, nil, ` entitlement X entitlement Y entitlement Z @@ -2623,8 +2567,8 @@ func TestInterpretEntitledAttachments(t *testing.T) { } fun test(): auth(X) &R { let r <- attach A() to <-create R() with (X) - account.save(<-r, to: /storage/foo) - let ref = account.borrow(from: /storage/foo)! + account.storage.save(<-r, to: /storage/foo) + let ref = account.storage.borrow(from: /storage/foo)! return ref[A]!.entitled() } `, sema.Config{ diff --git a/runtime/tests/interpreter/fixedpoint_test.go b/runtime/tests/interpreter/fixedpoint_test.go index 4575a32ab9..b099d8519e 100644 --- a/runtime/tests/interpreter/fixedpoint_test.go +++ b/runtime/tests/interpreter/fixedpoint_test.go @@ -599,7 +599,7 @@ func TestInterpretFixedPointMinMax(t *testing.T) { } } -func TestStringFixedpointConversion(t *testing.T) { +func TestInterpretStringFixedPointConversion(t *testing.T) { t.Parallel() type testcase struct { diff --git a/runtime/tests/interpreter/integers_test.go b/runtime/tests/interpreter/integers_test.go index 01b19a161d..160826e5f1 100644 --- a/runtime/tests/interpreter/integers_test.go +++ b/runtime/tests/interpreter/integers_test.go @@ -913,7 +913,7 @@ func TestInterpretIntegerMinMax(t *testing.T) { } } -func TestStringIntegerConversion(t *testing.T) { +func TestInterpretStringIntegerConversion(t *testing.T) { t.Parallel() test := func(t *testing.T, typ sema.Type) { diff --git a/runtime/tests/interpreter/interface_test.go b/runtime/tests/interpreter/interface_test.go index 43d3aac568..59ffb437f2 100644 --- a/runtime/tests/interpreter/interface_test.go +++ b/runtime/tests/interpreter/interface_test.go @@ -860,7 +860,7 @@ func TestInterpretInterfaceFunctionConditionsInheritance(t *testing.T) { }) } -func TestRuntimeNestedInterfaceCast(t *testing.T) { +func TestInterpretNestedInterfaceCast(t *testing.T) { t.Parallel() diff --git a/runtime/tests/interpreter/interpreter_test.go b/runtime/tests/interpreter/interpreter_test.go index abe3c9171e..ddcdf1afa9 100644 --- a/runtime/tests/interpreter/interpreter_test.go +++ b/runtime/tests/interpreter/interpreter_test.go @@ -33,7 +33,6 @@ import ( "github.com/onflow/cadence/runtime/ast" "github.com/onflow/cadence/runtime/common" - "github.com/onflow/cadence/runtime/errors" "github.com/onflow/cadence/runtime/interpreter" "github.com/onflow/cadence/runtime/parser" "github.com/onflow/cadence/runtime/pretty" @@ -4703,7 +4702,6 @@ func TestInterpretDictionaryIndexingAssignmentNil(t *testing.T) { AssertValueSlicesEqual( t, inter, - []interpreter.Value{ interpreter.NewUnmeteredStringValue("abc"), interpreter.NewUnmeteredIntValueFromInt64(23), @@ -5127,7 +5125,7 @@ func TestInterpretReferenceFailableDowncasting(t *testing.T) { var auth interpreter.Authorization = interpreter.UnauthorizedAccess if authorized { - auth = interpreter.ConvertSemaAccesstoStaticAuthorization( + auth = interpreter.ConvertSemaAccessToStaticAuthorization( invocation.Interpreter, sema.NewEntitlementSetAccess( []*sema.EntitlementType{getType("E").(*sema.EntitlementType)}, @@ -5377,7 +5375,6 @@ func TestInterpretArrayAppend(t *testing.T) { AssertValueSlicesEqual( t, inter, - []interpreter.Value{ interpreter.NewUnmeteredIntValueFromInt64(1), interpreter.NewUnmeteredIntValueFromInt64(2), @@ -5408,7 +5405,6 @@ func TestInterpretArrayAppendBound(t *testing.T) { AssertValueSlicesEqual( t, inter, - []interpreter.Value{ interpreter.NewUnmeteredIntValueFromInt64(1), interpreter.NewUnmeteredIntValueFromInt64(2), @@ -5438,7 +5434,6 @@ func TestInterpretArrayAppendAll(t *testing.T) { AssertValueSlicesEqual( t, inter, - []interpreter.Value{ interpreter.NewUnmeteredIntValueFromInt64(1), interpreter.NewUnmeteredIntValueFromInt64(2), @@ -5469,7 +5464,6 @@ func TestInterpretArrayAppendAllBound(t *testing.T) { AssertValueSlicesEqual( t, inter, - []interpreter.Value{ interpreter.NewUnmeteredIntValueFromInt64(1), interpreter.NewUnmeteredIntValueFromInt64(2), @@ -5498,7 +5492,6 @@ func TestInterpretArrayConcat(t *testing.T) { AssertValueSlicesEqual( t, inter, - []interpreter.Value{ interpreter.NewUnmeteredIntValueFromInt64(1), interpreter.NewUnmeteredIntValueFromInt64(2), @@ -5528,7 +5521,6 @@ func TestInterpretArrayConcatBound(t *testing.T) { AssertValueSlicesEqual( t, inter, - []interpreter.Value{ interpreter.NewUnmeteredIntValueFromInt64(1), interpreter.NewUnmeteredIntValueFromInt64(2), @@ -5558,7 +5550,6 @@ func TestInterpretArrayConcatDoesNotModifyOriginalArray(t *testing.T) { AssertValueSlicesEqual( t, inter, - []interpreter.Value{ interpreter.NewUnmeteredIntValueFromInt64(1), interpreter.NewUnmeteredIntValueFromInt64(2), @@ -5630,7 +5621,6 @@ func TestInterpretArrayInsert(t *testing.T) { AssertValueSlicesEqual( t, inter, - testCase.expectedValues, ArrayElements(inter, actualArray.(*interpreter.ArrayValue)), ) @@ -5693,7 +5683,6 @@ func TestInterpretArrayRemove(t *testing.T) { AssertValueSlicesEqual( t, inter, - []interpreter.Value{ interpreter.NewUnmeteredIntValueFromInt64(1), interpreter.NewUnmeteredIntValueFromInt64(3), @@ -5764,7 +5753,6 @@ func TestInterpretArrayRemoveFirst(t *testing.T) { AssertValueSlicesEqual( t, inter, - []interpreter.Value{ interpreter.NewUnmeteredIntValueFromInt64(2), interpreter.NewUnmeteredIntValueFromInt64(3), @@ -5826,7 +5814,6 @@ func TestInterpretArrayRemoveLast(t *testing.T) { AssertValueSlicesEqual( t, inter, - []interpreter.Value{ interpreter.NewUnmeteredIntValueFromInt64(1), interpreter.NewUnmeteredIntValueFromInt64(2), @@ -6155,7 +6142,6 @@ func TestInterpretDictionaryRemove(t *testing.T) { AssertValueSlicesEqual( t, inter, - []interpreter.Value{ interpreter.NewUnmeteredStringValue("def"), interpreter.NewUnmeteredIntValueFromInt64(2), @@ -6229,7 +6215,6 @@ func TestInterpretDictionaryKeys(t *testing.T) { AssertValueSlicesEqual( t, inter, - []interpreter.Value{ interpreter.NewUnmeteredStringValue("abc"), interpreter.NewUnmeteredStringValue("def"), @@ -7257,10 +7242,104 @@ func TestInterpretEmitEvent(t *testing.T) { AssertValueSlicesEqual( t, inter, + expectedEvents, + actualEvents, + ) +} + +func TestInterpretReferenceEventParameter(t *testing.T) { + + t.Parallel() + + var actualEvents []interpreter.Value + + inter, err := parseCheckAndInterpretWithOptions(t, + ` + event TestEvent(ref: &[{Int: String}]) + + fun test(ref: &[{Int: String}]) { + emit TestEvent(ref: ref) + } + `, + ParseCheckAndInterpretOptions{ + Config: &interpreter.Config{ + OnEventEmitted: func( + _ *interpreter.Interpreter, + _ interpreter.LocationRange, + event *interpreter.CompositeValue, + eventType *sema.CompositeType, + ) error { + actualEvents = append(actualEvents, event) + return nil + }, + }, + }, + ) + require.NoError(t, err) + + dictionaryStaticType := interpreter.NewDictionaryStaticType( + nil, + interpreter.PrimitiveStaticTypeInt, + interpreter.PrimitiveStaticTypeString, + ) + + dictionaryValue := interpreter.NewDictionaryValue( + inter, + interpreter.EmptyLocationRange, + dictionaryStaticType, + interpreter.NewUnmeteredIntValueFromInt64(42), + interpreter.NewUnmeteredStringValue("answer"), + ) + + arrayStaticType := interpreter.NewVariableSizedStaticType(nil, dictionaryStaticType) + + arrayValue := interpreter.NewArrayValue( + inter, + interpreter.EmptyLocationRange, + arrayStaticType, + common.ZeroAddress, + dictionaryValue, + ) + + ref := interpreter.NewUnmeteredEphemeralReferenceValue( + interpreter.UnauthorizedAccess, + arrayValue, + inter.MustConvertStaticToSemaType(arrayStaticType), + ) + + _, err = inter.Invoke("test", ref) + require.NoError(t, err) + + eventType := checker.RequireGlobalType(t, inter.Program.Elaboration, "TestEvent") + + expectedEvents := []interpreter.Value{ + interpreter.NewCompositeValue( + inter, + interpreter.EmptyLocationRange, + TestLocation, + TestLocation.QualifiedIdentifier(eventType.ID()), + common.CompositeKindEvent, + []interpreter.CompositeField{ + { + Name: "ref", + Value: ref, + }, + }, + common.ZeroAddress, + ), + } + + for _, event := range expectedEvents { + event.(*interpreter.CompositeValue).InitializeFunctions(inter) + } + AssertValueSlicesEqual( + t, + inter, expectedEvents, actualEvents, ) + } type testValue struct { @@ -7598,7 +7677,6 @@ func TestInterpretEmitEventParameterTypes(t *testing.T) { AssertValueSlicesEqual( t, inter, - expectedEvents, actualEvents, ) @@ -8428,9 +8506,7 @@ func TestInterpretContractAccountFieldUse(t *testing.T) { access(all) let address2 = Test.test() ` - addressValue := interpreter.AddressValue{ - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, - } + addressValue := interpreter.AddressValue(common.MustBytesToAddress([]byte{0x1})) inter, err := parseCheckAndInterpretWithOptions(t, code, ParseCheckAndInterpretOptions{ @@ -8442,8 +8518,16 @@ func TestInterpretContractAccountFieldUse(t *testing.T) { _ string, _ common.CompositeKind, ) map[string]interpreter.Value { + + accountRef := stdlib.NewAccountReferenceValue( + nil, + nil, + addressValue, + interpreter.FullyEntitledAccountAccess, + ) + return map[string]interpreter.Value{ - "account": newTestAuthAccountValue(inter, addressValue), + sema.ContractAccountFieldName: accountRef, } }, }, @@ -8840,7 +8924,6 @@ func TestInterpretHexDecode(t *testing.T) { AssertValueSlicesEqual( t, inter, - expected, ArrayElements(inter, arrayValue), ) @@ -8865,7 +8948,6 @@ func TestInterpretHexDecode(t *testing.T) { AssertValueSlicesEqual( t, inter, - expected, ArrayElements(inter, arrayValue), ) @@ -8961,9 +9043,9 @@ func TestInterpretResourceOwnerFieldUse(t *testing.T) { let r <- create R() addresses.append(r.owner?.address) - account.save(<-r, to: /storage/r) + account.storage.save(<-r, to: /storage/r) - let ref = account.borrow<&R>(from: /storage/r) + let ref = account.storage.borrow<&R>(from: /storage/r) addresses.append(ref?.owner?.address) return addresses @@ -8971,15 +9053,18 @@ func TestInterpretResourceOwnerFieldUse(t *testing.T) { ` // `authAccount` - address := common.Address{ - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, - } + address := common.MustBytesToAddress([]byte{0x1}) valueDeclaration := stdlib.StandardLibraryValue{ - Name: "account", - Type: sema.AuthAccountType, - Value: newTestAuthAccountValue(nil, interpreter.AddressValue(address)), - Kind: common.DeclarationKindConstant, + Name: "account", + Type: sema.FullyEntitledAccountReferenceType, + Value: stdlib.NewAccountReferenceValue( + nil, + nil, + interpreter.AddressValue(address), + interpreter.FullyEntitledAccountAccess, + ), + Kind: common.DeclarationKindConstant, } baseValueActivation := sema.NewVariableActivation(sema.BaseValueActivation) @@ -8996,8 +9081,8 @@ func TestInterpretResourceOwnerFieldUse(t *testing.T) { }, Config: &interpreter.Config{ BaseActivation: baseActivation, - PublicAccountHandler: func(address interpreter.AddressValue) interpreter.Value { - return newTestPublicAccountValue(nil, address) + AccountHandler: func(address interpreter.AddressValue) interpreter.Value { + return stdlib.NewAccountValue(nil, nil, address) }, }, }, @@ -9018,158 +9103,6 @@ func TestInterpretResourceOwnerFieldUse(t *testing.T) { ) } -func newPanicFunctionValue(gauge common.MemoryGauge) *interpreter.HostFunctionValue { - return interpreter.NewHostFunctionValue( - gauge, - stdlib.PanicFunction.Type.(*sema.FunctionType), - func(invocation interpreter.Invocation) interpreter.Value { - panic(errors.NewUnreachableError()) - }, - ) -} - -func newTestAuthAccountValue(gauge common.MemoryGauge, addressValue interpreter.AddressValue) interpreter.Value { - panicFunctionValue := newPanicFunctionValue(gauge) - return interpreter.NewAuthAccountValue( - gauge, - addressValue, - returnZeroUFix64, - returnZeroUFix64, - returnZeroUInt64, - returnZeroUInt64, - func() interpreter.Value { - return interpreter.NewAuthAccountContractsValue( - gauge, - addressValue, - panicFunctionValue, - panicFunctionValue, - panicFunctionValue, - panicFunctionValue, - panicFunctionValue, - func( - inter *interpreter.Interpreter, - locationRange interpreter.LocationRange, - ) *interpreter.ArrayValue { - return interpreter.NewArrayValue( - inter, - locationRange, - interpreter.VariableSizedStaticType{ - Type: interpreter.PrimitiveStaticTypeString, - }, - common.ZeroAddress, - ) - }, - ) - }, - func() interpreter.Value { - return interpreter.NewAuthAccountKeysValue( - gauge, - addressValue, - panicFunctionValue, - panicFunctionValue, - panicFunctionValue, - panicFunctionValue, - func() interpreter.UInt64Value { - panic(errors.NewUnreachableError()) - }, - ) - }, - func() interpreter.Value { - return interpreter.NewAuthAccountInboxValue( - gauge, - addressValue, - panicFunctionValue, - panicFunctionValue, - panicFunctionValue, - ) - }, - func() interpreter.Value { - return interpreter.NewAuthAccountCapabilitiesValue( - gauge, - addressValue, - panicFunctionValue, - panicFunctionValue, - panicFunctionValue, - panicFunctionValue, - func() interpreter.Value { - return interpreter.NewAuthAccountStorageCapabilitiesValue( - gauge, - addressValue, - panicFunctionValue, - panicFunctionValue, - panicFunctionValue, - panicFunctionValue, - ) - }, - func() interpreter.Value { - return interpreter.NewAuthAccountAccountCapabilitiesValue( - gauge, - addressValue, - panicFunctionValue, - panicFunctionValue, - panicFunctionValue, - panicFunctionValue, - ) - }, - ) - }, - ) -} - -func newTestPublicAccountValue(gauge common.MemoryGauge, addressValue interpreter.AddressValue) interpreter.Value { - - panicFunctionValue := newPanicFunctionValue(gauge) - - return interpreter.NewPublicAccountValue( - gauge, - addressValue, - returnZeroUFix64, - returnZeroUFix64, - returnZeroUInt64, - returnZeroUInt64, - func() interpreter.Value { - return interpreter.NewPublicAccountKeysValue( - gauge, - addressValue, - panicFunctionValue, - panicFunctionValue, - interpreter.AccountKeysCountGetter(func() interpreter.UInt64Value { - panic(errors.NewUnreachableError()) - }), - ) - }, - func() interpreter.Value { - return interpreter.NewPublicAccountContractsValue( - gauge, - addressValue, - panicFunctionValue, - panicFunctionValue, - func( - inter *interpreter.Interpreter, - locationRange interpreter.LocationRange, - ) *interpreter.ArrayValue { - return interpreter.NewArrayValue( - inter, - interpreter.EmptyLocationRange, - interpreter.VariableSizedStaticType{ - Type: interpreter.PrimitiveStaticTypeString, - }, - common.ZeroAddress, - ) - }, - ) - }, - func() interpreter.Value { - return interpreter.NewPublicAccountCapabilitiesValue( - gauge, - addressValue, - panicFunctionValue, - panicFunctionValue, - ) - }, - ) -} - func TestInterpretResourceAssignmentForceTransfer(t *testing.T) { t.Parallel() @@ -9935,7 +9868,7 @@ func BenchmarkNewInterpreter(b *testing.B) { }) } -func TestHostFunctionStaticType(t *testing.T) { +func TestInterpretHostFunctionStaticType(t *testing.T) { t.Parallel() @@ -10197,12 +10130,13 @@ func TestInterpretArrayReverse(t *testing.T) { return res } - fun originalsa(): [Int] { + + fun originalsa(): [Int] { let res: [Int] = []; for s in sa { res.append(s.test) } - + return res } @@ -10216,12 +10150,13 @@ func TestInterpretArrayReverse(t *testing.T) { return res } - fun originalsa_fixed(): [Int] { + + fun originalsa_fixed(): [Int] { let res: [Int] = []; for s in sa_fixed { res.append(s.test) } - + return res } `) @@ -11400,11 +11335,8 @@ func TestInterpretReferenceUpAndDowncast(t *testing.T) { t.Parallel() - inter, _ := testAccount(t, - interpreter.NewUnmeteredAddressValueFromBytes([]byte{0x1}), - true, - fmt.Sprintf( - ` + inter, _ := testAccount(t, interpreter.NewUnmeteredAddressValueFromBytes([]byte{0x1}), true, nil, fmt.Sprintf( + ` #allowAccountLinking struct S {} @@ -11421,11 +11353,9 @@ func TestInterpretReferenceUpAndDowncast(t *testing.T) { return (ref2 as AnyStruct) as! &%[1]s } `, - tc.typeName, - tc.code, - ), - sema.Config{}, - ) + tc.typeName, + tc.code, + ), sema.Config{}) _, err := inter.Invoke("test") require.NoError(t, err) @@ -11438,11 +11368,8 @@ func TestInterpretReferenceUpAndDowncast(t *testing.T) { t.Parallel() - inter, _ := testAccount(t, - interpreter.NewUnmeteredAddressValueFromBytes([]byte{0x1}), - true, - fmt.Sprintf( - ` + inter, _ := testAccount(t, interpreter.NewUnmeteredAddressValueFromBytes([]byte{0x1}), true, nil, fmt.Sprintf( + ` #allowAccountLinking struct S {} @@ -11455,11 +11382,9 @@ func TestInterpretReferenceUpAndDowncast(t *testing.T) { return (ref2 as AnyStruct) as! &%[1]s } `, - tc.typeName, - tc.code, - ), - sema.Config{}, - ) + tc.typeName, + tc.code, + ), sema.Config{}) _, err := inter.Invoke("test") require.NoError(t, err) @@ -11469,9 +11394,9 @@ func TestInterpretReferenceUpAndDowncast(t *testing.T) { testCases := []testCase{ { name: "account reference", - typeName: "AuthAccount", + typeName: "Account", code: ` - let ref = &account as &AuthAccount + let ref = account `, }, } @@ -11499,8 +11424,8 @@ func TestInterpretReferenceUpAndDowncast(t *testing.T) { name: fmt.Sprintf("storage reference%s", testNameSuffix), typeName: "S", code: fmt.Sprintf(` - account.save(S(), to: /storage/s) - let ref = account.borrow<%s &S>(from: /storage/s)! + account.storage.save(S(), to: /storage/s) + let ref = account.storage.borrow<%s &S>(from: /storage/s)! `, authKeyword, ), diff --git a/runtime/tests/interpreter/member_test.go b/runtime/tests/interpreter/member_test.go index 9e9af3e31d..26cb33b692 100644 --- a/runtime/tests/interpreter/member_test.go +++ b/runtime/tests/interpreter/member_test.go @@ -1129,13 +1129,29 @@ func TestInterpretMemberAccess(t *testing.T) { "{I}", "[Int]", "{Bool: String}", - "AnyStruct", - "Block", } // Test all built-in composite types - for i := interpreter.PrimitiveStaticTypeAuthAccount; i < interpreter.PrimitiveStaticType_Count; i++ { - semaType := i.SemaType() + for ty := interpreter.PrimitiveStaticType(1); ty < interpreter.PrimitiveStaticType_Count; ty++ { + if !ty.IsDefined() { + continue + } + + semaType := ty.SemaType() + + // Some primitive static types are deprecated, + // and only exist for migration purposes, + // so do not have an equivalent sema type + if semaType == nil { + continue + } + + if !semaType.ContainFieldsOrElements() || + semaType.IsResourceType() { + + continue + } + types = append(types, semaType.QualifiedString()) } diff --git a/runtime/tests/interpreter/memory_metering_test.go b/runtime/tests/interpreter/memory_metering_test.go index 5246ca9281..3bb817901b 100644 --- a/runtime/tests/interpreter/memory_metering_test.go +++ b/runtime/tests/interpreter/memory_metering_test.go @@ -693,40 +693,26 @@ func TestInterpretCompositeMetering(t *testing.T) { func TestInterpretSimpleCompositeMetering(t *testing.T) { t.Parallel() - t.Run("auth account", func(t *testing.T) { + t.Run("Account", func(t *testing.T) { t.Parallel() script := ` - access(all) fun main(a: AuthAccount) { - - } + access(all) fun main(a: &Account) {} ` meter := newTestMemoryGauge() inter := parseCheckAndInterpretWithMemoryMetering(t, script, meter) - addressValue := newRandomValueGenerator().randomAddressValue() - _, err := inter.Invoke("main", newTestAuthAccountValue(meter, addressValue)) - require.NoError(t, err) - - assert.Equal(t, uint64(1), meter.getMemory(common.MemoryKindSimpleCompositeValueBase)) - assert.Equal(t, uint64(1), meter.getMemory(common.MemoryKindSimpleCompositeValue)) - }) - - t.Run("public account", func(t *testing.T) { - t.Parallel() + address := common.MustBytesToAddress([]byte{0x1}) - script := ` - access(all) fun main(a: PublicAccount) { - - } - ` - - meter := newTestMemoryGauge() - inter := parseCheckAndInterpretWithMemoryMetering(t, script, meter) + account := stdlib.NewAccountReferenceValue( + meter, + nil, + interpreter.AddressValue(address), + interpreter.UnauthorizedAccess, + ) - addressValue := newRandomValueGenerator().randomAddressValue() - _, err := inter.Invoke("main", newTestPublicAccountValue(meter, addressValue)) + _, err := inter.Invoke("main", account) require.NoError(t, err) assert.Equal(t, uint64(1), meter.getMemory(common.MemoryKindSimpleCompositeValueBase)) @@ -6669,15 +6655,27 @@ func TestInterpretStorageReferenceValueMetering(t *testing.T) { script := ` resource R {} - access(all) fun main(account: AuthAccount) { - account.borrow<&R>(from: /storage/r) + access(all) fun main(account: auth(Storage) &Account) { + account.storage.borrow<&R>(from: /storage/r) } ` meter := newTestMemoryGauge() inter := parseCheckAndInterpretWithMemoryMetering(t, script, meter) - account := newTestAuthAccountValue(meter, interpreter.AddressValue{}) + address := common.MustBytesToAddress([]byte{0x1}) + authorization := interpreter.NewEntitlementSetAuthorization( + meter, + func() []common.TypeID { + return []common.TypeID{ + sema.StorageType.ID(), + } + }, + 1, + sema.Conjunction, + ) + account := stdlib.NewAccountReferenceValue(meter, nil, interpreter.AddressValue(address), authorization) + _, err := inter.Invoke("main", account) require.NoError(t, err) @@ -7797,14 +7795,14 @@ func TestInterpreterStringLocationMetering(t *testing.T) { script := ` struct S {} - access(all) fun main(account: AuthAccount) { + access(all) fun main() { let s = CompositeType("") } ` meter := newTestMemoryGauge() inter := parseCheckAndInterpretWithMemoryMetering(t, script, meter) - account := newTestAuthAccountValue(meter, interpreter.AddressValue{}) - _, err := inter.Invoke("main", account) + + _, err := inter.Invoke("main") require.NoError(t, err) emptyLocationStringCount := meter.getMemory(common.MemoryKindRawString) @@ -7814,15 +7812,15 @@ func TestInterpreterStringLocationMetering(t *testing.T) { script = ` struct S {} - access(all) fun main(account: AuthAccount) { + access(all) fun main() { let s = CompositeType("S.test.S") } ` meter = newTestMemoryGauge() inter = parseCheckAndInterpretWithMemoryMetering(t, script, meter) - account = newTestAuthAccountValue(meter, interpreter.AddressValue{}) - _, err = inter.Invoke("main", account) + + _, err = inter.Invoke("main") require.NoError(t, err) testLocationStringCount := meter.getMemory(common.MemoryKindRawString) @@ -8601,16 +8599,33 @@ func TestInterpretStorageMapMetering(t *testing.T) { script := ` resource R {} - access(all) fun main(account: AuthAccount) { + access(all) fun main(account: auth(Storage) &Account) { let r <- create R() - account.save(<-r, to: /storage/r) + account.storage.save(<-r, to: /storage/r) } ` meter := newTestMemoryGauge() inter := parseCheckAndInterpretWithMemoryMetering(t, script, meter) - account := newTestAuthAccountValue(meter, interpreter.AddressValue{}) + address := interpreter.AddressValue(common.MustBytesToAddress([]byte{0x1})) + authorization := interpreter.NewEntitlementSetAuthorization( + meter, + func() []common.TypeID { + return []common.TypeID{ + sema.StorageType.ID(), + } + }, + 1, + sema.Conjunction, + ) + account := stdlib.NewAccountReferenceValue( + meter, + nil, + address, + authorization, + ) + _, err := inter.Invoke("main", account) require.NoError(t, err) @@ -9024,12 +9039,26 @@ func TestInterpretStaticTypeStringConversion(t *testing.T) { continue } + semaType := primitiveStaticType.SemaType() + + // Some primitive static types are deprecated, + // and only exist for migration purposes, + // so do not have an equivalent sema type + if semaType == nil { + continue + } + + switch semaType.(type) { + case *sema.EntitlementType, + *sema.EntitlementMapType: + continue + } + script := fmt.Sprintf(` access(all) fun main() { log(Type<%s>()) }`, - sema.NewTypeAnnotation(primitiveStaticType.SemaType()). - QualifiedString(), + sema.NewTypeAnnotation(semaType).QualifiedString(), ) testStaticTypeStringConversion(t, script) diff --git a/runtime/tests/interpreter/metatype_test.go b/runtime/tests/interpreter/metatype_test.go index 434fffd512..90994ccfd6 100644 --- a/runtime/tests/interpreter/metatype_test.go +++ b/runtime/tests/interpreter/metatype_test.go @@ -522,8 +522,8 @@ func TestInterpretMetaTypeIsSubtype(t *testing.T) { { name: "resource is not a subtype of String", code: ` - resource R {} - let result = Type<@R>().isSubtype(of: Type()) + resource R {} + let result = Type<@R>().isSubtype(of: Type()) `, result: false, }, @@ -649,7 +649,8 @@ func TestInterpretGetType(t *testing.T) { // i.e. EphemeralReferenceValue.StaticType is tested name: "optional auth ephemeral reference", code: ` - entitlement X + entitlement X + fun test(): Type { let value = 1 let ref = &value as auth(X) &Int @@ -676,7 +677,8 @@ func TestInterpretGetType(t *testing.T) { // i.e. EphemeralReferenceValue.StaticType is tested name: "optional ephemeral reference, auth to unauth", code: ` - entitlement X + entitlement X + fun test(): Type { let value = 1 let ref = &value as auth(X) &Int @@ -700,7 +702,8 @@ func TestInterpretGetType(t *testing.T) { // i.e. EphemeralReferenceValue.StaticType is tested name: "optional ephemeral reference, auth to auth", code: ` - entitlement X + entitlement X + fun test(): Type { let value = 1 let ref = &value as auth(X) &Int @@ -726,11 +729,13 @@ func TestInterpretGetType(t *testing.T) { // i.e. StorageReferenceValue.StaticType is tested name: "optional storage reference, auth to unauth", code: ` - entitlement X - fun getStorageReference(): auth(X) &Int { - account.save(1, to: /storage/foo) - return account.borrow(from: /storage/foo)! - } + entitlement X + + fun getStorageReference(): auth(X) &Int { + account.storage.save(1, to: /storage/foo) + return account.storage.borrow(from: /storage/foo)! + } + fun test(): Type { let ref = getStorageReference() let optRef: &Int? = ref @@ -753,11 +758,13 @@ func TestInterpretGetType(t *testing.T) { // i.e. StorageReferenceValue.StaticType is tested name: "optional storage reference, auth to auth", code: ` - entitlement X - fun getStorageReference(): auth(X) &Int { - account.save(1, to: /storage/foo) - return account.borrow(from: /storage/foo)! - } + entitlement X + + fun getStorageReference(): auth(X) &Int { + account.storage.save(1, to: /storage/foo) + return account.storage.borrow(from: /storage/foo)! + } + fun test(): Type { let ref = getStorageReference() let optRef: auth(X) &Int? = ref @@ -795,12 +802,7 @@ func TestInterpretGetType(t *testing.T) { for _, testCase := range cases { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) t.Run(testCase.name, func(t *testing.T) { - inter, _ := testAccount(t, - address, - true, - testCase.code, - sema.Config{}, - ) + inter, _ := testAccount(t, address, true, nil, testCase.code, sema.Config{}) result, err := inter.Invoke("test") require.NoError(t, err) diff --git a/runtime/tests/interpreter/reference_test.go b/runtime/tests/interpreter/reference_test.go index f4f3b68fec..7a72fd03ae 100644 --- a/runtime/tests/interpreter/reference_test.go +++ b/runtime/tests/interpreter/reference_test.go @@ -541,11 +541,7 @@ func TestInterpretResourceReferenceInvalidationOnMove(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccountWithErrorHandler( - t, - address, - true, - ` + inter, _ := testAccountWithErrorHandler(t, address, true, nil, ` resource R { access(all) var id: Int @@ -563,14 +559,11 @@ func TestInterpretResourceReferenceInvalidationOnMove(t *testing.T) { let ref = &r as &R // Move the resource into the account - account.save(<-r, to: /storage/r) + account.storage.save(<-r, to: /storage/r) // Update the reference ref.setID(2) - }`, - sema.Config{}, - errorHandler(t), - ) + }`, sema.Config{}, errorHandler(t)) _, err := inter.Invoke("test") RequireError(t, err) @@ -583,11 +576,7 @@ func TestInterpretResourceReferenceInvalidationOnMove(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccountWithErrorHandler( - t, - address, - true, - ` + inter, _ := testAccountWithErrorHandler(t, address, true, nil, ` resource R { access(all) var id: Int @@ -601,14 +590,11 @@ func TestInterpretResourceReferenceInvalidationOnMove(t *testing.T) { let ref = &r as &R // Move the resource into the account - account.save(<-r, to: /storage/r) + account.storage.save(<-r, to: /storage/r) // 'Read' a field from the reference let id = ref.id - }`, - sema.Config{}, - errorHandler(t), - ) + }`, sema.Config{}, errorHandler(t)) _, err := inter.Invoke("test") RequireError(t, err) @@ -885,11 +871,7 @@ func TestInterpretResourceReferenceInvalidationOnMove(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount( - t, - address, - true, - ` + inter, _ := testAccount(t, address, true, nil, ` resource R { access(all) var id: Int @@ -904,17 +886,15 @@ func TestInterpretResourceReferenceInvalidationOnMove(t *testing.T) { fun test() { let r1 <-create R() - account.save(<-r1, to: /storage/r) + account.storage.save(<-r1, to: /storage/r) - let r1Ref = account.borrow<&R>(from: /storage/r)! + let r1Ref = account.storage.borrow<&R>(from: /storage/r)! - let r2 <- account.load<@R>(from: /storage/r)! + let r2 <- account.storage.load<@R>(from: /storage/r)! r1Ref.setID(2) destroy r2 - }`, - sema.Config{}, - ) + }`, sema.Config{}) _, err := inter.Invoke("test") RequireError(t, err) @@ -1388,11 +1368,7 @@ func TestInterpretResourceReferenceInvalidationOnDestroy(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccountWithErrorHandler( - t, - address, - true, - ` + inter, _ := testAccountWithErrorHandler(t, address, true, nil, ` resource R { access(all) var id: Int @@ -1413,10 +1389,7 @@ func TestInterpretResourceReferenceInvalidationOnDestroy(t *testing.T) { // Update the reference ref.setID(2) - }`, - sema.Config{}, - errorHandler(t), - ) + }`, sema.Config{}, errorHandler(t)) _, err := inter.Invoke("test") RequireError(t, err) diff --git a/runtime/tests/interpreter/resources_test.go b/runtime/tests/interpreter/resources_test.go index 615dd62c0d..7e69be2f75 100644 --- a/runtime/tests/interpreter/resources_test.go +++ b/runtime/tests/interpreter/resources_test.go @@ -1743,7 +1743,7 @@ func TestInterpretInvalidatedResourceValidation(t *testing.T) { }) } -func TestCheckResourceInvalidationWithConditionalExprInDestroy(t *testing.T) { +func TestInterpretResourceInvalidationWithConditionalExprInDestroy(t *testing.T) { t.Parallel() @@ -2048,11 +2048,7 @@ func TestInterpretOptionalResourceReference(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount( - t, - address, - true, - ` + inter, _ := testAccount(t, address, true, nil, ` resource R { access(all) let id: Int @@ -2062,8 +2058,8 @@ func TestInterpretOptionalResourceReference(t *testing.T) { } fun test() { - account.save(<-{0 : <-create R()}, to: /storage/x) - let collection = account.borrow(from: /storage/x)! + account.storage.save(<-{0 : <-create R()}, to: /storage/x) + let collection = account.storage.borrow(from: /storage/x)! let resourceRef = collection[0]! let token <- collection.remove(key: 0) @@ -2071,9 +2067,7 @@ func TestInterpretOptionalResourceReference(t *testing.T) { let x = resourceRef.id destroy token } - `, - sema.Config{}, - ) + `, sema.Config{}) _, err := inter.Invoke("test") require.Error(t, err) @@ -2086,11 +2080,7 @@ func TestInterpretArrayOptionalResourceReference(t *testing.T) { address := interpreter.NewUnmeteredAddressValueFromBytes([]byte{42}) - inter, _ := testAccount( - t, - address, - true, - ` + inter, _ := testAccount(t, address, true, nil, ` resource R { access(all) let id: Int @@ -2100,8 +2090,8 @@ func TestInterpretArrayOptionalResourceReference(t *testing.T) { } fun test() { - account.save(<-[<-create R()], to: /storage/x) - let collection = account.borrow(from: /storage/x)! + account.storage.save(<-[<-create R()], to: /storage/x) + let collection = account.storage.borrow(from: /storage/x)! let resourceRef = collection[0]! let token <- collection.remove(at: 0) @@ -2109,9 +2099,7 @@ func TestInterpretArrayOptionalResourceReference(t *testing.T) { let x = resourceRef.id destroy token } - `, - sema.Config{}, - ) + `, sema.Config{}) _, err := inter.Invoke("test") require.Error(t, err) diff --git a/runtime/tests/interpreter/transactions_test.go b/runtime/tests/interpreter/transactions_test.go index 0efb00a66d..50a1574261 100644 --- a/runtime/tests/interpreter/transactions_test.go +++ b/runtime/tests/interpreter/transactions_test.go @@ -24,6 +24,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/onflow/cadence/runtime/common" + "github.com/onflow/cadence/runtime/stdlib" . "github.com/onflow/cadence/runtime/tests/utils" "github.com/onflow/cadence/runtime/ast" @@ -226,7 +228,7 @@ func TestInterpretTransactions(t *testing.T) { inter := parseCheckAndInterpret(t, ` transaction { - prepare(signer: AuthAccount) {} + prepare(signer: &Account) {} } `) @@ -244,20 +246,14 @@ func TestInterpretTransactions(t *testing.T) { } transaction { - prepare(signer: AuthAccount) {} + prepare(signer: &Account) {} execute {} } `) - signer1 := newTestAuthAccountValue( - nil, - interpreter.AddressValue{0, 0, 0, 0, 0, 0, 0, 1}, - ) - signer2 := newTestAuthAccountValue( - nil, - interpreter.AddressValue{0, 0, 0, 0, 0, 0, 0, 2}, - ) + signer1 := stdlib.NewAccountReferenceValue(nil, nil, interpreter.AddressValue{1}, interpreter.UnauthorizedAccess) + signer2 := stdlib.NewAccountReferenceValue(nil, nil, interpreter.AddressValue{2}, interpreter.UnauthorizedAccess) // first transaction err := inter.InvokeTransaction(0, signer1) @@ -277,7 +273,7 @@ func TestInterpretTransactions(t *testing.T) { transaction(x: Int, y: Bool) { - prepare(signer: AuthAccount) { + prepare(signer: &Account) { values.append(signer.address) values.append(y) values.append(x) @@ -290,17 +286,21 @@ func TestInterpretTransactions(t *testing.T) { interpreter.TrueValue, } - prepareArguments := []interpreter.Value{ - newTestAuthAccountValue( - nil, - interpreter.AddressValue{}, - ), - } + address := common.MustBytesToAddress([]byte{0x1}) + + account := stdlib.NewAccountReferenceValue( + nil, + nil, + interpreter.AddressValue(address), + interpreter.UnauthorizedAccess, + ) + + prepareArguments := []interpreter.Value{account} arguments = append(arguments, prepareArguments...) err := inter.InvokeTransaction(0, arguments...) - assert.NoError(t, err) + require.NoError(t, err) values := inter.Globals.Get("values").GetValue() @@ -310,7 +310,7 @@ func TestInterpretTransactions(t *testing.T) { t, inter, []interpreter.Value{ - interpreter.AddressValue{}, + interpreter.AddressValue(address), interpreter.TrueValue, interpreter.NewUnmeteredIntValueFromInt64(1), }, diff --git a/runtime/tests/interpreter/values_test.go b/runtime/tests/interpreter/values_test.go index d7b9e1b9c3..1b10450836 100644 --- a/runtime/tests/interpreter/values_test.go +++ b/runtime/tests/interpreter/values_test.go @@ -48,7 +48,7 @@ const compositeMaxFields = 10 var runSmokeTests = flag.Bool("runSmokeTests", false, "Run smoke tests on values") var validateAtree = flag.Bool("validateAtree", true, "Enable atree validation") -func TestRandomMapOperations(t *testing.T) { +func TestInterpretRandomMapOperations(t *testing.T) { if !*runSmokeTests { t.Skip("smoke tests are disabled") } @@ -514,7 +514,7 @@ func TestRandomMapOperations(t *testing.T) { }) } -func TestRandomArrayOperations(t *testing.T) { +func TestInterpretRandomArrayOperations(t *testing.T) { if !*runSmokeTests { t.Skip("smoke tests are disabled") } @@ -879,7 +879,7 @@ func TestRandomArrayOperations(t *testing.T) { }) } -func TestRandomCompositeValueOperations(t *testing.T) { +func TestInterpretRandomCompositeValueOperations(t *testing.T) { if !*runSmokeTests { t.Skip("smoke tests are disabled") } diff --git a/runtime/tests/utils/utils.go b/runtime/tests/utils/utils.go index 1a03296ca8..8fcdf5d306 100644 --- a/runtime/tests/utils/utils.go +++ b/runtime/tests/utils/utils.go @@ -99,7 +99,7 @@ func DeploymentTransaction(name string, contract []byte) []byte { ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Contracts) &Account) { signer.contracts.add(name: "%s", code: "%s".decodeHex()) } } @@ -114,7 +114,7 @@ func RemovalTransaction(name string) []byte { ` transaction { - prepare(signer: AuthAccount) { + prepare(signer: auth(Contracts) &Account) { signer.contracts.remove(name: "%s") } } @@ -128,8 +128,8 @@ func UpdateTransaction(name string, contract []byte) []byte { ` transaction { - prepare(signer: AuthAccount) { - signer.contracts.update__experimental(name: "%s", code: "%s".decodeHex()) + prepare(signer: auth(Contracts) &Account) { + signer.contracts.update(name: "%s", code: "%s".decodeHex()) } } `, diff --git a/runtime/transaction_executor.go b/runtime/transaction_executor.go index 1591a8d8b0..966eb6b196 100644 --- a/runtime/transaction_executor.go +++ b/runtime/transaction_executor.go @@ -34,7 +34,6 @@ type interpreterTransactionExecutorPreparation struct { transactionType *sema.TransactionType storage *Storage program *interpreter.Program - authorizers []Address preprocessOnce sync.Once } @@ -144,19 +143,18 @@ func (executor *interpreterTransactionExecutor) preprocess() (err error) { transactionType := transactions[0] executor.transactionType = transactionType - var authorizers []Address + var authorizerAddresses []Address errors.WrapPanic(func() { - authorizers, err = runtimeInterface.GetSigningAccounts() + authorizerAddresses, err = runtimeInterface.GetSigningAccounts() }) if err != nil { return newError(err, location, codesAndPrograms) } - executor.authorizers = authorizers // check parameter count argumentCount := len(script.Arguments) - authorizerCount := len(authorizers) + authorizerCount := len(authorizerAddresses) transactionParameterCount := len(transactionType.Parameters) if argumentCount != transactionParameterCount { @@ -167,7 +165,9 @@ func (executor *interpreterTransactionExecutor) preprocess() (err error) { return newError(err, location, codesAndPrograms) } - transactionAuthorizerCount := len(transactionType.PrepareParameters) + prepareParameters := transactionType.PrepareParameters + + transactionAuthorizerCount := len(prepareParameters) if authorizerCount != transactionAuthorizerCount { err = InvalidTransactionAuthorizerCountError{ Expected: transactionAuthorizerCount, @@ -178,23 +178,54 @@ func (executor *interpreterTransactionExecutor) preprocess() (err error) { // gather authorizers - executor.interpret = executor.transactionExecutionFunction(executor.authorizerValues) + executor.interpret = executor.transactionExecutionFunction( + func(inter *interpreter.Interpreter) []interpreter.Value { + return executor.authorizerValues( + inter, + authorizerAddresses, + prepareParameters, + ) + }, + ) return nil } -func (executor *interpreterTransactionExecutor) authorizerValues(inter *interpreter.Interpreter) []interpreter.Value { +func (executor *interpreterTransactionExecutor) authorizerValues( + inter *interpreter.Interpreter, + addresses []Address, + parameters []sema.Parameter, +) []interpreter.Value { // gather authorizers - authorizerValues := make([]interpreter.Value, 0, len(executor.authorizers)) + authorizerValues := make([]interpreter.Value, 0, len(addresses)) + + for i, address := range addresses { + parameter := parameters[i] - for _, address := range executor.authorizers { addressValue := interpreter.NewAddressValue(inter, address) - authorizerValues = append( - authorizerValues, - executor.environment.NewAuthAccountValue(addressValue), + + accountValue := executor.environment.NewAccountValue(addressValue) + + referenceType, ok := parameter.TypeAnnotation.Type.(*sema.ReferenceType) + if !ok || referenceType.Type != sema.AccountType { + panic(errors.NewUnreachableError()) + } + + authorization := interpreter.ConvertSemaAccessToStaticAuthorization( + inter, + referenceType.Authorization, + ) + + accountReferenceValue := interpreter.NewEphemeralReferenceValue( + inter, + authorization, + accountValue, + sema.AccountType, ) + + authorizerValues = append(authorizerValues, accountReferenceValue) } return authorizerValues diff --git a/runtime/type_test.go b/runtime/type_test.go index 105f38b529..287d49357c 100644 --- a/runtime/type_test.go +++ b/runtime/type_test.go @@ -36,16 +36,16 @@ func TestRuntimeTypeStorage(t *testing.T) { tx1 := []byte(` transaction { - prepare(signer: AuthAccount) { - signer.save(Type(), to: /storage/intType) + prepare(signer: auth(Storage) &Account) { + signer.storage.save(Type(), to: /storage/intType) } } `) tx2 := []byte(` transaction { - prepare(signer: AuthAccount) { - let intType = signer.load(from: /storage/intType) + prepare(signer: auth(Storage) &Account) { + let intType = signer.storage.load(from: /storage/intType) log(intType?.identifier) } } @@ -209,8 +209,8 @@ func TestRuntimeBlockFieldTypes(t *testing.T) { values := value.(cadence.Array).Values require.Equal(t, 2, len(values)) - assert.IsType(t, cadence.UFix64Type{}, values[0].Type()) - assert.IsType(t, cadence.UFix64Type{}, values[1].Type()) + assert.IsType(t, cadence.UFix64Type, values[0].Type()) + assert.IsType(t, cadence.UFix64Type, values[1].Type()) assert.Equal( t, diff --git a/tools/batch-script/address_provider.go b/tools/batch-script/address_provider.go index 2573b2d44d..ce56d76e93 100644 --- a/tools/batch-script/address_provider.go +++ b/tools/batch-script/address_provider.go @@ -47,7 +47,7 @@ const endOfAccountsError = "get storage used failed" const accountStorageUsageScript = ` access(all) fun main(address: Address): UInt64 { - return getAccount(address).storageUsed + return getAccount(address).storage.used } ` diff --git a/types.go b/types.go index f6e79afc99..e0608208b5 100644 --- a/types.go +++ b/types.go @@ -25,6 +25,7 @@ import ( "sync" "github.com/onflow/cadence/runtime/common" + "github.com/onflow/cadence/runtime/interpreter" "github.com/onflow/cadence/runtime/sema" ) @@ -50,861 +51,177 @@ func (t TypeID) Equal(other Type) bool { return t == other } -// AnyType - -type AnyType struct{} - -var TheAnyType = AnyType{} - -func NewAnyType() AnyType { - return TheAnyType -} - -func (AnyType) isType() {} - -func (AnyType) ID() string { - return "Any" -} - -func (t AnyType) Equal(other Type) bool { - return t == other -} - -// AnyStructType - -type AnyStructType struct{} - -var TheAnyStructType = AnyStructType{} - -func NewAnyStructType() AnyStructType { - return TheAnyStructType -} - -func (AnyStructType) isType() {} - -func (AnyStructType) ID() string { - return "AnyStruct" -} - -func (t AnyStructType) Equal(other Type) bool { - return t == other -} - -// AnyStructAttachmentType - -type AnyStructAttachmentType struct{} - -var TheAnyStructAttachmentType = AnyStructAttachmentType{} - -func NewAnyStructAttachmentType() AnyStructAttachmentType { - return TheAnyStructAttachmentType -} - -func (AnyStructAttachmentType) isType() {} - -func (AnyStructAttachmentType) ID() string { - return "AnyStructAttachment" -} - -func (t AnyStructAttachmentType) Equal(other Type) bool { - return t == other -} - -// AnyResourceType - -type AnyResourceType struct{} - -var TheAnyResourceType = AnyResourceType{} - -func NewAnyResourceType() AnyResourceType { - return TheAnyResourceType -} - -func (AnyResourceType) isType() {} - -func (AnyResourceType) ID() string { - return "AnyResource" -} - -func (t AnyResourceType) Equal(other Type) bool { - return t == other -} - -// AnyResourceAttachmentType - -type AnyResourceAttachmentType struct{} - -var TheAnyResourceAttachmentType = AnyResourceAttachmentType{} - -func NewAnyResourceAttachmentType() AnyResourceAttachmentType { - return TheAnyResourceAttachmentType -} - -func (AnyResourceAttachmentType) isType() {} - -func (AnyResourceAttachmentType) ID() string { - return "AnyResourceAttachment" -} - -func (t AnyResourceAttachmentType) Equal(other Type) bool { - return t == other -} - -// OptionalType - -type OptionalType struct { - Type Type - typeID string -} - -var _ Type = &OptionalType{} - -func NewOptionalType(typ Type) *OptionalType { - return &OptionalType{Type: typ} -} - -func NewMeteredOptionalType(gauge common.MemoryGauge, typ Type) *OptionalType { - common.UseMemory(gauge, common.CadenceOptionalTypeMemoryUsage) - return NewOptionalType(typ) -} - -func (*OptionalType) isType() {} - -func (t *OptionalType) ID() string { - if len(t.typeID) == 0 { - t.typeID = fmt.Sprintf("%s?", t.Type.ID()) - } - return t.typeID -} - -func (t *OptionalType) Equal(other Type) bool { - otherOptional, ok := other.(*OptionalType) - if !ok { - return false - } - - return t.Type.Equal(otherOptional.Type) -} - -// MetaType - -type MetaType struct{} - -var TheMetaType = MetaType{} - -func NewMetaType() MetaType { - return TheMetaType -} - -func (MetaType) isType() {} - -func (MetaType) ID() string { - return "Type" -} - -func (t MetaType) Equal(other Type) bool { - return t == other -} - -// VoidType - -type VoidType struct{} - -var TheVoidType = VoidType{} - -func NewVoidType() VoidType { - return TheVoidType -} - -func (VoidType) isType() {} - -func (VoidType) ID() string { - return "Void" -} - -func (t VoidType) Equal(other Type) bool { - return t == other -} - -// NeverType - -type NeverType struct{} - -var TheNeverType = NeverType{} - -func NewNeverType() NeverType { - return TheNeverType -} - -func (NeverType) isType() {} - -func (NeverType) ID() string { - return "Never" -} - -func (t NeverType) Equal(other Type) bool { - return t == other -} - -// BoolType - -type BoolType struct{} - -var TheBoolType = BoolType{} - -func NewBoolType() BoolType { - return TheBoolType -} - -func (BoolType) isType() {} - -func (BoolType) ID() string { - return "Bool" -} - -func (t BoolType) Equal(other Type) bool { - return t == other -} - -// StringType - -type StringType struct{} - -var TheStringType = StringType{} - -func NewStringType() StringType { - return TheStringType -} - -func (StringType) isType() {} - -func (StringType) ID() string { - return "String" -} - -func (t StringType) Equal(other Type) bool { - return t == other -} - -// CharacterType - -type CharacterType struct{} - -var TheCharacterType = CharacterType{} - -func NewCharacterType() CharacterType { - return TheCharacterType -} - -func (CharacterType) isType() {} - -func (CharacterType) ID() string { - return "Character" -} - -func (t CharacterType) Equal(other Type) bool { - return t == other -} - -// BytesType - -type BytesType struct{} - -var TheBytesType = BytesType{} - -func NewBytesType() BytesType { - return TheBytesType -} - -func (BytesType) isType() {} - -func (BytesType) ID() string { - return "Bytes" -} - -func (t BytesType) Equal(other Type) bool { - return t == other -} - -// AddressType - -type AddressType struct{} - -var TheAddressType = AddressType{} - -func NewAddressType() AddressType { - return TheAddressType -} - -func (AddressType) isType() {} - -func (AddressType) ID() string { - return "Address" -} - -func (t AddressType) Equal(other Type) bool { - return t == other -} - -// NumberType - -type NumberType struct{} - -var TheNumberType = NumberType{} - -func NewNumberType() NumberType { - return TheNumberType -} - -func (NumberType) isType() {} - -func (NumberType) ID() string { - return "Number" -} - -func (t NumberType) Equal(other Type) bool { - return t == other -} - -// SignedNumberType - -type SignedNumberType struct{} - -var TheSignedNumberType = SignedNumberType{} - -func NewSignedNumberType() SignedNumberType { - return TheSignedNumberType -} - -func (SignedNumberType) isType() {} - -func (SignedNumberType) ID() string { - return "SignedNumber" -} - -func (t SignedNumberType) Equal(other Type) bool { - return t == other -} - -// IntegerType - -type IntegerType struct{} - -var TheIntegerType = IntegerType{} - -func NewIntegerType() IntegerType { - return TheIntegerType -} - -func (IntegerType) isType() {} - -func (IntegerType) ID() string { - return "Integer" -} - -func (t IntegerType) Equal(other Type) bool { - return t == other -} - -// SignedIntegerType - -type SignedIntegerType struct{} - -var TheSignedIntegerType = SignedIntegerType{} - -func NewSignedIntegerType() SignedIntegerType { - return TheSignedIntegerType -} - -func (SignedIntegerType) isType() {} - -func (SignedIntegerType) ID() string { - return "SignedInteger" -} - -func (t SignedIntegerType) Equal(other Type) bool { - return t == other -} - -// FixedPointType - -type FixedPointType struct{} - -var TheFixedPointType = FixedPointType{} - -func NewFixedPointType() FixedPointType { - return TheFixedPointType -} - -func (FixedPointType) isType() {} - -func (FixedPointType) ID() string { - return "FixedPoint" -} - -func (t FixedPointType) Equal(other Type) bool { - return t == other -} - -// SignedFixedPointType - -type SignedFixedPointType struct{} - -var TheSignedFixedPointType = SignedFixedPointType{} - -func NewSignedFixedPointType() SignedFixedPointType { - return TheSignedFixedPointType -} - -func (SignedFixedPointType) isType() {} - -func (SignedFixedPointType) ID() string { - return "SignedFixedPoint" -} - -func (t SignedFixedPointType) Equal(other Type) bool { - return t == other -} - -// IntType - -type IntType struct{} - -var TheIntType = IntType{} - -func NewIntType() IntType { - return TheIntType -} - -func (IntType) isType() {} - -func (IntType) ID() string { - return "Int" -} - -func (t IntType) Equal(other Type) bool { - return t == other -} - -// Int8Type - -type Int8Type struct{} - -var TheInt8Type = Int8Type{} - -func NewInt8Type() Int8Type { - return TheInt8Type -} - -func (t Int8Type) Equal(other Type) bool { - return t == other -} - -func (Int8Type) isType() {} - -func (Int8Type) ID() string { - return "Int8" -} - -// Int16Type - -type Int16Type struct{} - -var TheInt16Type = Int16Type{} - -func NewInt16Type() Int16Type { - return TheInt16Type -} - -func (Int16Type) isType() {} - -func (Int16Type) ID() string { - return "Int16" -} - -func (t Int16Type) Equal(other Type) bool { - return t == other -} - -// Int32Type - -type Int32Type struct{} - -var TheInt32Type = Int32Type{} - -func NewInt32Type() Int32Type { - return TheInt32Type -} - -func (Int32Type) isType() {} - -func (Int32Type) ID() string { - return "Int32" -} - -func (t Int32Type) Equal(other Type) bool { - return t == other -} - -// Int64Type - -type Int64Type struct{} - -var TheInt64Type = Int64Type{} - -func NewInt64Type() Int64Type { - return TheInt64Type -} - -func (Int64Type) isType() {} - -func (Int64Type) ID() string { - return "Int64" -} - -func (t Int64Type) Equal(other Type) bool { - return t == other -} - -// Int128Type - -type Int128Type struct{} - -var TheInt128Type = Int128Type{} - -func NewInt128Type() Int128Type { - return TheInt128Type -} - -func (Int128Type) isType() {} - -func (Int128Type) ID() string { - return "Int128" -} - -func (t Int128Type) Equal(other Type) bool { - return t == other -} - -// Int256Type - -type Int256Type struct{} - -var TheInt256Type = Int256Type{} - -func NewInt256Type() Int256Type { - return TheInt256Type -} - -func (Int256Type) isType() {} - -func (Int256Type) ID() string { - return "Int256" -} - -func (t Int256Type) Equal(other Type) bool { - return t == other -} - -// UIntType - -type UIntType struct{} - -var TheUIntType = UIntType{} - -func NewUIntType() UIntType { - return TheUIntType -} - -func (UIntType) isType() {} - -func (UIntType) ID() string { - return "UInt" -} - -func (t UIntType) Equal(other Type) bool { - return t == other -} - -// UInt8Type - -type UInt8Type struct{} - -var TheUInt8Type = UInt8Type{} - -func NewUInt8Type() UInt8Type { - return TheUInt8Type -} - -func (UInt8Type) isType() {} - -func (UInt8Type) ID() string { - return "UInt8" -} - -func (t UInt8Type) Equal(other Type) bool { - return t == other -} - -// UInt16Type - -type UInt16Type struct{} - -var TheUInt16Type = UInt16Type{} - -func NewUInt16Type() UInt16Type { - return TheUInt16Type -} - -func (UInt16Type) isType() {} - -func (UInt16Type) ID() string { - return "UInt16" -} - -func (t UInt16Type) Equal(other Type) bool { - return t == other -} - -// UInt32Type - -type UInt32Type struct{} - -var TheUInt32Type = UInt32Type{} - -func NewUInt32Type() UInt32Type { - return TheUInt32Type -} - -func (UInt32Type) isType() {} - -func (UInt32Type) ID() string { - return "UInt32" -} - -func (t UInt32Type) Equal(other Type) bool { - return t == other -} - -// UInt64Type - -type UInt64Type struct{} - -var TheUInt64Type = UInt64Type{} - -func NewUInt64Type() UInt64Type { - return TheUInt64Type -} - -func (UInt64Type) isType() {} - -func (UInt64Type) ID() string { - return "UInt64" -} - -func (t UInt64Type) Equal(other Type) bool { - return t == other -} - -// UInt128Type - -type UInt128Type struct{} - -var TheUInt128Type = UInt128Type{} - -func NewUInt128Type() UInt128Type { - return TheUInt128Type -} - -func (UInt128Type) isType() {} - -func (UInt128Type) ID() string { - return "UInt128" -} - -func (t UInt128Type) Equal(other Type) bool { - return t == other -} - -// UInt256Type - -type UInt256Type struct{} - -var TheUInt256Type = UInt256Type{} - -func NewUInt256Type() UInt256Type { - return TheUInt256Type -} - -func (UInt256Type) isType() {} - -func (UInt256Type) ID() string { - return "UInt256" -} - -func (t UInt256Type) Equal(other Type) bool { - return t == other -} - -// Word8Type - -type Word8Type struct{} - -var TheWord8Type = Word8Type{} - -func NewWord8Type() Word8Type { - return TheWord8Type -} - -func (Word8Type) isType() {} - -func (Word8Type) ID() string { - return "Word8" -} - -func (t Word8Type) Equal(other Type) bool { - return t == other -} - -// Word16Type - -type Word16Type struct{} - -var TheWord16Type = Word16Type{} - -func NewWord16Type() Word16Type { - return TheWord16Type -} - -func (Word16Type) isType() {} - -func (Word16Type) ID() string { - return "Word16" -} - -func (t Word16Type) Equal(other Type) bool { - return t == other -} - -// Word32Type - -type Word32Type struct{} - -var TheWord32Type = Word32Type{} - -func NewWord32Type() Word32Type { - return TheWord32Type -} - -func (Word32Type) isType() {} - -func (Word32Type) ID() string { - return "Word32" -} - -func (t Word32Type) Equal(other Type) bool { - return t == other -} - -// Word64Type - -type Word64Type struct{} - -var TheWord64Type = Word64Type{} - -func NewWord64Type() Word64Type { - return TheWord64Type -} - -func (Word64Type) isType() {} - -func (Word64Type) ID() string { - return "Word64" -} - -func (t Word64Type) Equal(other Type) bool { - return t == other -} - -// Word128Type - -type Word128Type struct{} - -var TheWord128Type = Word128Type{} +// OptionalType -func NewWord128Type() Word128Type { - return TheWord128Type +type OptionalType struct { + Type Type + typeID string } -func (Word128Type) isType() {} +var _ Type = &OptionalType{} -func (Word128Type) ID() string { - return "Word128" +func NewOptionalType(typ Type) *OptionalType { + return &OptionalType{Type: typ} } -func (t Word128Type) Equal(other Type) bool { - return t == other +func NewMeteredOptionalType(gauge common.MemoryGauge, typ Type) *OptionalType { + common.UseMemory(gauge, common.CadenceOptionalTypeMemoryUsage) + return NewOptionalType(typ) } -// Word256Type - -type Word256Type struct{} - -var TheWord256Type = Word256Type{} +func (*OptionalType) isType() {} -func NewWord256Type() Word256Type { - return TheWord256Type +func (t *OptionalType) ID() string { + if len(t.typeID) == 0 { + t.typeID = fmt.Sprintf("%s?", t.Type.ID()) + } + return t.typeID } -func (Word256Type) isType() {} - -func (Word256Type) ID() string { - return "Word256" -} +func (t *OptionalType) Equal(other Type) bool { + otherOptional, ok := other.(*OptionalType) + if !ok { + return false + } -func (t Word256Type) Equal(other Type) bool { - return t == other + return t.Type.Equal(otherOptional.Type) } -// Fix64Type - -type Fix64Type struct{} +// BytesType -var TheFix64Type = Fix64Type{} +type BytesType struct{} -func NewFix64Type() Fix64Type { - return TheFix64Type -} +var TheBytesType = BytesType{} -func (Fix64Type) isType() {} +func (BytesType) isType() {} -func (Fix64Type) ID() string { - return "Fix64" +func (BytesType) ID() string { + return "Bytes" } -func (t Fix64Type) Equal(other Type) bool { +func (t BytesType) Equal(other Type) bool { return t == other } -// UFix64Type - -type UFix64Type struct{} - -var TheUFix64Type = UFix64Type{} - -func NewUFix64Type() UFix64Type { - return TheUFix64Type -} - -func (UFix64Type) isType() {} - -func (UFix64Type) ID() string { - return "UFix64" -} - -func (t UFix64Type) Equal(other Type) bool { - return t == other -} +// PrimitiveType + +type PrimitiveType interpreter.PrimitiveStaticType + +var _ Type = PrimitiveType(interpreter.PrimitiveStaticTypeUnknown) + +func (p PrimitiveType) isType() {} + +func (p PrimitiveType) ID() string { + return string(interpreter.PrimitiveStaticType(p).SemaType().ID()) +} + +func (p PrimitiveType) Equal(other Type) bool { + otherP, ok := other.(PrimitiveType) + return ok && p == otherP +} + +var VoidType = PrimitiveType(interpreter.PrimitiveStaticTypeVoid) +var AnyType = PrimitiveType(interpreter.PrimitiveStaticTypeAny) +var NeverType = PrimitiveType(interpreter.PrimitiveStaticTypeNever) +var AnyStructType = PrimitiveType(interpreter.PrimitiveStaticTypeAnyStruct) +var AnyResourceType = PrimitiveType(interpreter.PrimitiveStaticTypeAnyResource) +var AnyStructAttachmentType = PrimitiveType(interpreter.PrimitiveStaticTypeAnyStructAttachment) +var AnyResourceAttachmentType = PrimitiveType(interpreter.PrimitiveStaticTypeAnyResourceAttachment) + +var BoolType = PrimitiveType(interpreter.PrimitiveStaticTypeBool) +var AddressType = PrimitiveType(interpreter.PrimitiveStaticTypeAddress) +var StringType = PrimitiveType(interpreter.PrimitiveStaticTypeString) +var CharacterType = PrimitiveType(interpreter.PrimitiveStaticTypeCharacter) +var MetaType = PrimitiveType(interpreter.PrimitiveStaticTypeMetaType) +var BlockType = PrimitiveType(interpreter.PrimitiveStaticTypeBlock) + +var NumberType = PrimitiveType(interpreter.PrimitiveStaticTypeNumber) +var SignedNumberType = PrimitiveType(interpreter.PrimitiveStaticTypeSignedNumber) + +var IntegerType = PrimitiveType(interpreter.PrimitiveStaticTypeInteger) +var SignedIntegerType = PrimitiveType(interpreter.PrimitiveStaticTypeSignedInteger) + +var FixedPointType = PrimitiveType(interpreter.PrimitiveStaticTypeFixedPoint) +var SignedFixedPointType = PrimitiveType(interpreter.PrimitiveStaticTypeSignedFixedPoint) + +var IntType = PrimitiveType(interpreter.PrimitiveStaticTypeInt) +var Int8Type = PrimitiveType(interpreter.PrimitiveStaticTypeInt8) +var Int16Type = PrimitiveType(interpreter.PrimitiveStaticTypeInt16) +var Int32Type = PrimitiveType(interpreter.PrimitiveStaticTypeInt32) +var Int64Type = PrimitiveType(interpreter.PrimitiveStaticTypeInt64) +var Int128Type = PrimitiveType(interpreter.PrimitiveStaticTypeInt128) +var Int256Type = PrimitiveType(interpreter.PrimitiveStaticTypeInt256) + +var UIntType = PrimitiveType(interpreter.PrimitiveStaticTypeUInt) +var UInt8Type = PrimitiveType(interpreter.PrimitiveStaticTypeUInt8) +var UInt16Type = PrimitiveType(interpreter.PrimitiveStaticTypeUInt16) +var UInt32Type = PrimitiveType(interpreter.PrimitiveStaticTypeUInt32) +var UInt64Type = PrimitiveType(interpreter.PrimitiveStaticTypeUInt64) +var UInt128Type = PrimitiveType(interpreter.PrimitiveStaticTypeUInt128) +var UInt256Type = PrimitiveType(interpreter.PrimitiveStaticTypeUInt256) + +var Word8Type = PrimitiveType(interpreter.PrimitiveStaticTypeWord8) +var Word16Type = PrimitiveType(interpreter.PrimitiveStaticTypeWord16) +var Word32Type = PrimitiveType(interpreter.PrimitiveStaticTypeWord32) +var Word64Type = PrimitiveType(interpreter.PrimitiveStaticTypeWord64) +var Word128Type = PrimitiveType(interpreter.PrimitiveStaticTypeWord128) +var Word256Type = PrimitiveType(interpreter.PrimitiveStaticTypeWord256) + +var Fix64Type = PrimitiveType(interpreter.PrimitiveStaticTypeFix64) +var UFix64Type = PrimitiveType(interpreter.PrimitiveStaticTypeUFix64) + +var PathType = PrimitiveType(interpreter.PrimitiveStaticTypePath) +var CapabilityPathType = PrimitiveType(interpreter.PrimitiveStaticTypeCapabilityPath) +var StoragePathType = PrimitiveType(interpreter.PrimitiveStaticTypeStoragePath) +var PublicPathType = PrimitiveType(interpreter.PrimitiveStaticTypePublicPath) +var PrivatePathType = PrimitiveType(interpreter.PrimitiveStaticTypePrivatePath) + +var DeployedContractType = PrimitiveType(interpreter.PrimitiveStaticTypeDeployedContract) + +var StorageCapabilityControllerType = PrimitiveType(interpreter.PrimitiveStaticTypeStorageCapabilityController) +var AccountCapabilityControllerType = PrimitiveType(interpreter.PrimitiveStaticTypeAccountCapabilityController) + +var AccountType = PrimitiveType(interpreter.PrimitiveStaticTypeAccount) +var Account_ContractsType = PrimitiveType(interpreter.PrimitiveStaticTypeAccount_Contracts) +var Account_KeysType = PrimitiveType(interpreter.PrimitiveStaticTypeAccount_Keys) +var Account_StorageType = PrimitiveType(interpreter.PrimitiveStaticTypeAccount_Storage) +var Account_InboxType = PrimitiveType(interpreter.PrimitiveStaticTypeAccount_Inbox) +var Account_CapabilitiesType = PrimitiveType(interpreter.PrimitiveStaticTypeAccount_Capabilities) +var Account_StorageCapabilitiesType = PrimitiveType(interpreter.PrimitiveStaticTypeAccount_StorageCapabilities) +var Account_AccountCapabilitiesType = PrimitiveType(interpreter.PrimitiveStaticTypeAccount_AccountCapabilities) + +var MutateType = PrimitiveType(interpreter.PrimitiveStaticTypeMutate) +var InsertType = PrimitiveType(interpreter.PrimitiveStaticTypeInsert) +var RemoveType = PrimitiveType(interpreter.PrimitiveStaticTypeRemove) +var IdentityType = PrimitiveType(interpreter.PrimitiveStaticTypeIdentity) + +var StorageType = PrimitiveType(interpreter.PrimitiveStaticTypeStorage) +var SaveValueType = PrimitiveType(interpreter.PrimitiveStaticTypeSaveValue) +var LoadValueType = PrimitiveType(interpreter.PrimitiveStaticTypeLoadValue) +var BorrowValueType = PrimitiveType(interpreter.PrimitiveStaticTypeBorrowValue) +var ContractsType = PrimitiveType(interpreter.PrimitiveStaticTypeContracts) +var AddContractType = PrimitiveType(interpreter.PrimitiveStaticTypeAddContract) +var UpdateContractType = PrimitiveType(interpreter.PrimitiveStaticTypeUpdateContract) +var RemoveContractType = PrimitiveType(interpreter.PrimitiveStaticTypeRemoveContract) +var KeysType = PrimitiveType(interpreter.PrimitiveStaticTypeKeys) +var AddKeyType = PrimitiveType(interpreter.PrimitiveStaticTypeAddKey) +var RevokeKeyType = PrimitiveType(interpreter.PrimitiveStaticTypeRevokeKey) +var InboxType = PrimitiveType(interpreter.PrimitiveStaticTypeInbox) +var PublishInboxCapabilityType = PrimitiveType(interpreter.PrimitiveStaticTypePublishInboxCapability) +var UnpublishInboxCapabilityType = PrimitiveType(interpreter.PrimitiveStaticTypeUnpublishInboxCapability) +var ClaimInboxCapabilityType = PrimitiveType(interpreter.PrimitiveStaticTypeClaimInboxCapability) +var CapabilitiesType = PrimitiveType(interpreter.PrimitiveStaticTypeCapabilities) +var StorageCapabilitiesType = PrimitiveType(interpreter.PrimitiveStaticTypeStorageCapabilities) +var AccountCapabilitiesType = PrimitiveType(interpreter.PrimitiveStaticTypeAccountCapabilities) +var PublishCapabilityType = PrimitiveType(interpreter.PrimitiveStaticTypePublishCapability) +var UnpublishCapabilityType = PrimitiveType(interpreter.PrimitiveStaticTypeUnpublishCapability) +var GetStorageCapabilityControllerType = PrimitiveType(interpreter.PrimitiveStaticTypeGetStorageCapabilityController) +var IssueStorageCapabilityControllerType = PrimitiveType(interpreter.PrimitiveStaticTypeIssueStorageCapabilityController) +var GetAccountCapabilityControllerType = PrimitiveType(interpreter.PrimitiveStaticTypeGetAccountCapabilityController) +var IssueAccountCapabilityControllerType = PrimitiveType(interpreter.PrimitiveStaticTypeIssueAccountCapabilityController) + +var CapabilitiesMappingType = PrimitiveType(interpreter.PrimitiveStaticTypeCapabilitiesMapping) +var AccountMappingType = PrimitiveType(interpreter.PrimitiveStaticTypeAccountMapping) type ArrayType interface { Type @@ -1536,7 +853,7 @@ func NewMeteredAttachmentType( fields []Field, initializers [][]Parameter, ) *AttachmentType { - common.UseMemory(gauge, common.CadenceStructTypeMemoryUsage) + common.UseMemory(gauge, common.CadenceAttachmentTypeMemoryUsage) return NewAttachmentType( location, baseType, @@ -2354,126 +1671,6 @@ func (t *IntersectionType) IntersectionSet() IntersectionSet { return t.intersectionSet } -// BlockType - -type BlockType struct{} - -var TheBlockType = BlockType{} - -func NewBlockType() BlockType { - return TheBlockType -} - -func (BlockType) isType() {} - -func (BlockType) ID() string { - return "Block" -} - -func (t BlockType) Equal(other Type) bool { - return t == other -} - -// PathType - -type PathType struct{} - -var ThePathType = PathType{} - -func NewPathType() PathType { - return ThePathType -} - -func (PathType) isType() {} - -func (PathType) ID() string { - return "Path" -} - -func (t PathType) Equal(other Type) bool { - return t == other -} - -// CapabilityPathType - -type CapabilityPathType struct{} - -var TheCapabilityPathType = CapabilityPathType{} - -func NewCapabilityPathType() CapabilityPathType { - return TheCapabilityPathType -} - -func (CapabilityPathType) isType() {} - -func (CapabilityPathType) ID() string { - return "CapabilityPath" -} - -func (t CapabilityPathType) Equal(other Type) bool { - return t == other -} - -// StoragePathType - -type StoragePathType struct{} - -var TheStoragePathType = StoragePathType{} - -func NewStoragePathType() StoragePathType { - return TheStoragePathType -} - -func (StoragePathType) isType() {} - -func (StoragePathType) ID() string { - return "StoragePath" -} - -func (t StoragePathType) Equal(other Type) bool { - return t == other -} - -// PublicPathType - -type PublicPathType struct{} - -var ThePublicPathType = PublicPathType{} - -func NewPublicPathType() PublicPathType { - return ThePublicPathType -} - -func (PublicPathType) isType() {} - -func (PublicPathType) ID() string { - return "PublicPath" -} - -func (t PublicPathType) Equal(other Type) bool { - return t == other -} - -// PrivatePathType - -type PrivatePathType struct{} - -var ThePrivatePathType = PrivatePathType{} - -func NewPrivatePathType() PrivatePathType { - return ThePrivatePathType -} - -func (PrivatePathType) isType() {} - -func (PrivatePathType) ID() string { - return "PrivatePath" -} - -func (t PrivatePathType) Equal(other Type) bool { - return t == other -} - // CapabilityType type CapabilityType struct { @@ -2601,158 +1798,6 @@ func (t *EnumType) Equal(other Type) bool { t.QualifiedIdentifier == otherType.QualifiedIdentifier } -// AuthAccountType -type AuthAccountType struct{} - -var TheAuthAccountType = AuthAccountType{} - -func NewAuthAccountType() AuthAccountType { - return TheAuthAccountType -} - -func (AuthAccountType) isType() {} - -func (AuthAccountType) ID() string { - return "AuthAccount" -} - -func (t AuthAccountType) Equal(other Type) bool { - return t == other -} - -// PublicAccountType -type PublicAccountType struct{} - -var ThePublicAccountType = PublicAccountType{} - -func NewPublicAccountType() PublicAccountType { - return ThePublicAccountType -} - -func (PublicAccountType) isType() {} - -func (PublicAccountType) ID() string { - return "PublicAccount" -} - -func (t PublicAccountType) Equal(other Type) bool { - return t == other -} - -// DeployedContractType -type DeployedContractType struct{} - -var TheDeployedContractType = DeployedContractType{} - -func NewDeployedContractType() DeployedContractType { - return TheDeployedContractType -} - -func (DeployedContractType) isType() {} - -func (DeployedContractType) ID() string { - return "DeployedContract" -} - -func (t DeployedContractType) Equal(other Type) bool { - return t == other -} - -// AuthAccountContractsType -type AuthAccountContractsType struct{} - -var TheAuthAccountContractsType = AuthAccountContractsType{} - -func NewAuthAccountContractsType() AuthAccountContractsType { - return TheAuthAccountContractsType -} - -func (AuthAccountContractsType) isType() {} - -func (AuthAccountContractsType) ID() string { - return "AuthAccount.Contracts" -} - -func (t AuthAccountContractsType) Equal(other Type) bool { - return t == other -} - -// PublicAccountContractsType -type PublicAccountContractsType struct{} - -var ThePublicAccountContractsType = PublicAccountContractsType{} - -func NewPublicAccountContractsType() PublicAccountContractsType { - return ThePublicAccountContractsType -} - -func (PublicAccountContractsType) isType() {} - -func (PublicAccountContractsType) ID() string { - return "PublicAccount.Contracts" -} - -func (t PublicAccountContractsType) Equal(other Type) bool { - return t == other -} - -// AuthAccountKeysType -type AuthAccountKeysType struct{} - -var TheAuthAccountKeysType = AuthAccountKeysType{} - -func NewAuthAccountKeysType() AuthAccountKeysType { - return TheAuthAccountKeysType -} - -func (AuthAccountKeysType) isType() {} - -func (AuthAccountKeysType) ID() string { - return "AuthAccount.Keys" -} - -func (t AuthAccountKeysType) Equal(other Type) bool { - return t == other -} - -// PublicAccountKeysType -type PublicAccountKeysType struct{} - -var ThePublicAccountKeysType = PublicAccountKeysType{} - -func NewPublicAccountKeysType() PublicAccountKeysType { - return ThePublicAccountKeysType -} - -func (PublicAccountKeysType) isType() {} - -func (PublicAccountKeysType) ID() string { - return "PublicAccount.Keys" -} - -func (t PublicAccountKeysType) Equal(other Type) bool { - return t == other -} - -// AccountKeyType -type AccountKeyType struct{} - -var TheAccountKeyType = AccountKeyType{} - -func NewAccountKeyType() AccountKeyType { - return TheAccountKeyType -} - -func (AccountKeyType) isType() {} - -func (AccountKeyType) ID() string { - return "AccountKey" -} - -func (t AccountKeyType) Equal(other Type) bool { - return t == other -} - // TypeWithCachedTypeID recursively caches type ID of type t. // This is needed because each type ID is lazily cached on // its first use in ID() to avoid performance penalty. diff --git a/types_test.go b/types_test.go index e913c34006..e8d712c023 100644 --- a/types_test.go +++ b/types_test.go @@ -38,84 +38,41 @@ func TestType_ID(t *testing.T) { } stringerTests := []testCase{ - {AnyType{}, "Any"}, - {AnyStructType{}, "AnyStruct"}, - {AnyResourceType{}, "AnyResource"}, - {NumberType{}, "Number"}, - {SignedNumberType{}, "SignedNumber"}, - {IntegerType{}, "Integer"}, - {SignedIntegerType{}, "SignedInteger"}, - {FixedPointType{}, "FixedPoint"}, - {SignedFixedPointType{}, "SignedFixedPoint"}, - {UIntType{}, "UInt"}, - {UInt8Type{}, "UInt8"}, - {UInt16Type{}, "UInt16"}, - {UInt32Type{}, "UInt32"}, - {UInt64Type{}, "UInt64"}, - {UInt128Type{}, "UInt128"}, - {UInt256Type{}, "UInt256"}, - {IntType{}, "Int"}, - {Int8Type{}, "Int8"}, - {Int16Type{}, "Int16"}, - {Int32Type{}, "Int32"}, - {Int64Type{}, "Int64"}, - {Int128Type{}, "Int128"}, - {Int256Type{}, "Int256"}, - {Word8Type{}, "Word8"}, - {Word16Type{}, "Word16"}, - {Word32Type{}, "Word32"}, - {Word64Type{}, "Word64"}, - {Word128Type{}, "Word128"}, - {Word256Type{}, "Word256"}, - {UFix64Type{}, "UFix64"}, - {Fix64Type{}, "Fix64"}, - {VoidType{}, "Void"}, - {BoolType{}, "Bool"}, - {CharacterType{}, "Character"}, - {NeverType{}, "Never"}, - {StringType{}, "String"}, + {AnyType, "Any"}, {BytesType{}, "Bytes"}, - {AddressType{}, "Address"}, - {PathType{}, "Path"}, - {StoragePathType{}, "StoragePath"}, - {CapabilityPathType{}, "CapabilityPath"}, - {PublicPathType{}, "PublicPath"}, - {PrivatePathType{}, "PrivatePath"}, - {BlockType{}, "Block"}, - {MetaType{}, "Type"}, { &CapabilityType{}, "Capability", }, { &CapabilityType{ - BorrowType: IntType{}, + BorrowType: IntType, }, "Capability", }, { &OptionalType{ - Type: StringType{}, + Type: StringType, }, "String?", }, { &VariableSizedArrayType{ - ElementType: StringType{}, + ElementType: StringType, }, "[String]", }, { &ConstantSizedArrayType{ - ElementType: StringType{}, + ElementType: StringType, Size: 2, }, "[String;2]", }, { &DictionaryType{ - KeyType: StringType{}, - ElementType: IntType{}, + KeyType: StringType, + ElementType: IntType, }, "{String:Int}", }, @@ -185,9 +142,9 @@ func TestType_ID(t *testing.T) { { &FunctionType{ Parameters: []Parameter{ - {Type: IntType{}}, + {Type: IntType}, }, - ReturnType: StringType{}, + ReturnType: StringType, }, "fun(Int):String", }, @@ -269,59 +226,8 @@ func TestTypeEquality(t *testing.T) { t.Parallel() types := []Type{ - AnyType{}, - AnyStructType{}, - AnyResourceType{}, - NumberType{}, - SignedNumberType{}, - IntegerType{}, - SignedIntegerType{}, - FixedPointType{}, - SignedFixedPointType{}, - UIntType{}, - UInt8Type{}, - UInt16Type{}, - UInt32Type{}, - UInt64Type{}, - UInt128Type{}, - UInt256Type{}, - IntType{}, - Int8Type{}, - Int16Type{}, - Int32Type{}, - Int64Type{}, - Int128Type{}, - Int256Type{}, - Word8Type{}, - Word16Type{}, - Word32Type{}, - Word64Type{}, - Word128Type{}, - Word256Type{}, - UFix64Type{}, - Fix64Type{}, - VoidType{}, - BoolType{}, - CharacterType{}, - NeverType{}, - StringType{}, - BytesType{}, - AddressType{}, - PathType{}, - StoragePathType{}, - CapabilityPathType{}, - PublicPathType{}, - PrivatePathType{}, - BlockType{}, - MetaType{}, - AuthAccountType{}, - AuthAccountKeysType{}, - AuthAccountContractsType{}, - PublicAccountType{}, - PublicAccountKeysType{}, - PublicAccountContractsType{}, - AccountKeyType{}, - DeployedContractType{}, + AnyType, + TheBytesType, } for i, source := range types { @@ -362,10 +268,10 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &CapabilityType{ - BorrowType: IntType{}, + BorrowType: IntType, } target := &CapabilityType{ - BorrowType: IntType{}, + BorrowType: IntType, } assert.True(t, source.Equal(target)) }) @@ -382,10 +288,10 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &CapabilityType{ - BorrowType: IntType{}, + BorrowType: IntType, } target := &CapabilityType{ - BorrowType: StringType{}, + BorrowType: StringType, } assert.False(t, source.Equal(target)) }) @@ -395,7 +301,7 @@ func TestTypeEquality(t *testing.T) { source := &CapabilityType{} target := &CapabilityType{ - BorrowType: StringType{}, + BorrowType: StringType, } assert.False(t, source.Equal(target)) }) @@ -404,7 +310,7 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &CapabilityType{ - BorrowType: IntType{}, + BorrowType: IntType, } target := &CapabilityType{} assert.False(t, source.Equal(target)) @@ -414,9 +320,9 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &CapabilityType{ - BorrowType: IntType{}, + BorrowType: IntType, } - target := AnyType{} + target := AnyType assert.False(t, source.Equal(target)) }) }) @@ -428,10 +334,10 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &OptionalType{ - Type: IntType{}, + Type: IntType, } target := &OptionalType{ - Type: IntType{}, + Type: IntType, } assert.True(t, source.Equal(target)) }) @@ -440,10 +346,10 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &OptionalType{ - Type: IntType{}, + Type: IntType, } target := &OptionalType{ - Type: StringType{}, + Type: StringType, } assert.False(t, source.Equal(target)) }) @@ -452,9 +358,9 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &OptionalType{ - Type: IntType{}, + Type: IntType, } - target := AnyType{} + target := AnyType assert.False(t, source.Equal(target)) }) }) @@ -466,10 +372,10 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &VariableSizedArrayType{ - ElementType: IntType{}, + ElementType: IntType, } target := &VariableSizedArrayType{ - ElementType: IntType{}, + ElementType: IntType, } assert.True(t, source.Equal(target)) }) @@ -478,10 +384,10 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &VariableSizedArrayType{ - ElementType: IntType{}, + ElementType: IntType, } target := &VariableSizedArrayType{ - ElementType: StringType{}, + ElementType: StringType, } assert.False(t, source.Equal(target)) }) @@ -490,9 +396,9 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &VariableSizedArrayType{ - ElementType: IntType{}, + ElementType: IntType, } - target := AnyType{} + target := AnyType assert.False(t, source.Equal(target)) }) }) @@ -504,11 +410,11 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &ConstantSizedArrayType{ - ElementType: IntType{}, + ElementType: IntType, Size: 3, } target := &ConstantSizedArrayType{ - ElementType: IntType{}, + ElementType: IntType, Size: 3, } assert.True(t, source.Equal(target)) @@ -518,11 +424,11 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &ConstantSizedArrayType{ - ElementType: IntType{}, + ElementType: IntType, Size: 3, } target := &ConstantSizedArrayType{ - ElementType: StringType{}, + ElementType: StringType, Size: 3, } assert.False(t, source.Equal(target)) @@ -532,11 +438,11 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &ConstantSizedArrayType{ - ElementType: IntType{}, + ElementType: IntType, Size: 3, } target := &ConstantSizedArrayType{ - ElementType: IntType{}, + ElementType: IntType, Size: 4, } assert.False(t, source.Equal(target)) @@ -546,10 +452,10 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &ConstantSizedArrayType{ - ElementType: IntType{}, + ElementType: IntType, Size: 3, } - target := AnyType{} + target := AnyType assert.False(t, source.Equal(target)) }) }) @@ -561,12 +467,12 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &DictionaryType{ - KeyType: IntType{}, - ElementType: BoolType{}, + KeyType: IntType, + ElementType: BoolType, } target := &DictionaryType{ - KeyType: IntType{}, - ElementType: BoolType{}, + KeyType: IntType, + ElementType: BoolType, } assert.True(t, source.Equal(target)) }) @@ -575,12 +481,12 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &DictionaryType{ - KeyType: IntType{}, - ElementType: BoolType{}, + KeyType: IntType, + ElementType: BoolType, } target := &DictionaryType{ - KeyType: UIntType{}, - ElementType: BoolType{}, + KeyType: UIntType, + ElementType: BoolType, } assert.False(t, source.Equal(target)) }) @@ -589,12 +495,12 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &DictionaryType{ - KeyType: IntType{}, - ElementType: BoolType{}, + KeyType: IntType, + ElementType: BoolType, } target := &DictionaryType{ - KeyType: IntType{}, - ElementType: StringType{}, + KeyType: IntType, + ElementType: StringType, } assert.False(t, source.Equal(target)) }) @@ -603,12 +509,12 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &DictionaryType{ - KeyType: IntType{}, - ElementType: BoolType{}, + KeyType: IntType, + ElementType: BoolType, } target := &DictionaryType{ - KeyType: UIntType{}, - ElementType: StringType{}, + KeyType: UIntType, + ElementType: StringType, } assert.False(t, source.Equal(target)) }) @@ -617,10 +523,10 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &DictionaryType{ - KeyType: IntType{}, - ElementType: BoolType{}, + KeyType: IntType, + ElementType: BoolType, } - target := AnyType{} + target := AnyType assert.False(t, source.Equal(target)) }) }) @@ -718,7 +624,7 @@ func TestTypeEquality(t *testing.T) { }, QualifiedIdentifier: "Bar", } - target := AnyType{} + target := AnyType assert.False(t, source.Equal(target)) }) }) @@ -816,7 +722,7 @@ func TestTypeEquality(t *testing.T) { }, QualifiedIdentifier: "Bar", } - target := AnyType{} + target := AnyType assert.False(t, source.Equal(target)) }) }) @@ -914,7 +820,7 @@ func TestTypeEquality(t *testing.T) { }, QualifiedIdentifier: "Bar", } - target := AnyType{} + target := AnyType assert.False(t, source.Equal(target)) }) }) @@ -1012,7 +918,7 @@ func TestTypeEquality(t *testing.T) { }, QualifiedIdentifier: "Bar", } - target := AnyType{} + target := AnyType assert.False(t, source.Equal(target)) }) }) @@ -1110,7 +1016,7 @@ func TestTypeEquality(t *testing.T) { }, QualifiedIdentifier: "Bar", } - target := AnyType{} + target := AnyType assert.False(t, source.Equal(target)) }) }) @@ -1208,7 +1114,7 @@ func TestTypeEquality(t *testing.T) { }, QualifiedIdentifier: "Bar", } - target := AnyType{} + target := AnyType assert.False(t, source.Equal(target)) }) }) @@ -1306,7 +1212,7 @@ func TestTypeEquality(t *testing.T) { }, QualifiedIdentifier: "Bar", } - target := AnyType{} + target := AnyType assert.False(t, source.Equal(target)) }) }) @@ -1318,24 +1224,24 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &FunctionType{ - ReturnType: StringType{}, + ReturnType: StringType, Parameters: []Parameter{ { - Type: IntType{}, + Type: IntType, }, { - Type: BoolType{}, + Type: BoolType, }, }, } target := &FunctionType{ - ReturnType: StringType{}, + ReturnType: StringType, Parameters: []Parameter{ { - Type: IntType{}, + Type: IntType, }, { - Type: BoolType{}, + Type: BoolType, }, }, } @@ -1346,18 +1252,18 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &FunctionType{ - ReturnType: StringType{}, + ReturnType: StringType, Parameters: []Parameter{ { - Type: IntType{}, + Type: IntType, }, }, } target := &FunctionType{ - ReturnType: BoolType{}, + ReturnType: BoolType, Parameters: []Parameter{ { - Type: IntType{}, + Type: IntType, }, }, } @@ -1368,18 +1274,18 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &FunctionType{ - ReturnType: StringType{}, + ReturnType: StringType, Parameters: []Parameter{ { - Type: IntType{}, + Type: IntType, }, }, } target := &FunctionType{ - ReturnType: StringType{}, + ReturnType: StringType, Parameters: []Parameter{ { - Type: StringType{}, + Type: StringType, }, }, } @@ -1390,21 +1296,21 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &FunctionType{ - ReturnType: StringType{}, + ReturnType: StringType, Parameters: []Parameter{ { - Type: IntType{}, + Type: IntType, }, }, } target := &FunctionType{ - ReturnType: StringType{}, + ReturnType: StringType, Parameters: []Parameter{ { - Type: IntType{}, + Type: IntType, }, { - Type: StringType{}, + Type: StringType, }, }, } @@ -1422,19 +1328,19 @@ func TestTypeEquality(t *testing.T) { }, Parameters: []Parameter{ { - Type: IntType{}, + Type: IntType, }, }, - ReturnType: StringType{}, + ReturnType: StringType, } target := &FunctionType{ TypeParameters: []TypeParameter{}, Parameters: []Parameter{ { - Type: IntType{}, + Type: IntType, }, }, - ReturnType: StringType{}, + ReturnType: StringType, } assert.False(t, source.Equal(target)) }) @@ -1450,10 +1356,10 @@ func TestTypeEquality(t *testing.T) { }, Parameters: []Parameter{ { - Type: IntType{}, + Type: IntType, }, }, - ReturnType: StringType{}, + ReturnType: StringType, } target := &FunctionType{ TypeParameters: []TypeParameter{ @@ -1463,10 +1369,10 @@ func TestTypeEquality(t *testing.T) { }, Parameters: []Parameter{ { - Type: IntType{}, + Type: IntType, }, }, - ReturnType: StringType{}, + ReturnType: StringType, } assert.True(t, source.Equal(target)) }) @@ -1482,24 +1388,24 @@ func TestTypeEquality(t *testing.T) { }, Parameters: []Parameter{ { - Type: IntType{}, + Type: IntType, }, }, - ReturnType: StringType{}, + ReturnType: StringType, } target := &FunctionType{ TypeParameters: []TypeParameter{ { Name: "T", - TypeBound: AnyStructType{}, + TypeBound: AnyStructType, }, }, Parameters: []Parameter{ { - Type: IntType{}, + Type: IntType, }, }, - ReturnType: StringType{}, + ReturnType: StringType, } assert.False(t, source.Equal(target)) }) @@ -1511,15 +1417,15 @@ func TestTypeEquality(t *testing.T) { TypeParameters: []TypeParameter{ { Name: "T", - TypeBound: AnyStructType{}, + TypeBound: AnyStructType, }, }, Parameters: []Parameter{ { - Type: IntType{}, + Type: IntType, }, }, - ReturnType: StringType{}, + ReturnType: StringType, } target := &FunctionType{ TypeParameters: []TypeParameter{ @@ -1529,10 +1435,10 @@ func TestTypeEquality(t *testing.T) { }, Parameters: []Parameter{ { - Type: IntType{}, + Type: IntType, }, }, - ReturnType: StringType{}, + ReturnType: StringType, } assert.False(t, source.Equal(target)) }) @@ -1544,29 +1450,29 @@ func TestTypeEquality(t *testing.T) { TypeParameters: []TypeParameter{ { Name: "T", - TypeBound: AnyResourceType{}, + TypeBound: AnyResourceType, }, }, Parameters: []Parameter{ { - Type: IntType{}, + Type: IntType, }, }, - ReturnType: StringType{}, + ReturnType: StringType, } target := &FunctionType{ TypeParameters: []TypeParameter{ { Name: "T", - TypeBound: AnyStructType{}, + TypeBound: AnyStructType, }, }, Parameters: []Parameter{ { - Type: IntType{}, + Type: IntType, }, }, - ReturnType: StringType{}, + ReturnType: StringType, } assert.False(t, source.Equal(target)) }) @@ -1578,29 +1484,29 @@ func TestTypeEquality(t *testing.T) { TypeParameters: []TypeParameter{ { Name: "T", - TypeBound: AnyResourceType{}, + TypeBound: AnyResourceType, }, }, Parameters: []Parameter{ { - Type: IntType{}, + Type: IntType, }, }, - ReturnType: StringType{}, + ReturnType: StringType, } target := &FunctionType{ TypeParameters: []TypeParameter{ { Name: "T", - TypeBound: AnyResourceType{}, + TypeBound: AnyResourceType, }, }, Parameters: []Parameter{ { - Type: IntType{}, + Type: IntType, }, }, - ReturnType: StringType{}, + ReturnType: StringType, } assert.True(t, source.Equal(target)) }) @@ -1609,14 +1515,14 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &FunctionType{ - ReturnType: StringType{}, + ReturnType: StringType, Parameters: []Parameter{ { - Type: IntType{}, + Type: IntType, }, }, } - target := AnyType{} + target := AnyType assert.False(t, source.Equal(target)) }) }) @@ -1628,11 +1534,11 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &ReferenceType{ - Type: IntType{}, + Type: IntType, Authorization: UnauthorizedAccess, } target := &ReferenceType{ - Type: IntType{}, + Type: IntType, Authorization: UnauthorizedAccess, } assert.True(t, source.Equal(target)) @@ -1642,11 +1548,11 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &ReferenceType{ - Type: IntType{}, + Type: IntType, Authorization: UnauthorizedAccess, } target := &ReferenceType{ - Type: StringType{}, + Type: StringType, Authorization: UnauthorizedAccess, } assert.False(t, source.Equal(target)) @@ -1656,11 +1562,11 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &ReferenceType{ - Type: IntType{}, + Type: IntType, Authorization: UnauthorizedAccess, } target := &ReferenceType{ - Type: IntType{}, + Type: IntType, Authorization: EntitlementMapAuthorization{TypeID: "foo"}, } assert.False(t, source.Equal(target)) @@ -1670,11 +1576,11 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &ReferenceType{ - Type: IntType{}, + Type: IntType, Authorization: EntitlementMapAuthorization{TypeID: "foo"}, } target := &ReferenceType{ - Type: IntType{}, + Type: IntType, Authorization: UnauthorizedAccess, } assert.False(t, source.Equal(target)) @@ -1684,10 +1590,10 @@ func TestTypeEquality(t *testing.T) { t.Parallel() source := &ReferenceType{ - Type: IntType{}, + Type: IntType, Authorization: EntitlementMapAuthorization{TypeID: "foo"}, } - target := AnyType{} + target := AnyType assert.False(t, source.Equal(target)) }) }) @@ -1700,14 +1606,14 @@ func TestTypeEquality(t *testing.T) { source := &IntersectionType{ Types: []Type{ - AnyType{}, - IntType{}, + AnyType, + IntType, }, } target := &IntersectionType{ Types: []Type{ - AnyType{}, - IntType{}, + AnyType, + IntType, }, } assert.True(t, source.Equal(target)) @@ -1718,14 +1624,14 @@ func TestTypeEquality(t *testing.T) { source := &IntersectionType{ Types: []Type{ - AnyType{}, - IntType{}, + AnyType, + IntType, }, } target := &IntersectionType{ Types: []Type{ - IntType{}, - AnyType{}, + IntType, + AnyType, }, } assert.True(t, source.Equal(target)) @@ -1736,15 +1642,15 @@ func TestTypeEquality(t *testing.T) { source := &IntersectionType{ Types: []Type{ - IntType{}, - AnyType{}, - IntType{}, + IntType, + AnyType, + IntType, }, } target := &IntersectionType{ Types: []Type{ - IntType{}, - AnyType{}, + IntType, + AnyType, }, } assert.True(t, source.Equal(target)) @@ -1755,14 +1661,14 @@ func TestTypeEquality(t *testing.T) { source := &IntersectionType{ Types: []Type{ - AnyType{}, - IntType{}, + AnyType, + IntType, }, } target := &IntersectionType{ Types: []Type{ - AnyType{}, - StringType{}, + AnyType, + StringType, }, } assert.False(t, source.Equal(target)) @@ -1773,13 +1679,13 @@ func TestTypeEquality(t *testing.T) { source := &IntersectionType{ Types: []Type{ - AnyType{}, + AnyType, }, } target := &IntersectionType{ Types: []Type{ - AnyType{}, - StringType{}, + AnyType, + StringType, }, } assert.False(t, source.Equal(target)) @@ -1790,10 +1696,10 @@ func TestTypeEquality(t *testing.T) { source := &IntersectionType{ Types: []Type{ - AnyType{}, + AnyType, }, } - target := AnyType{} + target := AnyType assert.False(t, source.Equal(target)) }) }) @@ -1810,7 +1716,7 @@ func TestTypeEquality(t *testing.T) { Address: common.Address{0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef}, }, QualifiedIdentifier: "Bar", - RawType: IntType{}, + RawType: IntType, } target := &EnumType{ Location: common.AddressLocation{ @@ -1818,7 +1724,7 @@ func TestTypeEquality(t *testing.T) { Address: common.Address{0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef}, }, QualifiedIdentifier: "Bar", - RawType: IntType{}, + RawType: IntType, } assert.True(t, source.Equal(target)) }) @@ -1832,7 +1738,7 @@ func TestTypeEquality(t *testing.T) { Address: common.Address{0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef}, }, QualifiedIdentifier: "Bar", - RawType: IntType{}, + RawType: IntType, } target := &EnumType{ Location: common.AddressLocation{ @@ -1840,7 +1746,7 @@ func TestTypeEquality(t *testing.T) { Address: common.Address{0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef}, }, QualifiedIdentifier: "Bar", - RawType: IntType{}, + RawType: IntType, } assert.False(t, source.Equal(target)) }) @@ -1854,7 +1760,7 @@ func TestTypeEquality(t *testing.T) { Address: common.Address{0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef}, }, QualifiedIdentifier: "Bar", - RawType: IntType{}, + RawType: IntType, } target := &EnumType{ Location: common.AddressLocation{ @@ -1862,7 +1768,7 @@ func TestTypeEquality(t *testing.T) { Address: common.Address{0, 0, 0, 0, 0, 0, 0, 0x01}, }, QualifiedIdentifier: "Bar", - RawType: IntType{}, + RawType: IntType, } assert.False(t, source.Equal(target)) }) @@ -1876,7 +1782,7 @@ func TestTypeEquality(t *testing.T) { Address: common.Address{0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef}, }, QualifiedIdentifier: "Bar", - RawType: IntType{}, + RawType: IntType, } target := &EnumType{ Location: common.AddressLocation{ @@ -1884,7 +1790,7 @@ func TestTypeEquality(t *testing.T) { Address: common.Address{0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef}, }, QualifiedIdentifier: "Baz", - RawType: IntType{}, + RawType: IntType, } assert.False(t, source.Equal(target)) }) @@ -1898,9 +1804,9 @@ func TestTypeEquality(t *testing.T) { Address: common.Address{0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef}, }, QualifiedIdentifier: "Bar", - RawType: IntType{}, + RawType: IntType, } - target := AnyType{} + target := AnyType assert.False(t, source.Equal(target)) }) }) @@ -1935,11 +1841,11 @@ func TestDecodeFields(t *testing.T) { NewOptional(NewInt(2)), String("bar"), Array{ - ArrayType: NewVariableSizedArrayType(IntType{}), + ArrayType: NewVariableSizedArrayType(IntType), Values: []Value{NewInt(1), NewInt(2)}, }, Array{ - ArrayType: NewVariableSizedArrayType(&OptionalType{Type: IntType{}}), + ArrayType: NewVariableSizedArrayType(&OptionalType{Type: IntType}), Values: []Value{ NewOptional(NewInt(1)), NewOptional(NewInt(2)), @@ -1947,18 +1853,18 @@ func TestDecodeFields(t *testing.T) { }, }, Array{ - ArrayType: NewConstantSizedArrayType(2, IntType{}), + ArrayType: NewConstantSizedArrayType(2, IntType), Values: []Value{NewInt(1), NewInt(2)}, }, Array{ - ArrayType: NewVariableSizedArrayType(AnyStructType{}), + ArrayType: NewVariableSizedArrayType(AnyStructType), Values: []Value{ NewInt(3), String("foo"), }, }, Array{ - ArrayType: NewVariableSizedArrayType(&OptionalType{Type: AnyStructType{}}), + ArrayType: NewVariableSizedArrayType(&OptionalType{Type: AnyStructType}), Values: []Value{ NewOptional(NewInt(1)), NewOptional(nil), @@ -1971,63 +1877,95 @@ func TestDecodeFields(t *testing.T) { Fields: []Field{ { Identifier: "intField", - Type: IntType{}, + Type: IntType, }, { Identifier: "stringField", - Type: StringType{}, + Type: StringType, }, { Identifier: "nilOptionalIntField", - Type: &OptionalType{Type: IntType{}}, + Type: &OptionalType{ + Type: IntType, + }, }, { Identifier: "optionalIntField", - Type: &OptionalType{Type: IntType{}}, + Type: &OptionalType{ + Type: IntType, + }, }, { Identifier: "dictField", - Type: &DictionaryType{KeyType: StringType{}, ElementType: IntType{}}, + Type: &DictionaryType{ + KeyType: StringType, + ElementType: IntType, + }, }, { Identifier: "dictOptionalField", - Type: &OptionalType{Type: &DictionaryType{KeyType: StringType{}, ElementType: &OptionalType{Type: IntType{}}}}, + Type: &OptionalType{ + Type: &DictionaryType{ + KeyType: StringType, + ElementType: &OptionalType{ + Type: IntType, + }, + }, + }, }, { Identifier: "dictAnyStructField", - Type: &DictionaryType{KeyType: StringType{}, ElementType: AnyStructType{}}, + Type: &DictionaryType{ + KeyType: StringType, + ElementType: AnyStructType, + }, }, { Identifier: "dictOptionalAnyStructField", - Type: &DictionaryType{KeyType: StringType{}, ElementType: &OptionalType{Type: AnyStructType{}}}, + Type: &DictionaryType{ + KeyType: StringType, + ElementType: &OptionalType{ + Type: AnyStructType, + }, + }, }, { Identifier: "optionalAnyStructField", - Type: &OptionalType{Type: AnyStructType{}}, + Type: &OptionalType{ + Type: AnyStructType, + }, }, { Identifier: "anyStructField", - Type: AnyStructType{}, + Type: AnyStructType, }, { Identifier: "variableArrayIntField", - Type: NewVariableSizedArrayType(IntType{}), + Type: NewVariableSizedArrayType(IntType), }, { Identifier: "variableArrayOptionalIntField", - Type: NewVariableSizedArrayType(&OptionalType{Type: IntType{}}), + Type: NewVariableSizedArrayType( + &OptionalType{ + Type: IntType, + }, + ), }, { Identifier: "fixedArrayIntField", - Type: NewConstantSizedArrayType(2, IntType{}), + Type: NewConstantSizedArrayType(2, IntType), }, { Identifier: "variableArrayAnyStructField", - Type: NewVariableSizedArrayType(AnyStructType{}), + Type: NewVariableSizedArrayType(AnyStructType), }, { Identifier: "variableArrayOptionalAnyStructField", - Type: NewVariableSizedArrayType(&OptionalType{Type: AnyStructType{}}), + Type: NewVariableSizedArrayType( + &OptionalType{ + Type: AnyStructType, + }, + ), }, }, }) diff --git a/values.go b/values.go index 65efc6e508..704024c633 100644 --- a/values.go +++ b/values.go @@ -68,7 +68,7 @@ func NewMeteredVoid(memoryGauge common.MemoryGauge) Void { func (Void) isValue() {} func (Void) Type() Type { - return TheVoidType + return VoidType } func (v Void) MeteredType(common.MemoryGauge) Type { @@ -105,7 +105,7 @@ func (Optional) isValue() {} func (o Optional) Type() Type { var innerType Type if o.Value == nil { - innerType = TheNeverType + innerType = NeverType } else { innerType = o.Value.Type() } @@ -118,7 +118,7 @@ func (o Optional) Type() Type { func (o Optional) MeteredType(gauge common.MemoryGauge) Type { var innerType Type if o.Value == nil { - innerType = TheNeverType + innerType = NeverType } else { innerType = o.Value.MeteredType(gauge) } @@ -164,7 +164,7 @@ func NewMeteredBool(memoryGauge common.MemoryGauge, b bool) Bool { func (Bool) isValue() {} func (Bool) Type() Type { - return TheBoolType + return BoolType } func (v Bool) MeteredType(common.MemoryGauge) Type { @@ -206,7 +206,7 @@ func NewMeteredString( func (String) isValue() {} func (String) Type() Type { - return TheStringType + return StringType } func (v String) MeteredType(common.MemoryGauge) Type { @@ -279,7 +279,7 @@ func NewMeteredCharacter( func (Character) isValue() {} func (Character) Type() Type { - return TheCharacterType + return CharacterType } func (v Character) MeteredType(common.MemoryGauge) Type { @@ -325,11 +325,11 @@ func BytesToMeteredAddress(memoryGauge common.MemoryGauge, b []byte) Address { func (Address) isValue() {} func (Address) Type() Type { - return TheAddressType + return AddressType } func (Address) MeteredType(common.MemoryGauge) Type { - return TheAddressType + return AddressType } func (v Address) ToGoValue() any { @@ -381,7 +381,7 @@ func NewMeteredIntFromBig( func (Int) isValue() {} func (Int) Type() Type { - return TheIntType + return IntType } func (v Int) MeteredType(common.MemoryGauge) Type { @@ -432,7 +432,7 @@ func (v Int8) ToGoValue() any { } func (Int8) Type() Type { - return TheInt8Type + return Int8Type } func (v Int8) MeteredType(common.MemoryGauge) Type { @@ -467,7 +467,7 @@ func NewMeteredInt16(memoryGauge common.MemoryGauge, v int16) Int16 { func (Int16) isValue() {} func (Int16) Type() Type { - return TheInt16Type + return Int16Type } func (v Int16) MeteredType(common.MemoryGauge) Type { @@ -508,7 +508,7 @@ func NewMeteredInt32(memoryGauge common.MemoryGauge, v int32) Int32 { func (Int32) isValue() {} func (Int32) Type() Type { - return TheInt32Type + return Int32Type } func (v Int32) MeteredType(common.MemoryGauge) Type { @@ -549,7 +549,7 @@ func NewMeteredInt64(memoryGauge common.MemoryGauge, v int64) Int64 { func (Int64) isValue() {} func (Int64) Type() Type { - return TheInt64Type + return Int64Type } func (v Int64) MeteredType(common.MemoryGauge) Type { @@ -611,7 +611,7 @@ func NewMeteredInt128FromBig( func (Int128) isValue() {} func (Int128) Type() Type { - return TheInt128Type + return Int128Type } func (v Int128) MeteredType(common.MemoryGauge) Type { @@ -679,7 +679,7 @@ func NewMeteredInt256FromBig( func (Int256) isValue() {} func (Int256) Type() Type { - return TheInt256Type + return Int256Type } func (v Int256) MeteredType(common.MemoryGauge) Type { @@ -742,7 +742,7 @@ func NewMeteredUIntFromBig( func (UInt) isValue() {} func (UInt) Type() Type { - return TheUIntType + return UIntType } func (v UInt) MeteredType(common.MemoryGauge) Type { @@ -789,7 +789,7 @@ func NewMeteredUInt8(gauge common.MemoryGauge, v uint8) UInt8 { func (UInt8) isValue() {} func (UInt8) Type() Type { - return TheUInt8Type + return UInt8Type } func (v UInt8) MeteredType(common.MemoryGauge) Type { @@ -828,7 +828,7 @@ func NewMeteredUInt16(gauge common.MemoryGauge, v uint16) UInt16 { func (UInt16) isValue() {} func (UInt16) Type() Type { - return TheUInt16Type + return UInt16Type } func (v UInt16) MeteredType(common.MemoryGauge) Type { @@ -869,7 +869,7 @@ func NewMeteredUInt32(gauge common.MemoryGauge, v uint32) UInt32 { func (UInt32) isValue() {} func (UInt32) Type() Type { - return TheUInt32Type + return UInt32Type } func (v UInt32) MeteredType(common.MemoryGauge) Type { @@ -910,7 +910,7 @@ func NewMeteredUInt64(gauge common.MemoryGauge, v uint64) UInt64 { func (UInt64) isValue() {} func (UInt64) Type() Type { - return TheUInt64Type + return UInt64Type } func (v UInt64) MeteredType(common.MemoryGauge) Type { @@ -972,7 +972,7 @@ func NewMeteredUInt128FromBig( func (UInt128) isValue() {} func (UInt128) Type() Type { - return TheUInt128Type + return UInt128Type } func (v UInt128) MeteredType(common.MemoryGauge) Type { @@ -1040,7 +1040,7 @@ func NewMeteredUInt256FromBig( func (UInt256) isValue() {} func (UInt256) Type() Type { - return TheUInt256Type + return UInt256Type } func (v UInt256) MeteredType(common.MemoryGauge) Type { @@ -1087,7 +1087,7 @@ func NewMeteredWord8(gauge common.MemoryGauge, v uint8) Word8 { func (Word8) isValue() {} func (Word8) Type() Type { - return TheWord8Type + return Word8Type } func (v Word8) MeteredType(common.MemoryGauge) Type { @@ -1126,7 +1126,7 @@ func NewMeteredWord16(gauge common.MemoryGauge, v uint16) Word16 { func (Word16) isValue() {} func (Word16) Type() Type { - return TheWord16Type + return Word16Type } func (v Word16) MeteredType(common.MemoryGauge) Type { @@ -1167,7 +1167,7 @@ func NewMeteredWord32(gauge common.MemoryGauge, v uint32) Word32 { func (Word32) isValue() {} func (Word32) Type() Type { - return TheWord32Type + return Word32Type } func (v Word32) MeteredType(common.MemoryGauge) Type { @@ -1208,7 +1208,7 @@ func NewMeteredWord64(gauge common.MemoryGauge, v uint64) Word64 { func (Word64) isValue() {} func (Word64) Type() Type { - return TheWord64Type + return Word64Type } func (v Word64) MeteredType(common.MemoryGauge) Type { @@ -1270,7 +1270,7 @@ func NewMeteredWord128FromBig( func (Word128) isValue() {} func (Word128) Type() Type { - return TheWord128Type + return Word128Type } func (v Word128) MeteredType(common.MemoryGauge) Type { @@ -1338,7 +1338,7 @@ func NewMeteredWord256FromBig( func (Word256) isValue() {} func (Word256) Type() Type { - return TheWord256Type + return Word256Type } func (v Word256) MeteredType(common.MemoryGauge) Type { @@ -1411,7 +1411,7 @@ func NewMeteredFix64FromRawFixedPointNumber(gauge common.MemoryGauge, n int64) ( func (Fix64) isValue() {} func (Fix64) Type() Type { - return TheFix64Type + return Fix64Type } func (v Fix64) MeteredType(common.MemoryGauge) Type { @@ -1485,7 +1485,7 @@ func NewMeteredUFix64FromRawFixedPointNumber(gauge common.MemoryGauge, n uint64) func (UFix64) isValue() {} func (UFix64) Type() Type { - return TheUFix64Type + return UFix64Type } func (v UFix64) MeteredType(common.MemoryGauge) Type { @@ -2089,11 +2089,11 @@ func (Path) isValue() {} func (v Path) Type() Type { switch v.Domain { case common.PathDomainStorage: - return TheStoragePathType + return StoragePathType case common.PathDomainPrivate: - return ThePrivatePathType + return PrivatePathType case common.PathDomainPublic: - return ThePublicPathType + return PublicPathType } panic(errors.NewUnreachableError()) @@ -2136,7 +2136,7 @@ func NewMeteredTypeValue(gauge common.MemoryGauge, staticType Type) TypeValue { func (TypeValue) isValue() {} func (TypeValue) Type() Type { - return TheMetaType + return MetaType } func (v TypeValue) MeteredType(common.MemoryGauge) Type { diff --git a/values_test.go b/values_test.go index 55b1790783..a86ab1e740 100644 --- a/values_test.go +++ b/values_test.go @@ -50,159 +50,159 @@ func newValueTestCases() map[string]valueTestCase { nil, []Parameter{ { - Type: StringType{}, + Type: StringType, }, }, - UInt8Type{}, + UInt8Type, ) return map[string]valueTestCase{ "UInt": { value: NewUInt(10), string: "10", - expectedType: UIntType{}, + expectedType: UIntType, }, "UInt8": { value: NewUInt8(8), string: "8", - expectedType: UInt8Type{}, + expectedType: UInt8Type, }, "UInt16": { value: NewUInt16(16), string: "16", - expectedType: UInt16Type{}, + expectedType: UInt16Type, }, "UInt32": { value: NewUInt32(32), string: "32", - expectedType: UInt32Type{}, + expectedType: UInt32Type, }, "UInt64": { value: NewUInt64(64), string: "64", - expectedType: UInt64Type{}, + expectedType: UInt64Type, }, "UInt128": { value: NewUInt128(128), string: "128", - expectedType: UInt128Type{}, + expectedType: UInt128Type, }, "UInt256": { value: NewUInt256(256), string: "256", - expectedType: UInt256Type{}, + expectedType: UInt256Type, }, "Int": { value: NewInt(1000000), string: "1000000", - expectedType: IntType{}, + expectedType: IntType, }, "Int8": { value: NewInt8(-8), string: "-8", - expectedType: Int8Type{}, + expectedType: Int8Type, }, "Int16": { value: NewInt16(-16), string: "-16", - expectedType: Int16Type{}, + expectedType: Int16Type, }, "Int32": { value: NewInt32(-32), string: "-32", - expectedType: Int32Type{}, + expectedType: Int32Type, }, "Int64": { value: NewInt64(-64), string: "-64", - expectedType: Int64Type{}, + expectedType: Int64Type, }, "Int128": { value: NewInt128(-128), string: "-128", - expectedType: Int128Type{}, + expectedType: Int128Type, }, "Int256": { value: NewInt256(-256), string: "-256", - expectedType: Int256Type{}, + expectedType: Int256Type, }, "Word8": { value: NewWord8(8), string: "8", - expectedType: Word8Type{}, + expectedType: Word8Type, }, "Word16": { value: NewWord16(16), string: "16", - expectedType: Word16Type{}, + expectedType: Word16Type, }, "Word32": { value: NewWord32(32), string: "32", - expectedType: Word32Type{}, + expectedType: Word32Type, }, "Word64": { value: NewWord64(64), string: "64", - expectedType: Word64Type{}, + expectedType: Word64Type, }, "Word128": { value: NewWord128(128), string: "128", - expectedType: Word128Type{}, + expectedType: Word128Type, }, "Word256": { value: NewWord256(256), string: "256", - expectedType: Word256Type{}, + expectedType: Word256Type, }, "UFix64": { value: ufix64, string: "64.01000000", - expectedType: UFix64Type{}, + expectedType: UFix64Type, }, "Fix64": { value: fix64, string: "-32.11000000", - expectedType: Fix64Type{}, + expectedType: Fix64Type, }, "Void": { value: NewVoid(), string: "()", - expectedType: VoidType{}, + expectedType: VoidType, }, "Bool": { value: NewBool(true), string: "true", - expectedType: BoolType{}, + expectedType: BoolType, }, "some": { value: NewOptional(ufix64), string: "64.01000000", - expectedType: NewOptionalType(UFix64Type{}), + expectedType: NewOptionalType(UFix64Type), }, "nil": { value: NewOptional(nil), string: "nil", - expectedType: NewOptionalType(NeverType{}), + expectedType: NewOptionalType(NeverType), }, "String": { value: String("Flow ridah!"), string: "\"Flow ridah!\"", - expectedType: StringType{}, + expectedType: StringType, }, "Character": { value: Character("✌️"), string: "\"\\u{270c}\\u{fe0f}\"", - expectedType: CharacterType{}, + expectedType: CharacterType, }, "Array": { value: NewArray([]Value{ NewInt(10), String("TEST"), }), - exampleType: NewConstantSizedArrayType(2, AnyType{}), + exampleType: NewConstantSizedArrayType(2, AnyType), withType: func(value Value, ty Type) Value { return value.(Array).WithType(ty.(ArrayType)) }, @@ -215,7 +215,7 @@ func newValueTestCases() map[string]valueTestCase { Value: String("value"), }, }), - exampleType: NewDictionaryType(StringType{}, StringType{}), + exampleType: NewDictionaryType(StringType, StringType), withType: func(value Value, ty Type) Value { return value.(Dictionary).WithType(ty.(*DictionaryType)) }, @@ -224,12 +224,12 @@ func newValueTestCases() map[string]valueTestCase { "Bytes": { value: NewBytes([]byte{0x1, 0x2}), string: "[0x1, 0x2]", - expectedType: BytesType{}, + expectedType: TheBytesType, }, "Address": { value: NewAddress([8]byte{0, 0, 0, 0, 0, 0, 0, 1}), string: "0x0000000000000001", - expectedType: AddressType{}, + expectedType: AddressType, }, "struct": { value: NewStruct([]Value{String("bar")}), @@ -239,7 +239,7 @@ func newValueTestCases() map[string]valueTestCase { Fields: []Field{ { Identifier: "y", - Type: StringType{}, + Type: StringType, }, }, }, @@ -256,7 +256,7 @@ func newValueTestCases() map[string]valueTestCase { Fields: []Field{ { Identifier: "bar", - Type: IntType{}, + Type: IntType, }, }, }, @@ -278,11 +278,11 @@ func newValueTestCases() map[string]valueTestCase { Fields: []Field{ { Identifier: "a", - Type: IntType{}, + Type: IntType, }, { Identifier: "b", - Type: StringType{}, + Type: StringType, }, }, }, @@ -299,7 +299,7 @@ func newValueTestCases() map[string]valueTestCase { Fields: []Field{ { Identifier: "y", - Type: StringType{}, + Type: StringType, }, }, }, @@ -316,7 +316,7 @@ func newValueTestCases() map[string]valueTestCase { Fields: []Field{ { Identifier: sema.EnumRawValueFieldName, - Type: UInt8Type{}, + Type: UInt8Type, }, }, }, @@ -333,7 +333,7 @@ func newValueTestCases() map[string]valueTestCase { Fields: []Field{ { Identifier: "bar", - Type: IntType{}, + Type: IntType, }, }, }, @@ -347,7 +347,7 @@ func newValueTestCases() map[string]valueTestCase { Domain: common.PathDomainStorage, Identifier: "foo", }, - expectedType: TheStoragePathType, + expectedType: StoragePathType, string: "/storage/foo", }, "PrivatePath": { @@ -355,7 +355,7 @@ func newValueTestCases() map[string]valueTestCase { Domain: common.PathDomainPrivate, Identifier: "foo", }, - expectedType: ThePrivatePathType, + expectedType: PrivatePathType, string: "/private/foo", }, "PublicPath": { @@ -363,21 +363,21 @@ func newValueTestCases() map[string]valueTestCase { Domain: common.PathDomainPublic, Identifier: "foo", }, - expectedType: ThePublicPathType, + expectedType: PublicPathType, string: "/public/foo", }, "Type": { - value: TypeValue{StaticType: IntType{}}, - expectedType: NewMetaType(), + value: TypeValue{StaticType: IntType}, + expectedType: MetaType, string: "Type()", }, "Capability (ID)": { value: NewCapability( 3, BytesToAddress([]byte{1, 2, 3, 4, 5}), - IntType{}, + IntType, ), - expectedType: NewCapabilityType(IntType{}), + expectedType: NewCapabilityType(IntType), string: "Capability(address: 0x0000000102030405, id: 3)", }, "Function": { @@ -666,7 +666,7 @@ func TestOptional_Type(t *testing.T) { require.Equal(t, &OptionalType{ - Type: NeverType{}, + Type: NeverType, }, Optional{}.Type(), ) @@ -676,7 +676,7 @@ func TestOptional_Type(t *testing.T) { require.Equal(t, &OptionalType{ - Type: Int8Type{}, + Type: Int8Type, }, Optional{ Value: Int8(2), @@ -925,11 +925,11 @@ func TestEvent_GetFieldByName(t *testing.T) { Fields: []Field{ { Identifier: "a", - Type: IntType{}, + Type: IntType, }, { Identifier: "b", - Type: StringType{}, + Type: StringType, }, }, })