@ixo/action-protocol 0.6.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
@@ -9,6 +9,8 @@ const HEX = /^[a-f0-9]{64}$/;
9
9
  const ADDRESS = /^ixo1[023456789acdefghjklmnpqrstuvwxyz]{38,59}$/;
10
10
  const INT = /^(0|[1-9][0-9]*)$/;
11
11
  const FIELD = /^[a-z][a-z0-9_]{0,39}$/;
12
+ /** 0.7.0 application and claim cards: an existing collection (never 0). */
13
+ const SUBMISSION_COLLECTION_ID = /^[1-9][0-9]{0,19}$/;
12
14
  /** Envelope tags. v1 carries only the 0.1 status/receipt set; v2 adds terminal non-execution outcomes. */
13
15
  export const OUTCOME_VERSION_V1 = "ixo.auth-outcome/1";
14
16
  export const OUTCOME_VERSION_V2 = "ixo.auth-outcome/2";
@@ -230,6 +232,24 @@ export function parseOperation(input) {
230
232
  if (new TextEncoder().encode(op.memo).length > MEMO_BYTES) fail("memo");
231
233
  return op.denom === undefined ? { ...op, denom: "uixo" } : op;
232
234
  }
235
+ if (op.kind === "ixo.bid.submit.v1" || op.kind === "ixo.claim.submit.v1") {
236
+ // Shape is checked by the schema; here the parts a schema cannot say.
237
+ jsonObject(op.data, "data");
238
+ // The card shows exactly what is sent and signed.
239
+ const issue = submissionSummaryIssue(op);
240
+ if (issue) fail(issue);
241
+ if (op.kind === "ixo.claim.submit.v1") {
242
+ const files = new Set();
243
+ for (const item of op.evidence) {
244
+ const url = new URL(item.url);
245
+ if (url.protocol !== "https:" || url.username || url.password || url.hash)
246
+ fail("evidence.url");
247
+ if (files.has(item.url)) fail("duplicate evidence");
248
+ files.add(item.url);
249
+ }
250
+ }
251
+ return op;
252
+ }
233
253
  if (op.kind === "resource.read.v1") {
234
254
  exact(
235
255
  op,
@@ -379,6 +399,66 @@ export function parseReceipt(input) {
379
399
  }
380
400
  return receipt;
381
401
  }
402
+ if (receipt.kind === "ixo.bid.submission.v1") {
403
+ exact(
404
+ receipt,
405
+ ["kind", "actionId", "revision", "digest", "collectionId", "bidId", "submittedAt"],
406
+ "receipt",
407
+ );
408
+ tuple(receipt);
409
+ pattern(receipt.collectionId, SUBMISSION_COLLECTION_ID, "receipt.collectionId");
410
+ if (receipt.bidId !== null) str(receipt.bidId, "receipt.bidId", 1, 200);
411
+ num(receipt.submittedAt, "receipt.submittedAt");
412
+ return receipt;
413
+ }
414
+ if (receipt.kind === "ixo.claim.submission.v1") {
415
+ exact(
416
+ receipt,
417
+ [
418
+ "kind",
419
+ "actionId",
420
+ "revision",
421
+ "digest",
422
+ "collectionId",
423
+ "claimId",
424
+ "transactionHash",
425
+ "height",
426
+ "submittedAt",
427
+ ],
428
+ "receipt",
429
+ );
430
+ tuple(receipt);
431
+ pattern(receipt.collectionId, SUBMISSION_COLLECTION_ID, "receipt.collectionId");
432
+ str(receipt.claimId, "receipt.claimId", 1, 200);
433
+ pattern(receipt.transactionHash, HEX, "receipt.transactionHash");
434
+ // The block the claim's MsgExec(MsgSubmitClaim) was included in.
435
+ num(receipt.height, "receipt.height");
436
+ num(receipt.submittedAt, "receipt.submittedAt");
437
+ return receipt;
438
+ }
439
+ if (receipt.kind === "ixo.submission.failed.v1") {
440
+ exact(
441
+ receipt,
442
+ ["kind", "actionId", "revision", "digest", "step", "message", "detail", "failedAt"],
443
+ "receipt",
444
+ );
445
+ tuple(receipt);
446
+ if (!SUBMISSION_FAILURE_STEPS.includes(receipt.step)) fail("receipt.step");
447
+ // Plain words the Hub chose (never raw text): shown to the person and
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)))
452
+ fail("receipt.message");
453
+ // Optional technical text, for the review page's closed disclosure only.
454
+ if (
455
+ "detail" in receipt &&
456
+ !isLegacyClean(str(receipt.detail, "receipt.detail", 1, SUBMISSION_TEXT_MAX))
457
+ )
458
+ fail("receipt.detail");
459
+ num(receipt.failedAt, "receipt.failedAt");
460
+ return receipt;
461
+ }
382
462
  return fail("receipt.kind");
