A Target the Document Names

A document reference normally names its target in the schema: a documentType, and a contractId when the type is in another contract. A reference whose contractId and documentType are written "$self.<property>" leaves both to the document: two of its own properties say which contract and which document type the value points into. $self is the document being written, as $old is the stored one in a rule. documentTypeRequirements then says what that document type must look like. Reach for it when a contract should accept a document of any contract that qualifies: a proposal described by a moderated text someone else hosts, a listing attached to a record of whichever registry issued it.

WhererefersTo on an identifier property, at the top level or inside an object. Not on the items of a typed array, not an operand of an expression, not ownerRefersTo or creatorRefersTo.
Value"contractId": "$self.<property>" and "documentType": "$self.<property>", both required, and optionally documentTypeRequirements, in a "type": "permanentDocument" or "type": "moderatedDocument" declaration, or one listing both, that carries nothing else.
Sinceprotocol version 15
On updateFixed, like the rest of refersTo (IncompatibleDocumentTypeSchemaError, 10246).
ErrorsWhen a document is written: ReferencedDocumentTypeNotFoundError (40121), ReferencedDocumentTypePrivateError (40150), ReferencedDocumentTypeIndexOnlyError (40146), ReferencedDocumentTypeRequirementNotMetError (40153), ReferencedDocumentTypeDeletableError (40122), ReferencedDocumentTypeNotModeratedError (40143), ReferencedDocumentTypeModeratedError (40144), ReferencedEntityNotFoundError (40120). At registration: InvalidContractStructure (10231), JsonSchemaError (10101).

Example

"note": {
  "type": "object",
  "properties": {
    "descriptionId": {
      "type": "identifier",
      "refersTo": {
        "type": "moderatedDocument",
        "contractId": "$self.descriptionContractId",
        "documentType": "$self.descriptionDocumentType",
        "documentTypeRequirements": {
          "properties": {
            "body":      { "name": "$any", "type": "string" },
            "bodyBytes": { "name": "$any", "type": "array", "byteArray": true }
          },
          "require": { "anyOf": ["body", "bodyBytes"] }
        }
      },
      "position": 0
    },
    "descriptionContractId": { "type": "identifier", "position": 1 },
    "descriptionDocumentType": { "type": "string", "minLength": 1, "maxLength": 64, "position": 2 }
  },
  "required": ["descriptionId", "descriptionContractId", "descriptionDocumentType"],
  "additionalProperties": false
}

A note is described by a document its author points at: descriptionContractId names a contract, descriptionDocumentType a document type of it, and descriptionId a document of that type. The type must be one whose documents only the contract's moderators remove, on the record, and it must hold text, as a string or as bytes. Nothing about that contract is in this schema.

The keys

KeyValueWhat it does
contractId"$self." followed by the name of a top-level identifier property of the document type, 1 to 64 letters, digits or underscoresThe property holding the id of the contract the referenced document type lives in, where a reference naming its target in the schema writes the id itself.
documentType"$self." followed by the name of a top-level string propertyThe property holding the name of the referenced document type, where a reference naming its target in the schema writes the name itself.
documentTypeRequirementsobject: properties (required), require, whenWhat the named document type must look like. Absent, the type is held to its kind alone.

The two come together: a declaration names its target in the schema or through the document, never half of each, so a $self. contractId beside a literal documentType is refused, as is one beside none. The declaring contract is named like any other: a document pointing into its own contract writes that contract's id. Nothing a schema could write literally starts with $self.: a contract id is base58 and a document type name holds no $.

documentTypeRequirements

properties holds 1 to 4 named slots. Each describes a top-level property the referenced document type must have, and is filled by one property of that type matching the description.

Slot keyValueMeaning
name"$any", a property name, or "$self.<a string property of the referring document>"Which property may fill the slot: any property matching the rest; the one called this; or the one the referring document names in that property of its own.
type"string", "identifier", "integer", "boolean", or "array" with "byteArray": trueWhat the property holds. A byte array slot is not filled by an identifier, nor an identifier slot by a byte array.
maxBytesinteger, 1 to 4294967295On a string or byte array slot: the property can never hold more bytes than this. A string's bound is its maxBytes or four times its maxLength, the smaller of the two when it declares both; a byte array's is its maxItems. A property declaring no bound meets none.
distinctFroma slot name, or a list of slot namesThis slot is filled by a different property than each of them. Saying it on one side is enough.
whena conditionWhat the referenced type must say of the property: one the condition does not hold for does not fill the slot. See A condition on the property.

