@ixo/action-protocol 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.js CHANGED
@@ -445,14 +445,15 @@ export function parseReceipt(input) {
445
445
  tuple(receipt);
446
446
  if (!SUBMISSION_FAILURE_STEPS.includes(receipt.step)) fail("receipt.step");
447
447
  // Plain words the Hub chose (never raw text): shown to the person and
448
- // relayed by gateways and runtimes. Already in sanitized form.
449
- if (sanitizeSubmissionText(str(receipt.message, "receipt.message", 1, 500)) !== receipt.message)
448
+ // relayed by gateways and runtimes. Already in sanitized form (the 0.7.0
449
+ // rule, so receipts stored before 0.8.0 keep parsing; the Hub's 0.8.0
450
+ // sanitizer also drops tag characters, and its output passes this too).
451
+ if (!isLegacyClean(str(receipt.message, "receipt.message", 1, 500)))
450
452
  fail("receipt.message");
451
453
  // Optional technical text, for the review page's closed disclosure only.
452
454
  if (
453
455
  "detail" in receipt &&
454
- sanitizeSubmissionText(str(receipt.detail, "receipt.detail", 1, SUBMISSION_TEXT_MAX)) !==
455
- receipt.detail
456
+ !isLegacyClean(str(receipt.detail, "receipt.detail", 1, SUBMISSION_TEXT_MAX))
456
457
  )
457
458
  fail("receipt.detail");
458
459
  num(receipt.failedAt, "receipt.failedAt");
@@ -511,7 +512,7 @@ export function parseReviewView(input) {
511
512
  // 0.7.0: the collection's name as the Hub read it when the card was made.
512
513
  if (view.collectionName !== undefined && view.collectionName !== null) {
513
514
  if (!SUBMISSION_KINDS.includes(view.operation?.kind)) fail("view.collectionName");
514
- if (sanitizeSubmissionText(str(view.collectionName, "view.collectionName", 1, 120)) !== view.collectionName)
515
+ if (!isLegacyClean(str(view.collectionName, "view.collectionName", 1, 120)))
515
516
  fail("view.collectionName");
516
517
  }
517
518
  if (view.service !== undefined && view.service !== null) {
@@ -1022,9 +1023,16 @@ export const SUBMISSION_TEXT_MAX = 500;
1022
1023
  const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/gu;
1023
1024
  // Invisible and direction-changing characters are dropped: zero-width
1024
1025
  // characters, bidi embeddings, overrides and isolates, word joiners and
1025
- // invisible operators, variation selectors, the BOM, soft hyphen and the
1026
- // Hangul and Mongolian fillers.
1026
+ // invisible operators, variation selectors, the BOM, soft hyphen, the
1027
+ // Hangul and Mongolian fillers, and (0.8.0) the Unicode tag characters
1028
+ // (U+E0000-E007F, which can carry text no one sees) and the musical-symbol
1029
+ // format characters (U+1D173-1D17A).
1027
1030
  const INVISIBLE_CHARACTERS =
1031
+ /[\u00ad\u034f\u061c\u115f\u1160\u17b4\u17b5\u180b-\u180f\u200b-\u200f\u202a-\u202e\u2060-\u206f\u3164\ufe00-\ufe0f\ufeff\uffa0\u{1d173}-\u{1d17a}\u{e0000}-\u{e007f}]/gu;
1032
+ // The 0.7.0 set (without the tag characters and the musical-symbol format
1033
+ // characters 0.8.0 adds): a value the 0.7.0 sanitizer left unchanged still
1034
+ // parses, so receipts and views stored before 0.8.0 keep parsing.
1035
+ const LEGACY_INVISIBLE_CHARACTERS =
1028
1036
  /[\u00ad\u034f\u061c\u115f\u1160\u17b4\u17b5\u180b-\u180f\u200b-\u200f\u202a-\u202e\u2060-\u206f\u3164\ufe00-\ufe0f\ufeff\uffa0]/gu;
1029
1037
  // Anything a chat app or browser could turn into a link: a URL with a
1030
1038
  // scheme, a www. host, an email address, or a dotted host name ending in a
@@ -1034,6 +1042,12 @@ const INVISIBLE_CHARACTERS =
1034
1042
  // backtracking); the input is also cut to SANITIZE_INPUT_MAX first.
1035
1043
  const LINK_LIKE =
1036
1044
  /\b[a-z][a-z0-9+.-]{0,31}:\/\/\S{0,2048}|\bwww\.\S{0,2048}|\b[^\s@]{1,64}@[^\s@]{1,255}\.[^\s@]{1,63}|\b(?:[a-z0-9-]{1,63}\.){1,16}[a-z]{2,63}\b(?::\d{1,5})?(?:\/\S{0,2048})?/giu;
1045
+ // 0.8.0: what counts as a link in free text published on chain (SHOWN_AS_IS):
1046
+ // a URL with a scheme, a www. host, an email address, or a dotted host
1047
+ // followed by a path ("pay.example/now"). A plain file name ("Annual
1048
+ // Report.pdf") or a version ("v2.0.1") is not one. Bounded like LINK_LIKE.
1049
+ const PUBLISHED_LINK_LIKE =
1050
+ /\b[a-z][a-z0-9+.-]{0,31}:\/\/\S{0,2048}|\bwww\.\S{0,2048}|\b[^\s@]{1,64}@[^\s@]{1,255}\.[^\s@]{1,63}|\b(?:[a-z0-9-]{1,63}\.){1,16}[a-z]{2,63}(?::\d{1,5})?\/\S{0,2048}/giu;
1037
1051
  /** At most this much input is looked at (4 x SUBMISSION_TEXT_MAX). */
1038
1052
  const SANITIZE_INPUT_MAX = 2000;
1039
1053
  /**
@@ -1044,30 +1058,63 @@ const SANITIZE_INPUT_MAX = 2000;
1044
1058
  * comes out unchanged, so a parser can check a value is already safe.
1045
1059
  */
1046
1060
  export function sanitizeSubmissionText(text) {
1061
+ return sanitizeWith(text, LINK_LIKE, INVISIBLE_CHARACTERS);
1062
+ }
1063
+ /**
1064
+ * 0.8.0: free text published on chain as the review page shows it
1065
+ * (SHOWN_AS_IS): as sanitizeSubmissionText, but only real links become
1066
+ * `[link]` (a scheme, www., an email address, or a host followed by a path),
1067
+ * so a file name such as "Annual Report.pdf" stays as it is. Idempotent.
1068
+ */
1069
+ export function sanitizePublishedText(text) {
1070
+ return sanitizeWith(text, PUBLISHED_LINK_LIKE, INVISIBLE_CHARACTERS);
1071
+ }
1072
+ /** True when the 0.7.0 sanitizer leaves `text` unchanged (stored data still parses). */
1073
+ const isLegacyClean = (text) =>
1074
+ sanitizeWith(text, LINK_LIKE, LEGACY_INVISIBLE_CHARACTERS) === text;
1075
+ function sanitizeWith(text, linkLike, invisible) {
1047
1076
  // Bounded input before any expression runs; then unpaired surrogates (also
1048
1077
  // one the cut split) are dropped, so every pass sees well-formed text.
1049
- let out = sanitizeOnce(String(text).slice(0, SANITIZE_INPUT_MAX));
1078
+ let out = sanitizeOnce(
1079
+ String(text).slice(0, SANITIZE_INPUT_MAX),
1080
+ linkLike,
1081
+ invisible,
1082
+ );
1050
1083
  // A pass can only change the text again at its cut tail (a new link-like
1051
1084
  // tail, or a "[link]" pushed over the limit), so it settles within a few
1052
1085
  // passes; SANITIZE_PASSES is a hard bound. Should it ever not settle, the
1053
1086
  // empty string (itself stable) is returned: the result is ALWAYS a fixed
1054
1087
  // point, so sanitize(sanitize(x)) === sanitize(x) and a parser can check it.
1055
1088
  for (let pass = 0; pass < SANITIZE_PASSES; pass++) {
1056
- const next = sanitizeOnce(out);
1089
+ const next = sanitizeOnce(out, linkLike, invisible);
1057
1090
  if (next === out) return out;
1058
1091
  out = next;
1059
1092
  }
1060
1093
  return "";
1061
1094
  }
1062
1095
  const SANITIZE_PASSES = 8;
1096
+ /**
1097
+ * 0.8.0: a raw value (an id, an address, a type URL) without anything that
1098
+ * could make it render as something else, for a technical fact that must
1099
+ * show it exactly: control characters become spaces and invisible or
1100
+ * direction-changing characters are dropped (the sets
1101
+ * `sanitizeSubmissionText` uses), but nothing link-like is replaced and
1102
+ * nothing is cut.
1103
+ */
1104
+ export function stripHiddenCharacters(text) {
1105
+ return String(text)
1106
+ .replace(UNPAIRED_SURROGATES, "")
1107
+ .replace(CONTROL_CHARACTERS, " ")
1108
+ .replace(INVISIBLE_CHARACTERS, "");
1109
+ }
1063
1110
  // A high surrogate not followed by a low one, or a low one not after a high one.
1064
1111
  const UNPAIRED_SURROGATES = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
1065
- function sanitizeOnce(text) {
1112
+ function sanitizeOnce(text, linkLike, invisible) {
1066
1113
  const cleaned = text
1067
1114
  .replace(UNPAIRED_SURROGATES, "")
1068
1115
  .replace(CONTROL_CHARACTERS, " ")
1069
- .replace(INVISIBLE_CHARACTERS, "")
1070
- .replace(LINK_LIKE, "[link]")
1116
+ .replace(invisible, "")
1117
+ .replace(linkLike, "[link]")
1071
1118
  .replace(/\s+/gu, " ")
1072
1119
  .trim();
1073
1120
  if (cleaned.length <= SUBMISSION_TEXT_MAX) return cleaned;
@@ -1668,12 +1715,65 @@ export function parseTransferDisplay(input) {
1668
1715
 
1669
1716
  /** One card kind for every chain transaction (1..8 messages, all or nothing). */
1670
1717
  export const CHAIN_TX_KIND = "ixo.chain.tx.v1";
1671
- export const CHAIN_TX_MESSAGE_TYPES = [
1718
+ /** 0.6.0: the message types wire levels 4 and 5 may see (exactly these four). */
1719
+ export const CHAIN_TX_LEVEL4_MESSAGE_TYPES = Object.freeze([
1672
1720
  "cosmos.bank.send",
1673
1721
  "ixo.claims.submit",
1674
1722
  "ixo.claims.evaluate",
1675
1723
  "ixo.token.transfer",
1676
- ];
1724
+ ]);
1725
+ /**
1726
+ * Every message type this package parses: the level-4 types, then the 29
1727
+ * types of 0.8.0 (wire level 6). What a caller may see or create is
1728
+ * `chainTxMessageTypesForLevel(level)`, never this list.
1729
+ */
1730
+ export const CHAIN_TX_MESSAGE_TYPES = Object.freeze([
1731
+ ...CHAIN_TX_LEVEL4_MESSAGE_TYPES,
1732
+ "ixo.token.retire",
1733
+ "cosmos.staking.delegate",
1734
+ "cosmos.staking.undelegate",
1735
+ "cosmos.staking.redelegate",
1736
+ "cosmos.distribution.withdraw-rewards",
1737
+ "cosmos.gov.vote",
1738
+ "ixo.claims.claim-intent",
1739
+ "ixo.claims.dispute",
1740
+ "ixo.claims.update-collection-state",
1741
+ "ixo.claims.update-collection-dates",
1742
+ "ixo.claims.update-collection-quota",
1743
+ "ixo.claims.create-claim-authorization",
1744
+ "ixo.claims.update-collection-payments",
1745
+ "ixo.claims.create-collection",
1746
+ "ixo.entity.create-account",
1747
+ "ixo.entity.update",
1748
+ "ixo.entity.revoke-account-authz",
1749
+ "ixo.entity.grant-account-authz",
1750
+ "ixo.entity.create",
1751
+ "ixo.iid.add-service",
1752
+ "ixo.iid.delete-service",
1753
+ "ixo.iid.add-linked-resource",
1754
+ "ixo.iid.delete-linked-resource",
1755
+ "ixo.iid.add-linked-claim",
1756
+ "ixo.iid.delete-linked-claim",
1757
+ "ixo.iid.add-linked-entity",
1758
+ "ixo.iid.delete-linked-entity",
1759
+ "ixo.iid.add-context",
1760
+ "ixo.iid.delete-context",
1761
+ ]);
1762
+ /** The wire level that adds the 29 types of 0.8.0. */
1763
+ export const CHAIN_TX_LEVEL6 = 6;
1764
+ const NO_CHAIN_TX_TYPES = Object.freeze([]);
1765
+ /**
1766
+ * The chain tx message types a caller at wire `level` may see in
1767
+ * capabilities and create: none below 4 (no chain tx), the four 0.6.0 types
1768
+ * at 4 and 5, all 33 from 6. One rule for the Hub, runtimes and tests.
1769
+ */
1770
+ export function chainTxMessageTypesForLevel(level) {
1771
+ if (!Number.isSafeInteger(level) || level < 1) fail("level");
1772
+ if (level < 4) return NO_CHAIN_TX_TYPES;
1773
+ return level < CHAIN_TX_LEVEL6
1774
+ ? CHAIN_TX_LEVEL4_MESSAGE_TYPES
1775
+ : CHAIN_TX_MESSAGE_TYPES;
1776
+ }
1677
1777
  export const CHAIN_TX_MAX_MESSAGES = 8;
1678
1778
  export const CHAIN_TX_MAX_TOKEN_LINES = 32;
1679
1779
  /** `check_tx_rejected`/`expired_not_included`: never included; `tx_failed`: included with code != 0. */
@@ -1685,6 +1785,137 @@ export const CHAIN_TX_FAILURE_REASONS = [
1685
1785
  export const CHAIN_TX_RISK_LEVELS = ["low", "medium", "high", "critical"];
1686
1786
  /** EvaluationStatus values a chain tx may record (0 pending and 5 flagged are refused). */
1687
1787
  export const CHAIN_TX_EVALUATION_STATUSES = [1, 2, 3, 4];
1788
+ // 0.8.0 enums: names on the wire; the Hub maps them to the chain's numbers.
1789
+ /** `cosmos.gov.vote` `option`: YES 1, NO 3, ABSTAIN 2, NO_WITH_VETO 4. */
1790
+ export const CHAIN_TX_VOTE_OPTIONS = Object.freeze([
1791
+ "yes",
1792
+ "no",
1793
+ "abstain",
1794
+ "no_with_veto",
1795
+ ]);
1796
+ /** `ixo.claims.dispute` `reason` (Portal's four; `check_wrong` targets the checker). */
1797
+ export const CHAIN_TX_DISPUTE_REASONS = Object.freeze([
1798
+ "not_as_asked",
1799
+ "not_delivered",
1800
+ "check_wrong",
1801
+ "other",
1802
+ ]);
1803
+ /** Collection `state`: OPEN 0, PAUSED 1, CLOSED 2. */
1804
+ export const CHAIN_TX_COLLECTION_STATES = Object.freeze([
1805
+ "open",
1806
+ "paused",
1807
+ "closed",
1808
+ ]);
1809
+ /** `ixo.claims.create-collection` `reservations` (intents): ALLOW 0, DENY 1, REQUIRED 2. */
1810
+ export const CHAIN_TX_RESERVATION_MODES = Object.freeze([
1811
+ "allow",
1812
+ "deny",
1813
+ "required",
1814
+ ]);
1815
+ /** `ixo.claims.create-claim-authorization` `role`: SUBMIT 1, EVALUATE 2. */
1816
+ export const CHAIN_TX_CLAIM_ROLES = Object.freeze(["file-claims", "check-claims"]);
1817
+ /**
1818
+ * `ixo.entity.grant-account-authz` / `revoke-account-authz` `permission`: the
1819
+ * only grants an entity's `admin` account can give through a card.
1820
+ */
1821
+ export const CHAIN_TX_ENTITY_PERMISSIONS = Object.freeze([
1822
+ "change-collection-state",
1823
+ "change-collection-dates",
1824
+ "change-collection-quota",
1825
+ "change-collection-payments",
1826
+ "authorize-claim-agents",
1827
+ "file-claims",
1828
+ "check-claims",
1829
+ ]);
1830
+ /** Collection payment legs (`payments.<leg>`). */
1831
+ export const CHAIN_TX_PAYMENT_LEGS = Object.freeze([
1832
+ "submission",
1833
+ "evaluation",
1834
+ "approval",
1835
+ "rejection",
1836
+ ]);
1837
+ /** At most this many coins per payment leg (distinct denoms). */
1838
+ export const CHAIN_TX_MAX_PAYMENT_COINS = 4;
1839
+ /** `payAfterSeconds` / `reservationSeconds`: 0 .. 365 days. */
1840
+ export const CHAIN_TX_MAX_SECONDS = 31536000;
1841
+ /** `maxClaims` of a claim permission: 1 .. 1 000 000 000. */
1842
+ export const CHAIN_TX_MAX_CLAIM_PERMISSION = 1000000000;
1843
+ /**
1844
+ * 0.8.0: why the Hub would not make a chain tx card from what it read on
1845
+ * chain (or from what the node's simulation said about one message). The
1846
+ * `reason` of the 400 then ends with one of these codes after the field:
1847
+ * `invalid_message: messages[<i>].<field>: <code>`. A reason without a code
1848
+ * is a shape the parser refused (as in 0.6.0). Fixed codes, never chain
1849
+ * text: a caller maps them to its own words and treats an unknown code like
1850
+ * none (`parseChainTxRefusal`).
1851
+ */
1852
+ export const CHAIN_TX_REFUSAL_CODES = Object.freeze([
1853
+ // Staking and rewards.
1854
+ "validator_not_found",
1855
+ "no_stake",
1856
+ "stake_too_small",
1857
+ "same_validator",
1858
+ "invalid_amount",
1859
+ "nothing_to_collect",
1860
+ // Voting.
1861
+ "proposal_not_found",
1862
+ "proposal_not_open",
1863
+ "invalid_vote_option",
1864
+ // Impact tokens.
1865
+ "token_not_found",
1866
+ // Claims and collections.
1867
+ "collection_not_found",
1868
+ "reservations_off",
1869
+ "reservation_exists",
1870
+ "claim_not_found",
1871
+ "claim_in_other_collection",
1872
+ "wrong_admin",
1873
+ "already_in_state",
1874
+ "start_date_missing",
1875
+ "end_before_start",
1876
+ "quota_below_count",
1877
+ "token_payments_present",
1878
+ // Permissions (claims and entity grants).
1879
+ "ends_too_soon",
1880
+ "deadline_too_soon",
1881
+ "current_permission_ends_too_soon",
1882
+ "unlimited_permission_exists",
1883
+ "other_permission_exists",
1884
+ "too_many_constraints",
1885
+ "no_such_permission",
1886
+ "collection_of_other_entity",
1887
+ // Entities and identity documents.
1888
+ "entity_not_found",
1889
+ "account_name_taken",
1890
+ "document_not_found",
1891
+ "nothing_to_remove",
1892
+ "already_exists",
1893
+ "invalid_did",
1894
+ // The card as a whole.
1895
+ "not_available",
1896
+ "chain_data_too_large",
1897
+ ]);
1898
+ const CHAIN_TX_REFUSAL =
1899
+ /^invalid_message: messages\[(\d)\]\.([A-Za-z][A-Za-z0-9_.[\]]{0,99})(?:: ([a-z_]{1,64}))?$/;
1900
+ /**
1901
+ * 0.8.0: a chain tx refusal `reason` as `{index, field, code}`: the message
1902
+ * index, its field (a path such as `payments.approval`) and the refusal code
1903
+ * (null when the reason has none, or one this package does not know). Null
1904
+ * when the reason does not name a message field.
1905
+ */
1906
+ export function parseChainTxRefusal(reason) {
1907
+ if (typeof reason !== "string") return null;
1908
+ const match = CHAIN_TX_REFUSAL.exec(reason);
1909
+ if (!match) return null;
1910
+ const index = Number(match[1]);
1911
+ if (index >= CHAIN_TX_MAX_MESSAGES) return null;
1912
+ const code = match[3] ?? null;
1913
+ return {
1914
+ index,
1915
+ field: match[2],
1916
+ code: code !== null && CHAIN_TX_REFUSAL_CODES.includes(code) ? code : null,
1917
+ };
1918
+ }
1688
1919
  // The chain's DID rule (x/iid/types/iid.go didValidationRegexpStr): segments of
1689
1920
  // [A-Za-z0-9._-] or a `%` followed by two hex digits, joined by ':', the last
1690
1921
  // one non-empty. Anchored at both ends here (the chain's own regex anchors
@@ -1730,7 +1961,177 @@ const CHAIN_TX_MESSAGE_KEYS = {
1730
1961
  "verificationProof",
1731
1962
  ],
1732
1963
  "ixo.token.transfer": ["type", "recipient", "tokens"],
1964
+ // 0.8.0 (wire level 6). Signer-derived chain fields (owner, delegator,
1965
+ // voter, signer, ...) are never wire keys: the Hub fills them from `signer`.
1966
+ "ixo.token.retire": ["type", "tokens", "jurisdiction", "reason"],
1967
+ "cosmos.staking.delegate": ["type", "validatorAddress", "amountBaseUnits"],
1968
+ "cosmos.staking.undelegate": ["type", "validatorAddress", "amountBaseUnits"],
1969
+ "cosmos.staking.redelegate": [
1970
+ "type",
1971
+ "fromValidatorAddress",
1972
+ "toValidatorAddress",
1973
+ "amountBaseUnits",
1974
+ ],
1975
+ "cosmos.distribution.withdraw-rewards": ["type", "validatorAddress"],
1976
+ "cosmos.gov.vote": ["type", "proposalId", "option"],
1977
+ "ixo.claims.claim-intent": ["type", "collectionId", "agentDid"],
1978
+ "ixo.claims.dispute": [
1979
+ "type",
1980
+ "claimId",
1981
+ "collectionId",
1982
+ "agentDid",
1983
+ "reason",
1984
+ "evidence",
1985
+ ],
1986
+ "ixo.claims.update-collection-state": [
1987
+ "type",
1988
+ "collectionId",
1989
+ "adminAddress",
1990
+ "state",
1991
+ ],
1992
+ "ixo.claims.update-collection-dates": [
1993
+ "type",
1994
+ "collectionId",
1995
+ "adminAddress",
1996
+ "startDate",
1997
+ "endDate",
1998
+ ],
1999
+ "ixo.claims.update-collection-quota": [
2000
+ "type",
2001
+ "collectionId",
2002
+ "adminAddress",
2003
+ "maxClaims",
2004
+ ],
2005
+ "ixo.claims.create-claim-authorization": [
2006
+ "type",
2007
+ "collectionId",
2008
+ "adminAddress",
2009
+ "granteeAddress",
2010
+ "role",
2011
+ "maxClaims",
2012
+ "expiresAt",
2013
+ "reservationSeconds",
2014
+ "decideBefore",
2015
+ "creatorDid",
2016
+ ],
2017
+ "ixo.claims.update-collection-payments": [
2018
+ "type",
2019
+ "collectionId",
2020
+ "adminAddress",
2021
+ "payments",
2022
+ ],
2023
+ "ixo.claims.create-collection": [
2024
+ "type",
2025
+ "entityId",
2026
+ "protocolId",
2027
+ "startDate",
2028
+ "endDate",
2029
+ "maxClaims",
2030
+ "state",
2031
+ "reservations",
2032
+ "payments",
2033
+ ],
2034
+ "ixo.entity.create-account": ["type", "entityId", "name"],
2035
+ // D20: no `status` in 0.8.0 (its meaning is client-defined).
2036
+ "ixo.entity.update": [
2037
+ "type",
2038
+ "entityId",
2039
+ "startDate",
2040
+ "endDate",
2041
+ "controllerDid",
2042
+ ],
2043
+ "ixo.entity.revoke-account-authz": [
2044
+ "type",
2045
+ "entityId",
2046
+ "granteeAddress",
2047
+ "permission",
2048
+ ],
2049
+ "ixo.entity.grant-account-authz": [
2050
+ "type",
2051
+ "entityId",
2052
+ "granteeAddress",
2053
+ "permission",
2054
+ "collectionId",
2055
+ "maxClaims",
2056
+ "reservationSeconds",
2057
+ "decideBefore",
2058
+ "expiresAt",
2059
+ ],
2060
+ "ixo.entity.create": [
2061
+ "type",
2062
+ "entityType",
2063
+ "profile",
2064
+ "protocolId",
2065
+ "startDate",
2066
+ "endDate",
2067
+ "ownerDid",
2068
+ ],
2069
+ "ixo.iid.add-service": ["type", "did", "service"],
2070
+ "ixo.iid.delete-service": ["type", "did", "serviceId"],
2071
+ "ixo.iid.add-linked-resource": ["type", "did", "resource"],
2072
+ "ixo.iid.delete-linked-resource": ["type", "did", "resourceId"],
2073
+ "ixo.iid.add-linked-claim": ["type", "did", "claim"],
2074
+ "ixo.iid.delete-linked-claim": ["type", "did", "claimId"],
2075
+ "ixo.iid.add-linked-entity": ["type", "did", "entity"],
2076
+ "ixo.iid.delete-linked-entity": ["type", "did", "entityId"],
2077
+ "ixo.iid.add-context": ["type", "did", "context"],
2078
+ "ixo.iid.delete-context": ["type", "did", "key"],
1733
2079
  };
2080
+ // 0.8.0 wire patterns (the JSON schema in operation-schema.js mirrors them).
2081
+ // A validator operator address: `ixovaloper1` + 38 bech32 characters (20
2082
+ // data bytes); the Hub also checks the checksum.
2083
+ const VALOPER_ADDRESS = /^ixovaloper1[023456789acdefghjklmnpqrstuvwxyz]{38}$/;
2084
+ // x/entity ids: md5 hex of `<nftContract>/<sequence>`.
2085
+ const ENTITY_DID = /^did:ixo:entity:[0-9a-f]{32}$/;
2086
+ // RFC 3339 with `Z` or an offset, at most milliseconds (the schema `instant`).
2087
+ const INSTANT =
2088
+ /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/;
2089
+ // The latest instant a protobuf Timestamp may hold (9999-12-31T23:59:59.999Z).
2090
+ const INSTANT_MAX_MS = Date.UTC(9999, 11, 31, 23, 59, 59, 999);
2091
+ // `maxClaims` of a claim permission: 1..10^9 (checked numerically below).
2092
+ const CLAIM_PERMISSION_COUNT = /^[1-9][0-9]{0,9}$/;
2093
+ // MsgRetireToken `jurisdiction`: the proto's documented `CC[-SUB[ POSTAL]]`
2094
+ // form, or `Global` (Portal's default). D13.
2095
+ const JURISDICTION =
2096
+ /^(?:Global|[A-Z]{2}(?:-[A-Za-z0-9]{1,3}(?: [A-Za-z0-9]{1,64})?)?)$/;
2097
+ // Dispute evidence `type`, e.g. `eval-engine/v1`.
2098
+ const EVIDENCE_TYPE = /^[A-Za-z0-9][A-Za-z0-9.+/_-]{0,99}$/;
2099
+ // Links on chain. https: a host with no user info (`https://a@b` reads as
2100
+ // `a` but goes to `b`); ipfs: a CID. No whitespace or backslashes anywhere.
2101
+ const HTTPS_URL = /^https:\/\/[^\s/?#@\\]+(?:[/?#][^\s\\]*)?$/;
2102
+ const IPFS_URL = /^ipfs:\/\/[A-Za-z0-9]+(?:\/[^\s\\]*)?$/;
2103
+ const URL_MAX = 300;
2104
+ // MsgCreateEntity `entity_type`: `dao`, `project`, `oracle`, `protocol/claim`.
2105
+ const ENTITY_TYPE = /^[a-z][a-z0-9_-]{0,31}(?:\/[a-z][a-z0-9_-]{0,31})?$/;
2106
+ // Entity account names (`admin` is refused separately, in any case).
2107
+ const ACCOUNT_NAME = /^[A-Za-z0-9](?:[A-Za-z0-9 _-]{0,62}[A-Za-z0-9])?$/;
2108
+ // x/iid item ids for an add: Portal writes `{id}#…` literally (the chain
2109
+ // stores it as is); the name after `#` may hold `:` (Portal's `#app:<id>`).
2110
+ const ITEM_ID = /^(?:\{id\}|did:ixo:[A-Za-z0-9._:%-]{1,160})#[A-Za-z0-9._~:-]{1,64}$/;
2111
+ const ITEM_ID_MAX = 233;
2112
+ // D28: the id of an item to remove is whatever the document holds (Portal
2113
+ // stored `#api` with no prefix, `{id}#ixo1…`, ids without `#`), so any 1..300
2114
+ // characters without whitespace or CONTROL. The Hub's required document read
2115
+ // proves the exact id exists before a card is made.
2116
+ const REMOVE_ID_MAX = 300;
2117
+ // `+`: Portal's `application/vnd.ixo.design-pod+json` resource type.
2118
+ const IID_TYPE = /^[A-Za-z][A-Za-z0-9._:/+-]{0,63}$/;
2119
+ const MEDIA_TYPE = /^[a-z]+\/[A-Za-z0-9.+-]{1,90}$/;
2120
+ const MEDIA_TYPE_MAX = 128;
2121
+ // D28: mixed case (Portal writes `Governs`).
2122
+ const RELATIONSHIP = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
2123
+ const CONTEXT_KEY = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
2124
+ // A linked entity's `service`: a service name (`svc1`, `matrix`,
2125
+ // `did:cosmos:ixo` as stored on chain) or a DID URL reference to one
2126
+ // (`{id}#matrix`); `""` means none (Portal's default).
2127
+ const SERVICE_REF =
2128
+ /^(?:(?:(?:\{id\}|did:ixo:[A-Za-z0-9._:%-]{1,160})#)?[A-Za-z0-9._~:-]{1,64})?$/;
2129
+ // D28: a linked entity is an IXO DID, an ixo account (20 bytes) or contract
2130
+ // (32 bytes) address, or Portal's `{id}#<address>` (a group's core contract).
2131
+ // The Hub checks the address checksum.
2132
+ const LINKED_ENTITY_ADDRESS =
2133
+ /^(?:\{id\}#)?ixo1(?:[023456789acdefghjklmnpqrstuvwxyz]{38}|[023456789acdefghjklmnpqrstuvwxyz]{58})$/;
2134
+ const CLAIM_PERMISSIONS = ["file-claims", "check-claims"];
1734
2135
  const plain = (value) =>
1735
2136
  value !== null && typeof value === "object" && !Array.isArray(value);
1736
2137
  const isText = (value, min = 1, max = 200) =>
@@ -1741,9 +2142,404 @@ const isId = (value, max) => isMatch(value, CHAIN_ID_CHARS, max);
1741
2142
  const isCollectionId = (value) =>
1742
2143
  isMatch(value, COLLECTION_ID, 20) && BigInt(value) <= UINT64_MAX;
1743
2144
  const utf8Length = (value) => new TextEncoder().encode(value).length;
2145
+ /** UINT64_TEXT: a uint64 in decimal, no leading zeros. */
2146
+ const isUint64Text = isCollectionId;
2147
+ /** PLAIN_TEXT(max): 1..max characters, not blank, no CONTROL characters. */
2148
+ const isPlainText = (value, max) =>
2149
+ isText(value, 1, max) && !CONTROL.test(value) && /\S/.test(value);
2150
+ /**
2151
+ * 0.8.0 SHOWN_AS_IS: free text published on chain must already be exactly
2152
+ * what the review page shows, i.e. `sanitizePublishedText` leaves it
2153
+ * unchanged: no control, invisible or direction-changing characters (soft
2154
+ * hyphen, word joiners, variation selectors, tag characters, ...), no real
2155
+ * link (a scheme, www., an email address, a host followed by a path; a file
2156
+ * name such as "Annual Report.pdf" is fine), single spaces and no space at
2157
+ * either end.
2158
+ */
2159
+ const isShownAsIs = (value) =>
2160
+ typeof value === "string" && sanitizePublishedText(value) === value;
2161
+ /**
2162
+ * INSTANT: a real calendar instant whose UTC time a protobuf Timestamp can
2163
+ * hold the way the Hub encodes it (1970-01-01T00:00:00Z .. year 9999).
2164
+ * Returns its epoch milliseconds, or null.
2165
+ */
2166
+ function instantMs(value) {
2167
+ if (!isMatch(value, INSTANT, 40) || !validCalendarInstant(value)) return null;
2168
+ const ms = Date.parse(value);
2169
+ return Number.isFinite(ms) && ms >= 0 && ms <= INSTANT_MAX_MS ? ms : null;
2170
+ }
2171
+ const isInstant = (value) => instantMs(value) !== null;
2172
+ const isSeconds = (value) =>
2173
+ Number.isSafeInteger(value) && value >= 0 && value <= CHAIN_TX_MAX_SECONDS;
2174
+ const isClaimCount = (value) =>
2175
+ isMatch(value, CLAIM_PERMISSION_COUNT, 10) &&
2176
+ Number(value) <= CHAIN_TX_MAX_CLAIM_PERMISSION;
2177
+ /** An https:// (and, when allowed, ipfs://) link of at most 300 characters. */
2178
+ function isLink(value, { ipfs }) {
2179
+ if (!isText(value, 1, URL_MAX) || CONTROL.test(value)) return false;
2180
+ if (ipfs && IPFS_URL.test(value)) return true;
2181
+ if (!HTTPS_URL.test(value)) return false;
2182
+ try {
2183
+ const url = new URL(value);
2184
+ return (
2185
+ url.protocol === "https:" &&
2186
+ url.hostname !== "" &&
2187
+ url.username === "" &&
2188
+ url.password === ""
2189
+ );
2190
+ } catch {
2191
+ return false;
2192
+ }
2193
+ }
2194
+ /** The first key of `value` not in `keys`, as `${at}.${key}`, or null. */
2195
+ function unknownKey(value, keys, at) {
2196
+ for (const key of Object.keys(value))
2197
+ if (!keys.includes(key)) return `${at}.${key}`;
2198
+ return null;
2199
+ }
2200
+ /** Impact token lines (`ixo.token.transfer`, `ixo.token.retire`). */
2201
+ function tokenLinesField(tokens) {
2202
+ if (
2203
+ !Array.isArray(tokens) ||
2204
+ tokens.length < 1 ||
2205
+ tokens.length > CHAIN_TX_MAX_TOKEN_LINES
2206
+ )
2207
+ return "tokens";
2208
+ for (const [j, token] of tokens.entries()) {
2209
+ if (!plain(token)) return `tokens[${j}]`;
2210
+ for (const key of Object.keys(token))
2211
+ if (key !== "id" && key !== "amount") return `tokens[${j}].${key}`;
2212
+ if (!isId(token.id, 128)) return `tokens[${j}].id`;
2213
+ if (!isMatch(token.amount, BASE_UNITS, 78)) return `tokens[${j}].amount`;
2214
+ }
2215
+ return null;
2216
+ }
2217
+ /**
2218
+ * Collection payments (the 0.8.0 subset): each leg optional; a leg is
2219
+ * `{amount: [{denom, amountBaseUnits}] (0..4, distinct denoms),
2220
+ * payAfterSeconds?}`, and the approval leg may add `networkSplit`.
2221
+ */
2222
+ function paymentsField(payments) {
2223
+ if (!plain(payments)) return "payments";
2224
+ const extra = unknownKey(payments, CHAIN_TX_PAYMENT_LEGS, "payments");
2225
+ if (extra) return extra;
2226
+ for (const leg of CHAIN_TX_PAYMENT_LEGS) {
2227
+ const value = payments[leg];
2228
+ if (value === undefined) continue;
2229
+ const at = `payments.${leg}`;
2230
+ if (!plain(value)) return at;
2231
+ const keys =
2232
+ leg === "approval"
2233
+ ? ["amount", "payAfterSeconds", "networkSplit"]
2234
+ : ["amount", "payAfterSeconds"];
2235
+ const unknown = unknownKey(value, keys, at);
2236
+ if (unknown) return unknown;
2237
+ if (
2238
+ !Array.isArray(value.amount) ||
2239
+ value.amount.length > CHAIN_TX_MAX_PAYMENT_COINS
2240
+ )
2241
+ return `${at}.amount`;
2242
+ const denoms = new Set();
2243
+ for (const [j, coin] of value.amount.entries()) {
2244
+ const c = `${at}.amount[${j}]`;
2245
+ if (!plain(coin)) return c;
2246
+ const bad = unknownKey(coin, ["denom", "amountBaseUnits"], c);
2247
+ if (bad) return bad;
2248
+ if (!isMatch(coin.denom, DENOM, 128) || denoms.has(coin.denom))
2249
+ return `${c}.denom`;
2250
+ denoms.add(coin.denom);
2251
+ if (!isMatch(coin.amountBaseUnits, BASE_UNITS, 78))
2252
+ return `${c}.amountBaseUnits`;
2253
+ }
2254
+ if (value.payAfterSeconds !== undefined && !isSeconds(value.payAfterSeconds))
2255
+ return `${at}.payAfterSeconds`;
2256
+ if (
2257
+ value.networkSplit !== undefined &&
2258
+ typeof value.networkSplit !== "boolean"
2259
+ )
2260
+ return `${at}.networkSplit`;
2261
+ }
2262
+ return null;
2263
+ }
2264
+ /**
2265
+ * Start/end dates. `endNullable`: `null` = no end date. `required`: both keys
2266
+ * must be present (create-collection); otherwise each is optional, and when
2267
+ * `atLeastOne` neither present names `startDate`. A given end at or before a
2268
+ * given start names `endDate`.
2269
+ */
2270
+ function datesField(m, { endNullable, required = false, atLeastOne = false }) {
2271
+ if (required ? !isInstant(m.startDate) : m.startDate !== undefined && !isInstant(m.startDate))
2272
+ return "startDate";
2273
+ if (
2274
+ (required && m.endDate === undefined) ||
2275
+ (m.endDate !== undefined &&
2276
+ !(endNullable && m.endDate === null) &&
2277
+ !isInstant(m.endDate))
2278
+ )
2279
+ return "endDate";
2280
+ if (atLeastOne && m.startDate === undefined && m.endDate === undefined)
2281
+ return "startDate";
2282
+ if (
2283
+ typeof m.startDate === "string" &&
2284
+ typeof m.endDate === "string" &&
2285
+ instantMs(m.endDate) <= instantMs(m.startDate)
2286
+ )
2287
+ return "endDate";
2288
+ return null;
2289
+ }
2290
+ /** A nested object with exactly `keys` (fields checked by `rules`, in order). */
2291
+ function nestedField(value, at, keys, rules) {
2292
+ if (!plain(value)) return at;
2293
+ const unknown = unknownKey(value, keys, at);
2294
+ if (unknown) return unknown;
2295
+ for (const [key, ok] of rules) if (!ok(value[key])) return `${at}.${key}`;
2296
+ return null;
2297
+ }
2298
+ const optionalRule = (rule) => (value) => value === undefined || rule(value);
2299
+ const linkRule = (value) => isLink(value, { ipfs: true });
2300
+ const itemIdRule = (value) => isMatch(value, ITEM_ID, ITEM_ID_MAX);
2301
+ const removeIdRule = (value) =>
2302
+ isText(value, 1, REMOVE_ID_MAX) && !/\s/.test(value) && !CONTROL.test(value);
2303
+ const iidTypeRule = (value) => isMatch(value, IID_TYPE, 64);
2304
+ const proofRule = (value) => isId(value, 300);
2305
+ // D28: linked resources and claims as Portal stores them: the proof may be
2306
+ // "" (app links), the description "" or up to 300 (form titles), `right` "".
2307
+ const linkProofRule = (value) => value === "" || isId(value, 300);
2308
+ const descriptionRule = (value) =>
2309
+ isText(value, 0, 300) && !CONTROL.test(value) && isShownAsIs(value);
2310
+ const rightRule = optionalRule(
2311
+ (value) => value === "" || (isPlainText(value, 300) && isShownAsIs(value)),
2312
+ );
2313
+ const booleanRule = (value) => typeof value === "boolean";
2314
+ const ixoDidRule = (value) => isMatch(value, IXO_DID);
2315
+
2316
+ /** 0.8.0: the first bad field of each new message type (relative), or null. */
2317
+ const CHAIN_TX_LEVEL6_FIELDS = {
2318
+ "ixo.token.retire": (m) => {
2319
+ const tokens = tokenLinesField(m.tokens);
2320
+ if (tokens) return tokens;
2321
+ if (!isMatch(m.jurisdiction, JURISDICTION, 71)) return "jurisdiction";
2322
+ if (!isPlainText(m.reason, 200) || !isShownAsIs(m.reason)) return "reason";
2323
+ return null;
2324
+ },
2325
+ "cosmos.staking.delegate": (m) => stakeField(m),
2326
+ "cosmos.staking.undelegate": (m) => stakeField(m),
2327
+ "cosmos.staking.redelegate": (m) => {
2328
+ if (!isMatch(m.fromValidatorAddress, VALOPER_ADDRESS, 49))
2329
+ return "fromValidatorAddress";
2330
+ if (
2331
+ !isMatch(m.toValidatorAddress, VALOPER_ADDRESS, 49) ||
2332
+ m.toValidatorAddress === m.fromValidatorAddress
2333
+ )
2334
+ return "toValidatorAddress";
2335
+ if (!isMatch(m.amountBaseUnits, BASE_UNITS, 78)) return "amountBaseUnits";
2336
+ return null;
2337
+ },
2338
+ "cosmos.distribution.withdraw-rewards": (m) =>
2339
+ isMatch(m.validatorAddress, VALOPER_ADDRESS, 49) ? null : "validatorAddress",
2340
+ "cosmos.gov.vote": (m) => {
2341
+ if (!isUint64Text(m.proposalId) || m.proposalId === "0") return "proposalId";
2342
+ if (!CHAIN_TX_VOTE_OPTIONS.includes(m.option)) return "option";
2343
+ return null;
2344
+ },
2345
+ "ixo.claims.claim-intent": (m) => {
2346
+ if (!isCollectionId(m.collectionId)) return "collectionId";
2347
+ if (!isMatch(m.agentDid, IXO_DID)) return "agentDid";
2348
+ return null;
2349
+ },
2350
+ "ixo.claims.dispute": (m) => {
2351
+ if (!isId(m.claimId, 256)) return "claimId";
2352
+ if (!isCollectionId(m.collectionId)) return "collectionId";
2353
+ if (!isMatch(m.agentDid, IXO_DID)) return "agentDid";
2354
+ if (!CHAIN_TX_DISPUTE_REASONS.includes(m.reason)) return "reason";
2355
+ return nestedField(m.evidence, "evidence", ["uri", "type", "proof", "encrypted"], [
2356
+ ["uri", linkRule],
2357
+ ["type", (v) => isMatch(v, EVIDENCE_TYPE, 100)],
2358
+ ["proof", proofRule],
2359
+ ["encrypted", optionalRule(booleanRule)],
2360
+ ]);
2361
+ },
2362
+ "ixo.claims.update-collection-state": (m) =>
2363
+ collectionAdminField(m) ??
2364
+ (CHAIN_TX_COLLECTION_STATES.includes(m.state) ? null : "state"),
2365
+ "ixo.claims.update-collection-dates": (m) =>
2366
+ collectionAdminField(m) ??
2367
+ datesField(m, { endNullable: true, atLeastOne: true }),
2368
+ "ixo.claims.update-collection-quota": (m) =>
2369
+ collectionAdminField(m) ?? (isUint64Text(m.maxClaims) ? null : "maxClaims"),
2370
+ "ixo.claims.create-claim-authorization": (m) => {
2371
+ const admin = collectionAdminField(m);
2372
+ if (admin) return admin;
2373
+ if (!isMatch(m.granteeAddress, ACCOUNT_ADDRESS)) return "granteeAddress";
2374
+ if (!CHAIN_TX_CLAIM_ROLES.includes(m.role)) return "role";
2375
+ if (!isClaimCount(m.maxClaims)) return "maxClaims";
2376
+ if (m.expiresAt !== undefined && !isInstant(m.expiresAt)) return "expiresAt";
2377
+ return claimConstraintField(m, m.role) ?? (isMatch(m.creatorDid, IXO_DID) ? null : "creatorDid");
2378
+ },
2379
+ "ixo.claims.update-collection-payments": (m) =>
2380
+ collectionAdminField(m) ?? paymentsField(m.payments),
2381
+ "ixo.claims.create-collection": (m) => {
2382
+ if (!isMatch(m.entityId, ENTITY_DID, 47)) return "entityId";
2383
+ if (!isMatch(m.protocolId, IXO_DID)) return "protocolId";
2384
+ const dates = datesField(m, { endNullable: true, required: true });
2385
+ if (dates) return dates;
2386
+ if (!isUint64Text(m.maxClaims)) return "maxClaims";
2387
+ if (!CHAIN_TX_COLLECTION_STATES.includes(m.state)) return "state";
2388
+ if (!CHAIN_TX_RESERVATION_MODES.includes(m.reservations)) return "reservations";
2389
+ return paymentsField(m.payments);
2390
+ },
2391
+ "ixo.entity.create-account": (m) => {
2392
+ if (!isMatch(m.entityId, ENTITY_DID, 47)) return "entityId";
2393
+ if (!isMatch(m.name, ACCOUNT_NAME, 64) || m.name.toLowerCase() === "admin")
2394
+ return "name";
2395
+ return null;
2396
+ },
2397
+ "ixo.entity.update": (m) => {
2398
+ if (!isMatch(m.entityId, ENTITY_DID, 47)) return "entityId";
2399
+ const dates = datesField(m, { endNullable: true, atLeastOne: true });
2400
+ if (dates) return dates;
2401
+ return isMatch(m.controllerDid, IXO_DID) ? null : "controllerDid";
2402
+ },
2403
+ "ixo.entity.revoke-account-authz": (m) => {
2404
+ if (!isMatch(m.entityId, ENTITY_DID, 47)) return "entityId";
2405
+ if (!isMatch(m.granteeAddress, ACCOUNT_ADDRESS)) return "granteeAddress";
2406
+ if (!CHAIN_TX_ENTITY_PERMISSIONS.includes(m.permission)) return "permission";
2407
+ return null;
2408
+ },
2409
+ "ixo.entity.grant-account-authz": (m) => {
2410
+ if (!isMatch(m.entityId, ENTITY_DID, 47)) return "entityId";
2411
+ if (!isMatch(m.granteeAddress, ACCOUNT_ADDRESS)) return "granteeAddress";
2412
+ if (!CHAIN_TX_ENTITY_PERMISSIONS.includes(m.permission)) return "permission";
2413
+ // collectionId and maxClaims: required for the claim permissions, refused otherwise.
2414
+ const claims = CLAIM_PERMISSIONS.includes(m.permission);
2415
+ if (claims ? !isCollectionId(m.collectionId) : m.collectionId !== undefined)
2416
+ return "collectionId";
2417
+ if (claims ? !isClaimCount(m.maxClaims) : m.maxClaims !== undefined)
2418
+ return "maxClaims";
2419
+ const constraint = claimConstraintField(m, m.permission);
2420
+ if (constraint) return constraint;
2421
+ if (m.expiresAt !== undefined && !isInstant(m.expiresAt)) return "expiresAt";
2422
+ return null;
2423
+ },
2424
+ "ixo.entity.create": (m) => {
2425
+ if (!isMatch(m.entityType, ENTITY_TYPE, 65)) return "entityType";
2426
+ if (m.profile !== undefined) {
2427
+ const profile = nestedField(m.profile, "profile", ["serviceEndpoint", "proof"], [
2428
+ ["serviceEndpoint", (v) => isLink(v, { ipfs: false })],
2429
+ ["proof", proofRule],
2430
+ ]);
2431
+ if (profile) return profile;
2432
+ }
2433
+ if (m.protocolId !== undefined && !isMatch(m.protocolId, IXO_DID))
2434
+ return "protocolId";
2435
+ const dates = datesField(m, { endNullable: false });
2436
+ if (dates) return dates;
2437
+ return isMatch(m.ownerDid, IXO_DID) ? null : "ownerDid";
2438
+ },
2439
+ "ixo.iid.add-service": (m) =>
2440
+ iidDidField(m) ??
2441
+ nestedField(m.service, "service", ["id", "type", "serviceEndpoint"], [
2442
+ ["id", itemIdRule],
2443
+ ["type", iidTypeRule],
2444
+ ["serviceEndpoint", linkRule],
2445
+ ]),
2446
+ "ixo.iid.delete-service": (m) =>
2447
+ iidDidField(m) ?? (removeIdRule(m.serviceId) ? null : "serviceId"),
2448
+ "ixo.iid.add-linked-resource": (m) =>
2449
+ iidDidField(m) ??
2450
+ nestedField(
2451
+ m.resource,
2452
+ "resource",
2453
+ ["id", "type", "description", "mediaType", "serviceEndpoint", "proof", "encrypted", "right"],
2454
+ [
2455
+ ["id", itemIdRule],
2456
+ ["type", iidTypeRule],
2457
+ ["description", descriptionRule],
2458
+ ["mediaType", (v) => isMatch(v, MEDIA_TYPE, MEDIA_TYPE_MAX)],
2459
+ ["serviceEndpoint", linkRule],
2460
+ ["proof", linkProofRule],
2461
+ ["encrypted", booleanRule],
2462
+ ["right", rightRule],
2463
+ ],
2464
+ ),
2465
+ "ixo.iid.delete-linked-resource": (m) =>
2466
+ iidDidField(m) ?? (removeIdRule(m.resourceId) ? null : "resourceId"),
2467
+ "ixo.iid.add-linked-claim": (m) =>
2468
+ iidDidField(m) ??
2469
+ nestedField(
2470
+ m.claim,
2471
+ "claim",
2472
+ ["id", "type", "description", "serviceEndpoint", "proof", "encrypted", "right"],
2473
+ [
2474
+ ["id", (v) => isId(v, 256)],
2475
+ ["type", iidTypeRule],
2476
+ ["description", descriptionRule],
2477
+ ["serviceEndpoint", linkRule],
2478
+ ["proof", linkProofRule],
2479
+ ["encrypted", booleanRule],
2480
+ ["right", rightRule],
2481
+ ],
2482
+ ),
2483
+ "ixo.iid.delete-linked-claim": (m) =>
2484
+ iidDidField(m) ?? (removeIdRule(m.claimId) ? null : "claimId"),
2485
+ "ixo.iid.add-linked-entity": (m) =>
2486
+ iidDidField(m) ??
2487
+ nestedField(m.entity, "entity", ["id", "type", "relationship", "service"], [
2488
+ ["id", (v) => ixoDidRule(v) || isMatch(v, LINKED_ENTITY_ADDRESS, 67)],
2489
+ ["type", iidTypeRule],
2490
+ ["relationship", (v) => isMatch(v, RELATIONSHIP, 64)],
2491
+ [
2492
+ "service",
2493
+ optionalRule((v) => typeof v === "string" && v.length <= ITEM_ID_MAX && SERVICE_REF.test(v)),
2494
+ ],
2495
+ ]),
2496
+ "ixo.iid.delete-linked-entity": (m) =>
2497
+ iidDidField(m) ?? (removeIdRule(m.entityId) ? null : "entityId"),
2498
+ "ixo.iid.add-context": (m) =>
2499
+ iidDidField(m) ??
2500
+ nestedField(m.context, "context", ["key", "val"], [
2501
+ ["key", (v) => isMatch(v, CONTEXT_KEY, 64)],
2502
+ ["val", (v) => isLink(v, { ipfs: false }) || isMatch(v, IXO_DID, URL_MAX)],
2503
+ ]),
2504
+ "ixo.iid.delete-context": (m) =>
2505
+ iidDidField(m) ?? (removeIdRule(m.key) ? null : "key"),
2506
+ };
2507
+ function stakeField(m) {
2508
+ if (!isMatch(m.validatorAddress, VALOPER_ADDRESS, 49)) return "validatorAddress";
2509
+ if (!isMatch(m.amountBaseUnits, BASE_UNITS, 78)) return "amountBaseUnits";
2510
+ return null;
2511
+ }
2512
+ /** The collection-admin types: `collectionId`, then `adminAddress` (D3). */
2513
+ function collectionAdminField(m) {
2514
+ if (!isCollectionId(m.collectionId)) return "collectionId";
2515
+ if (!isMatch(m.adminAddress, ACCOUNT_ADDRESS)) return "adminAddress";
2516
+ return null;
2517
+ }
2518
+ /**
2519
+ * Claim-permission constraint options: `reservationSeconds` only for
2520
+ * `file-claims` (intent duration), `decideBefore` only for `check-claims`.
2521
+ */
2522
+ function claimConstraintField(m, role) {
2523
+ if (
2524
+ m.reservationSeconds !== undefined &&
2525
+ (role !== "file-claims" || !isSeconds(m.reservationSeconds))
2526
+ )
2527
+ return "reservationSeconds";
2528
+ if (
2529
+ m.decideBefore !== undefined &&
2530
+ (role !== "check-claims" || !isInstant(m.decideBefore))
2531
+ )
2532
+ return "decideBefore";
2533
+ return null;
2534
+ }
2535
+ function iidDidField(m) {
2536
+ return isMatch(m.did, IXO_DID) ? null : "did";
2537
+ }
1744
2538
 
1745
2539
  /** The first bad field of one message (relative to the message), or null. */
1746
2540
  function chainTxMessageField(m) {
2541
+ if (Object.hasOwn(CHAIN_TX_LEVEL6_FIELDS, m.type))
2542
+ return CHAIN_TX_LEVEL6_FIELDS[m.type](m);
1747
2543
  if (m.type === "cosmos.bank.send") {
1748
2544
  if (!isMatch(m.toAddress, ACCOUNT_ADDRESS)) return "toAddress";
1749
2545
  if (!isMatch(m.amountBaseUnits, BASE_UNITS, 78)) return "amountBaseUnits";
@@ -1779,20 +2575,7 @@ function chainTxMessageField(m) {
1779
2575
  }
1780
2576
  // ixo.token.transfer
1781
2577
  if (!isMatch(m.recipient, ACCOUNT_ADDRESS)) return "recipient";
1782
- if (
1783
- !Array.isArray(m.tokens) ||
1784
- m.tokens.length < 1 ||
1785
- m.tokens.length > CHAIN_TX_MAX_TOKEN_LINES
1786
- )
1787
- return "tokens";
1788
- for (const [j, token] of m.tokens.entries()) {
1789
- if (!plain(token)) return `tokens[${j}]`;
1790
- for (const key of Object.keys(token))
1791
- if (key !== "id" && key !== "amount") return `tokens[${j}].${key}`;
1792
- if (!isId(token.id, 128)) return `tokens[${j}].id`;
1793
- if (!isMatch(token.amount, BASE_UNITS, 78)) return `tokens[${j}].amount`;
1794
- }
1795
- return null;
2578
+ return tokenLinesField(m.tokens);
1796
2579
  }
1797
2580
 
1798
2581
  /** The first bad field of a chain tx operation (`messages[1].toAddress`), or null. */
@@ -1850,7 +2633,11 @@ export function chainTxIssue(input) {
1850
2633
  return null;
1851
2634
  }
1852
2635
 
1853
- /** `GET /capabilities?version=4` `chainTx`. */
2636
+ /**
2637
+ * `GET /capabilities?version=4` `chainTx`. Accepts every type this package
2638
+ * knows; whether a type is allowed at the caller's level is the Hub's
2639
+ * `chainTxMessageTypesForLevel` rule.
2640
+ */
1854
2641
  export function parseChainTxCapabilities(input) {
1855
2642
  const c = object(input, "capabilities.chainTx");
1856
2643
  exact(c, ["messageTypes", "maxMessages"], "capabilities.chainTx");