383
463
  }
384
464
 
@@ -404,6 +484,8 @@ export function parseReviewView(input) {
404
484
  "service",
405
485
  "transfer",
406
486
  "chainTx",
487
+ "networkFee",
488
+ "collectionName",
407
489
  ],
408
490
  "view",
409
491
  );
@@ -422,6 +504,17 @@ export function parseReviewView(input) {
422
504
  )
423
505
  fail("view.chainTx");
424
506
  }
507
+ // 0.7.0: who pays a claim's network fee, read once when the card was made.
508
+ if (view.networkFee !== undefined && view.networkFee !== null) {
509
+ if (view.operation?.kind !== "ixo.claim.submit.v1") fail("view.networkFee");
510
+ if (!SUBMISSION_NETWORK_FEES.includes(view.networkFee)) fail("view.networkFee");
511
+ }
512
+ // 0.7.0: the collection's name as the Hub read it when the card was made.
513
+ if (view.collectionName !== undefined && view.collectionName !== null) {
514
+ if (!SUBMISSION_KINDS.includes(view.operation?.kind)) fail("view.collectionName");
515
+ if (!isLegacyClean(str(view.collectionName, "view.collectionName", 1, 120)))
516
+ fail("view.collectionName");
517
+ }
425
518
  if (view.service !== undefined && view.service !== null) {
426
519
  object(view.service, "view.service");
427
520
  exact(
@@ -738,6 +831,97 @@ export function parseCapabilities(input) {
738
831
  return data;
739
832
  }
740
833
 
834
+ /** 0.7.0: see index.d.ts. */
835
+ export function submissionDisplayValue(value) {
836
+ if (typeof value === "string") return value;
837
+ if (typeof value === "boolean") return String(value);
838
+ if (typeof value === "number") return Number.isFinite(value) ? String(value) : undefined;
839
+ if (value === null) return "";
840
+ if (
841
+ Array.isArray(value) &&
842
+ value.every((item) => ["string", "number", "boolean"].includes(typeof item))
843
+ ) {
844
+ const shown = value.map(submissionDisplayValue);
845
+ return shown.includes(undefined) ? undefined : shown.join(", ");
846
+ }
847
+ return undefined;
848
+ }
849
+ const plainObject = (value) =>
850
+ value !== null && typeof value === "object" && !Array.isArray(value);
851
+ /** The answers of `data`: path -> display form, or an issue string. */
852
+ function submissionAnswers(data) {
853
+ const answers = new Map();
854
+ const walk = (node, prefix) => {
855
+ for (const key of Object.keys(node)) {
856
+ if (key === "" || key.includes(".")) return `invalid_operation: data key ${JSON.stringify(key).slice(0, 60)}`;
857
+ const path = prefix ? `${prefix}.${key}` : key;
858
+ const value = node[key];
859
+ let issue = null;
860
+ if (plainObject(value)) issue = walk(value, path);
861
+ else if (Array.isArray(value) && value.length && value.every(plainObject)) {
862
+ for (const [index, item] of value.entries()) {
863
+ issue = walk(item, `${path}.${index}`);
864
+ if (issue) break;
865
+ }
866
+ } else {
867
+ const shown = submissionDisplayValue(value);
868
+ if (shown === undefined) return `invalid_operation: data.${path} has no display form`;
869
+ answers.set(path, shown);
870
+ }
871
+ if (issue) return issue;
872
+ }
873
+ return null;
874
+ };
875
+ const issue = walk(data, "");
876
+ return issue ?? answers;
877
+ }
878
+ /** The value at a dot path of `data` (objects by key, arrays by index), or undefined. */
879
+ function valueAt(data, path) {
880
+ let node = data;
881
+ for (const part of path.split(".")) {
882
+ if (Array.isArray(node) && /^\d+$/.test(part)) node = node[Number(part)];
883
+ else if (plainObject(node) && Object.prototype.hasOwnProperty.call(node, part)) node = node[part];
884
+ else return undefined;
885
+ }
886
+ return node;
887
+ }
888
+ /** 0.7.0: see index.d.ts. */
889
+ export function submissionSummaryIssue(op) {
890
+ let data;
891
+ try {
892
+ data = JSON.parse(op.data);
893
+ } catch {
894
+ return "invalid_operation: data";
895
+ }
896
+ if (!plainObject(data)) return "invalid_operation: data";
897
+ const answers = submissionAnswers(data);
898
+ if (typeof answers === "string") return answers;
899
+ const seen = new Set();
900
+ for (const [index, row] of (op.summary ?? []).entries()) {
901
+ if (seen.has(row.field)) return `invalid_operation: summary[${index}].field repeats`;
902
+ seen.add(row.field);
903
+ if (!answers.has(row.field)) return `invalid_operation: summary[${index}].field is not an answer`;
904
+ if (answers.get(row.field) !== row.value) return `invalid_operation: summary[${index}].value is not the answer`;
905
+ }
906
+ for (const path of answers.keys())
907
+ if (!seen.has(path)) return `invalid_operation: data.${path} has no summary row`;
908
+ if (op.kind === "ixo.claim.submit.v1")
909
+ for (const [index, item] of op.evidence.entries())
910
+ if (valueAt(data, item.field) !== undefined)
911
+ return `invalid_operation: evidence[${index}].field already holds an answer`;
912
+ return null;
913
+ }
914
+ /** 0.7.0: a string that must hold one JSON object (SurveyJS answers). */
915
+ const jsonObject = (value, field) => {
916
+ let parsed;
917
+ try {
918
+ parsed = JSON.parse(value);
919
+ } catch {
920
+ fail(field);
921
+ }
922
+ object(parsed, field);
923
+ return parsed;
924
+ };
741
925
  const utf8 = (value, field) => {
742
926
  str(value, field, 0, 8192);
743
927
  if (
@@ -813,7 +997,134 @@ const receiptKinds = {
813
997
  "vfs.access.request.v1": "vfs.access.requested.v1",
814
998
  "vfs.text.save.v1": "vfs.text.saved.v1",
815
999
  "ixo.chain.tx.v1": "ixo.chain.tx.v1",
1000
+ "ixo.bid.submit.v1": "ixo.bid.submission.v1",
1001
+ "ixo.claim.submit.v1": "ixo.claim.submission.v1",
816
1002
  };
1003
+ /** 0.7.0: kinds whose failed outcome carries `ixo.submission.failed.v1`. */
1004
+ const SUBMISSION_KINDS = ["ixo.bid.submit.v1", "ixo.claim.submit.v1"];
1005
+ /** 0.7.0: the step a bid or claim submission stopped at. */
1006
+ export const SUBMISSION_FAILURE_STEPS = [
1007
+ "collection",
1008
+ "evidence",
1009
+ "key",
1010
+ "bid_bot",
1011
+ "claim_bot",
1012
+ "chain",
1013
+ ];
1014
+ /**
1015
+ * 0.7.0: a claim card's network fee as read when the card was made: a
1016
+ * usable fee grant allowing MsgExec covers it, or the person's IXO balance
1017
+ * pays it (also when the grants could not be read).
1018
+ */
1019
+ export const SUBMISSION_NETWORK_FEES = ["covered", "balance"];
1020
+ /** 0.7.0: the longest failure `message` or `detail`, in UTF-16 units. */
1021
+ export const SUBMISSION_TEXT_MAX = 500;
1022
+ // Control characters (C0, DEL, C1, line/paragraph separators) become spaces.
1023
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/gu;
1024
+ // Invisible and direction-changing characters are dropped: zero-width
1025
+ // characters, bidi embeddings, overrides and isolates, word joiners and
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).
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 =
1036
+ /[\u00ad\u034f\u061c\u115f\u1160\u17b4\u17b5\u180b-\u180f\u200b-\u200f\u202a-\u202e\u2060-\u206f\u3164\ufe00-\ufe0f\ufeff\uffa0]/gu;
1037
+ // Anything a chat app or browser could turn into a link: a URL with a
1038
+ // scheme, a www. host, an email address, or a dotted host name ending in a
1039
+ // letters-only label (with an optional port and path). Every branch starts
1040
+ // at a word boundary and every repetition is bounded, so a match attempt
1041
+ // does a bounded amount of work at each position (no catastrophic
1042
+ // backtracking); the input is also cut to SANITIZE_INPUT_MAX first.
1043
+ const LINK_LIKE =
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;
1051
+ /** At most this much input is looked at (4 x SUBMISSION_TEXT_MAX). */
1052
+ const SANITIZE_INPUT_MAX = 2000;
1053
+ /**
1054
+ * 0.7.0: text safe to show as plain text: control characters become spaces,
1055
+ * invisible and bidi characters are dropped, anything link-like becomes
1056
+ * `[link]`, whitespace is collapsed and the result is cut to
1057
+ * SUBMISSION_TEXT_MAX (never inside a surrogate pair). The same text in
1058
+ * comes out unchanged, so a parser can check a value is already safe.
1059
+ */
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) {
1076
+ // Bounded input before any expression runs; then unpaired surrogates (also
1077
+ // one the cut split) are dropped, so every pass sees well-formed text.
1078
+ let out = sanitizeOnce(
1079
+ String(text).slice(0, SANITIZE_INPUT_MAX),
1080
+ linkLike,
1081
+ invisible,
1082
+ );
1083
+ // A pass can only change the text again at its cut tail (a new link-like
1084
+ // tail, or a "[link]" pushed over the limit), so it settles within a few
1085
+ // passes; SANITIZE_PASSES is a hard bound. Should it ever not settle, the
1086
+ // empty string (itself stable) is returned: the result is ALWAYS a fixed
1087
+ // point, so sanitize(sanitize(x)) === sanitize(x) and a parser can check it.
1088
+ for (let pass = 0; pass < SANITIZE_PASSES; pass++) {
1089
+ const next = sanitizeOnce(out, linkLike, invisible);
1090
+ if (next === out) return out;
1091
+ out = next;
1092
+ }
1093
+ return "";
1094
+ }
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
+ }
1110
+ // A high surrogate not followed by a low one, or a low one not after a high one.
1111
+ const UNPAIRED_SURROGATES = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
1112
+ function sanitizeOnce(text, linkLike, invisible) {
1113
+ const cleaned = text
1114
+ .replace(UNPAIRED_SURROGATES, "")
1115
+ .replace(CONTROL_CHARACTERS, " ")
1116
+ .replace(invisible, "")
1117
+ .replace(linkLike, "[link]")
1118
+ .replace(/\s+/gu, " ")
1119
+ .trim();
1120
+ if (cleaned.length <= SUBMISSION_TEXT_MAX) return cleaned;
1121
+ let out = "";
1122
+ for (const point of cleaned) {
1123
+ if (out.length + point.length > SUBMISSION_TEXT_MAX) break;
1124
+ out += point;
1125
+ }
1126
+ return out.trimEnd();
1127
+ }
817
1128
  export function assertReceiptForOperation(
818
1129
  operation,
819
1130
  receipt,
@@ -831,9 +1142,16 @@ export function assertReceiptForOperation(
831
1142
  receipt.service === serviceForOperation(operation)
832
1143
  )
833
1144
  return receipt;
1145
+ if (
1146
+ status === "failed" &&
1147
+ receipt.kind === "ixo.submission.failed.v1" &&
1148
+ SUBMISSION_KINDS.includes(operation.kind)
1149
+ )
1150
+ return receipt;
834
1151
  if (
835
1152
  receiptKinds[operation.kind] !== receipt.kind ||
836
- receipt.kind === "service.failure.v1"
1153
+ receipt.kind === "service.failure.v1" ||
1154
+ receipt.kind === "ixo.submission.failed.v1"
837
1155
  )
838
1156
  fail("operation receipt");
839
1157
  // 0.6.0: a chain tx receipt names the approved chain and steps, in order.
@@ -844,6 +1162,13 @@ export function assertReceiptForOperation(
844
1162
  receipt.steps.some((step, i) => step.type !== operation.messages[i].type))
845
1163
  )
846
1164
  fail("receipt steps");
1165
+ // 0.7.0: an application or claim receipt names the approved collection.
1166
+ if (
1167
+ operation.kind !== CHAIN_TX_KIND &&
1168
+ "collectionId" in receipt &&
1169
+ receipt.collectionId !== operation.collectionId
1170
+ )
1171
+ fail("receipt collection");
847
1172
  // Every kind: the receipt must name the approved connection / target.
848
1173
  if (
849
1174
  "connectionId" in operation &&
@@ -1304,9 +1629,14 @@ function receiptFitsStatus(receipt, status) {
1304
1629
  if (status === "succeeded")
1305
1630
  return bank
1306
1631
  ? receipt.code === 0 && receipt.height !== null && !("reason" in receipt)
1307
- : receipt.kind !== "service.failure.v1";
1632
+ : receipt.kind !== "service.failure.v1" &&
1633
+ receipt.kind !== "ixo.submission.failed.v1";
1308
1634
  if (status === "failed") {
1309
- if (receipt.kind === "service.failure.v1") return true;
1635
+ if (
1636
+ receipt.kind === "service.failure.v1" ||
1637
+ receipt.kind === "ixo.submission.failed.v1"
1638
+ )
1639
+ return true;
1310
1640
  if (!bank) return false;
1311
1641
  if ("reason" in receipt) return true; // checked by parseReceipt
1312
1642
  return (
@@ -1385,12 +1715,65 @@ export function parseTransferDisplay(input) {
1385
1715
 
1386
1716
  /** One card kind for every chain transaction (1..8 messages, all or nothing). */
1387
1717
  export const CHAIN_TX_KIND = "ixo.chain.tx.v1";
1388
- 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([
1389
1720
  "cosmos.bank.send",
1390
1721
  "ixo.claims.submit",
1391
1722
  "ixo.claims.evaluate",
1392
1723
  "ixo.token.transfer",
1393
- ];
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
+ }
1394
1777
  export const CHAIN_TX_MAX_MESSAGES = 8;
1395
1778
  export const CHAIN_TX_MAX_TOKEN_LINES = 32;
1396
1779
  /** `check_tx_rejected`/`expired_not_included`: never included; `tx_failed`: included with code != 0. */
@@ -1402,6 +1785,137 @@ export const CHAIN_TX_FAILURE_REASONS = [
1402
1785
  export const CHAIN_TX_RISK_LEVELS = ["low", "medium", "high", "critical"];
1403
1786
  /** EvaluationStatus values a chain tx may record (0 pending and 5 flagged are refused). */
1404
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
+ }
1405
1919
  // The chain's DID rule (x/iid/types/iid.go didValidationRegexpStr): segments of
1406
1920
  // [A-Za-z0-9._-] or a `%` followed by two hex digits, joined by ':', the last
1407
1921
  // one non-empty. Anchored at both ends here (the chain's own regex anchors
@@ -1447,7 +1961,177 @@ const CHAIN_TX_MESSAGE_KEYS = {
1447
1961
  "verificationProof",
1448
1962
  ],
1449
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"],
1450
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"];
1451
2135
  const plain = (value) =>
1452
2136
  value !== null && typeof value === "object" && !Array.isArray(value);
1453
2137
  const isText = (value, min = 1, max = 200) =>
@@ -1458,9 +2142,404 @@ const isId = (value, max) => isMatch(value, CHAIN_ID_CHARS, max);
1458
2142
  const isCollectionId = (value) =>
1459
2143
  isMatch(value, COLLECTION_ID, 20) && BigInt(value) <= UINT64_MAX;
1460
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
+ }
1461
2538
 
1462
2539
  /** The first bad field of one message (relative to the message), or null. */
1463
2540
  function chainTxMessageField(m) {
2541
+ if (Object.hasOwn(CHAIN_TX_LEVEL6_FIELDS, m.type))
2542
+ return CHAIN_TX_LEVEL6_FIELDS[m.type](m);
1464
2543
  if (m.type === "cosmos.bank.send") {
1465
2544
  if (!isMatch(m.toAddress, ACCOUNT_ADDRESS)) return "toAddress";
1466
2545
  if (!isMatch(m.amountBaseUnits, BASE_UNITS, 78)) return "amountBaseUnits";
@@ -1496,20 +2575,7 @@ function chainTxMessageField(m) {
1496
2575
  }
1497
2576
  // ixo.token.transfer
1498
2577
  if (!isMatch(m.recipient, ACCOUNT_ADDRESS)) return "recipient";
1499
- if (
1500
- !Array.isArray(m.tokens) ||
1501
- m.tokens.length < 1 ||
1502
- m.tokens.length > CHAIN_TX_MAX_TOKEN_LINES
1503
- )
1504
- return "tokens";
1505
- for (const [j, token] of m.tokens.entries()) {
1506
- if (!plain(token)) return `tokens[${j}]`;
1507
- for (const key of Object.keys(token))
1508
- if (key !== "id" && key !== "amount") return `tokens[${j}].${key}`;
1509
- if (!isId(token.id, 128)) return `tokens[${j}].id`;
1510
- if (!isMatch(token.amount, BASE_UNITS, 78)) return `tokens[${j}].amount`;
1511
- }
1512
- return null;
2578
+ return tokenLinesField(m.tokens);
1513
2579
  }
1514
2580
 
1515
2581
  /** The first bad field of a chain tx operation (`messages[1].toAddress`), or null. */
@@ -1567,7 +2633,11 @@ export function chainTxIssue(input) {
1567
2633
  return null;
1568
2634
  }
1569
2635
 
1570
- /** `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
+ */
1571
2641
  export function parseChainTxCapabilities(input) {
1572
2642
  const c = object(input, "capabilities.chainTx");
1573
2643
  exact(c, ["messageTypes", "maxMessages"], "capabilities.chainTx");