A slot name is 1 to 64 letters, digits or underscores. A transient property fills nothing: it is never stored.

require says which slots must be filled:

  • absent, every slot;
  • a slot name, that slot;
  • { "anyOf": [...] } or { "allOf": [...] } over two or more terms, each a slot name or the other combinator over two or more slot names. Two levels say everything anyOf and allOf can say of a set of slots. Nothing is named twice: no term, no slot within a group, no group with its slots in another order.

Every slot is named by require when there is one: a slot it never names could not matter.

"documentTypeRequirements": {
  "properties": {
    "title":     { "name": "$any", "type": "string", "maxBytes": 512 },
    "body":      { "name": "$self.bodyProperty", "type": "string", "distinctFrom": "title" },
    "bodyBytes": { "name": "$any", "type": "array", "byteArray": true }
  },
  "require": { "allOf": ["title", { "anyOf": ["body", "bodyBytes"] }] }
}

A short text property, and either the string property the document names in its bodyProperty, other than the one taken as the title, or a byte array.

When the requirements are met. They are met when some choice of properties fills a set of slots require holds for, with slots that are distinctFrom each other filled by different properties. Consensus only asks whether such a choice exists. A client that needs to know which property is the title and which the body can settle it the same way every time, in two steps:

  1. Which slots. Not every slot need be filled: require may hold for several sets of slots (every slot is the only set when there is no require). Take the sets it holds for with the most slots first and, between sets of the same size, the one whose slot names, listed in order, come first. Use the first set that step 2 can fill.
  2. Which property for each. Take the set's slots in the order of their names and give each the first property, in the type's position order, that matches it and that no slot it must differ from has taken, backing up to the previous slot's next property when a slot is left with nothing.

Take the first example of this page, body or bodyBytes: a type holding a string and a byte array fills both slots. A type holding only a string cannot fill that set, so the next ones are tried: body alone, which the string fills (bodyBytes alone would come after it). Naming the property outright, or through the referring document, leaves nothing to settle.

Either kind

type may list both kinds:

"refersTo": {
  "type": ["permanentDocument", "moderatedDocument"],
  "contractId": "$self.descriptionContractId",
  "documentType": "$self.descriptionDocumentType"
}

The named type is then a permanent one or a moderated one, and the reference is checked as a reference of the kind the type is: into a moderated type it resolves to the document or to its removal record, as a moderatedDocument reference does, and into a permanent type the document is always there. A type whose documents their owner can delete is neither, and is refused as it is for a permanentDocument reference (40122). The list holds the two names, once each, in either order. Only a reference naming its target through the document lists them: one naming its type in the schema knows the type's kind.

A condition on the property (when)

A slot's name, type and maxBytes describe the property. when adds a condition on what the referenced type says about it, written like a propertyConstraints condition and read against the referenced type's schema instead of a document:

"documentTypeRequirements": {
  "properties": {
    "body": {
      "name": "$any",
      "type": "string",
      "when": {
        "ifThen": [
          { "equal": ["$kind", { "const": "moderatedDocument" }] },
          { "allOf": [
            { "not": { "contains": ["$moderatorAbilities.deleteKeepsFields", "$property"] } },
            { "not": { "contains": ["$moderatorAbilities.changeFields", "$property"] } }
          ] }
        ]
      }
    }
  }
}

When the type is a moderated one, the string filling body is one a moderator's removal takes away (the removal record does not keep it) and one the document's author writes (it is not the moderators' field). A permanent type is asked nothing. With "type": ["permanentDocument", "moderatedDocument"] this accepts a text that is never removed, or a text moderators can take down, and not a text that would stay public after they did.

OperandReads
"$kind"The kind of the referenced type, by the refersTo type it is referred to with: permanentDocument or moderatedDocument.
"$property"The name of the property tried for the slot.
"$moderatorAbilities.deleteKeepsFields"The referenced type's deleteKeepsFields: the property paths a removal record keeps. Empty when the type lists none.
"$moderatorAbilities.changeFields"The referenced type's changeFields: the properties only moderators write. Empty when the type lists none.
"$electedAbilities"The abilities the referenced type's contract gives its elected moderation team on the type, by name: deleteDocuments, ban, suspend, warn, changeDocumentFields. Empty when the contract elects no team, or leaves the type out of what the team moderates.
"$moderatorAbilities.deleteWithin", "$moderatorAbilities.deleteSettled"Settings of the referenced type a present or an absent tests: whether moderators delete a document only within a window after its last change, and whether the type says who of a seated team may delete one past it.
"$moderatorAbilities.deleteSettled.approversPredateDocument"A setting a present or an absent tests: whether that rule counts a member the team's leader added only for documents created after its addition (approversPredateDocument, as the rule reads once its default is applied: set unless one approval meets it). Absent on a type with no such rule.
{ "const": "<string>" }The string, 1 to 256 characters.
ConditionHolds when
{ "equal": [a, b] }, { "notEqual": [a, b] }$kind or $property is, or is not, the constant on the other side. Compared with $kind, the constant is permanentDocument or moderatedDocument.
{ "in": [a, [...]] }, { "notIn": [a, [...]] }$kind or $property is, or is not, one of two or more distinct strings.
{ "contains": [list, a] }One of the two property lists holds $property or a constant, as a whole entry; or $electedAbilities holds the ability a constant names.
{ "present": setting }, { "absent": setting }The type declares, or does not declare, $moderatorAbilities.deleteWithin or $moderatorAbilities.deleteSettled; or its settled rule sets, or does not set, approversPredateDocument.
{ "not": c }, { "anyOf": [...] }, { "allOf": [...] }As in propertyConstraints: anyOf and allOf take two or more conditions, none listed twice and none the same combinator; not holds no not and no notIn.
{ "ifThen": [c, then] }, { "ifThenElse": [c, then, else] }then holds whenever c does; with an else, it holds when c does not.

One when is made of at most 16 conditions (max_document_type_requirement_condition_nodes), combinators counted and each string an in or a notIn lists counted too, and no string in it is longer than 256 characters (max_document_type_requirement_condition_text_length), so what it adds to a stored contract is bounded. It reads the type, never a document: no property path, no arithmetic, and no value of the referenced document. distinctFrom, require and the search for an assignment work as before, over the properties each slot's when leaves it.

A condition on the type (when)

documentTypeRequirements takes a when of its own, beside properties: the same condition, judged once for the named type as a whole, whatever fills the slots. No property is in hand, so it reads no $property. A type it does not hold for does not meet the requirements (40153).

"documentTypeRequirements": {
  "when": { "allOf": [
    { "contains": ["$electedAbilities", { "const": "deleteDocuments" }] },
    { "anyOf": [
      { "absent": "$moderatorAbilities.deleteWithin" },
      { "allOf": [
        { "present": "$moderatorAbilities.deleteSettled" },
        { "absent": "$moderatorAbilities.deleteSettled.approversPredateDocument" }
      ] }
    ] }
  ] },
  "properties": { "body": { "name": "$any", "type": "string" } }
}

The contract of the named type gives its elected team the deletion of the type's documents, and a document stays deletable: the type sets no window, or says who of the team deletes one past it and counts every member for every document. Without the first, a type can be a moderated one that nobody may moderate once a team is seated; without the second, a document outlasts its window for good; without the third, a rule taking more approvals than the leader and the elected members give never deletes a document older than the members the leader added. A reference that relies on a document being removable asks for both, and usually for an elected contract too.

A slot's when reads the same facts beside $property. Each when is held to the limits above on its own.

How it works

Nothing about the target is known when the contract is registered, so registration checks the declaration alone. Everything about the target is checked when a document is written, in this order, the first failure refusing the write:

  1. The document names a contract and a document type. A document that holds the reference but leaves out the property its contractId or its documentType is read from points nowhere: ReferencedEntityNotFoundError (40120).
  2. The contract exists and has a document type of that name: ReferencedDocumentTypeNotFoundError (40121) otherwise. Another contract costs a billed fetch, once per write.
  3. The type is not private, ReferencedDocumentTypePrivateError (40150), and not indexOnly, ReferencedDocumentTypeIndexOnlyError (40146): the documents of such a type are index entries, and none can be found by its id.
  4. The type meets documentTypeRequirements, each slot filled by a property its when holds for: ReferencedDocumentTypeRequirementNotMetError (40153). Judging it reads nothing from state but is billed by the comparisons it may take, before it is judged, so a refused write pays for it too: 100 credits (requirement_credits_per_comparison) for each property a slot tries (every property of the type for "$any", one for a name) and for each node of the slot's when for that property. A type of 20 properties under one "$any" slot with the seven-node condition above is 160 comparisons, 16,000 credits.
  5. The type is of the declared kind, as a reference naming it in the schema is held to at registration: for permanentDocument its documents never disappear (40122 or 40144 otherwise), for moderatedDocument they disappear only through a moderator's recorded removal (40143). A declaration listing both kinds is a moderated reference into a moderated type and a permanent one into any other, so it refuses only a type whose documents can be deleted (40122).
  6. The document exists: ReferencedEntityNotFoundError (40120).

On a replace the reference is checked again, whole, when its value changed or when a property it reads its target from changed: the contract id, the document type name, or a property a slot takes its name from. A changed one points the same id somewhere else. Otherwise it is kept as a permanent or moderated reference is: a moderated target a moderator removed since resolves to its removal record, and an edit of the referring document's other properties passes.

What stays true. A document type's deletion and moderation settings never change, its moderatorAbilities among them, and neither do its existing properties' types, so a target that qualified keeps its kind and what a when read of it. The requirements are judged when the reference is checked, not afterwards.

Rules at registration

  • Both contractId and documentType are present and read from the document ("$self.<property>"), from two different properties, and type is permanentDocument, moderatedDocument or the list of both. A deletableDocument reference always names its type in the schema: a dynamic target is trusted for what its type promises about its documents staying, and a deletable type promises nothing.
  • The declaration carries nothing else: no findBy, where, inList, consume or constraints. Each needs the referenced type when the contract is registered. documentTypeRequirements comes only with a target read from the document: a type the schema names needs no description.
  • It sits on a single identifier property: not on the elements of a typed array, in a reference expression, or in ownerRefersTo and creatorRefersTo.
  • contractId reads a top-level identifier property, and documentType and every slot's "$self.<property>" name a top-level string property. None is transient or the reference property itself, and each is required wherever the reference property is, so a document that must hold the reference always says where it points. None is listed under moderatorAbilities.changeFields, like the reference property itself: a moderator's change checks no reference again, so it could point a stored one somewhere nobody checked.
  • documentTypeRequirements holds 1 to 4 slots (max_document_type_requirement_slots), each well formed; distinctFrom names other slots of the same properties; require names slots, and all of them.
  • A slot's when is a condition of at most 16 conditions, listed strings counted (max_document_type_requirement_condition_nodes), over the operands above, each comparison pairing what it may pair, with no string longer than 256 characters (max_document_type_requirement_condition_text_length).
  • No propertyConstraints rule reads a value through the reference, no index holds one, and no chained query joins through it: each resolves the referenced type from the schema.

Before protocol version 15 the keys are not part of refersTo: registration refuses them.

Who vouches for the target

The requirements say what the target's type looks like. They do not say who runs its contract. A moderatedDocument target is removed by the moderators of the contract the document names, and the author of the document chose that contract. Where that matters, hold the contract to something as well: give the contract id property its own reference,

"descriptionContractId": {
  "type": "identifier",
  "refersTo": { "type": "contract", "contractRequirements": { "moderation": "elected" } },
  "position": 1
}

or compare it with the contracts the application trusts in a propertyConstraints rule ({ "in": ["descriptionContractId", ["<base58>", "<base58>"]] }).

The decision proposals contract does the first for the description of a multiple choice proposal: a moderatedDocument whose text a removal takes away, in a contract whose moderators the masternodes elect (see docs/protocol/decision-proposals.md). "moderation": "elected" says the contract declares such a team, not that one is seated: until then the contract's interim moderators, if it names any, are the ones who can remove the document.

Errors

ErrorCodeWhen
ReferencedDocumentTypeRequirementNotMetError40153Write: the named document type does not meet the reference's documentTypeRequirements.
ReferencedDocumentTypeNotFoundError40121Write: the named contract does not exist, or has no document type of that name.
ReferencedDocumentTypePrivateError40150Write: the named document type is private.
ReferencedDocumentTypeIndexOnlyError40146Write: the named document type is indexOnly.
ReferencedDocumentTypeDeletableError, ReferencedDocumentTypeModeratedError, ReferencedDocumentTypeNotModeratedError40122, 40144, 40143Write: the named document type is not of the declared kind.
ReferencedEntityNotFoundError40120Write: the document does not say where the reference points, or no document with that id exists in the named type.

See also