@sparkdreamnft/sparkdreamjs 0.0.46 → 0.0.47

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.
Files changed (70) hide show
  1. package/amino-schema.d.ts +5741 -0
  2. package/amino-schema.js +8 -0
  3. package/chain-amino.d.ts +61 -0
  4. package/chain-amino.js +670 -0
  5. package/esm/amino-schema.js +5 -0
  6. package/esm/chain-amino.js +665 -0
  7. package/esm/nested-amino.js +7 -1
  8. package/esm/sparkdream/artifact/v1/tx.amino.js +12 -473
  9. package/esm/sparkdream/blog/v1/tx.amino.js +15 -135
  10. package/esm/sparkdream/collect/v1/tx.amino.js +15 -254
  11. package/esm/sparkdream/commons/v1/tx.amino.js +12 -258
  12. package/esm/sparkdream/ecosystem/v1/tx.amino.js +15 -26
  13. package/esm/sparkdream/federation/v1/tx.amino.js +12 -174
  14. package/esm/sparkdream/forum/v1/tx.amino.js +15 -231
  15. package/esm/sparkdream/futarchy/v1/tx.amino.js +16 -38
  16. package/esm/sparkdream/guardian/v1/tx.amino.js +12 -33
  17. package/esm/sparkdream/name/v1/tx.amino.js +16 -63
  18. package/esm/sparkdream/rep/v1/tx.amino.js +12 -484
  19. package/esm/sparkdream/reveal/v1/tx.amino.js +15 -73
  20. package/esm/sparkdream/season/v1/tx.amino.js +12 -276
  21. package/esm/sparkdream/service/v1/tx.amino.js +16 -78
  22. package/esm/sparkdream/session/v1/tx.amino.js +16 -271
  23. package/esm/sparkdream/shield/v1/tx.amino.js +15 -80
  24. package/esm/sparkdream/sparkdream/v1/tx.amino.js +16 -8
  25. package/esm/sparkdream/split/v1/tx.amino.js +16 -8
  26. package/esm/sparkdream/vault/v1/tx.amino.js +12 -105
  27. package/nested-amino.d.ts +5 -1
  28. package/nested-amino.js +8 -1
  29. package/package.json +1 -1
  30. package/sparkdream/artifact/v1/tx.amino.d.ts +1 -353
  31. package/sparkdream/artifact/v1/tx.amino.js +47 -475
  32. package/sparkdream/blog/v1/tx.amino.d.ts +1 -103
  33. package/sparkdream/blog/v1/tx.amino.js +50 -137
  34. package/sparkdream/bundle.d.ts +19 -2047
  35. package/sparkdream/client.d.ts +1 -2009
  36. package/sparkdream/collect/v1/tx.amino.d.ts +1 -153
  37. package/sparkdream/collect/v1/tx.amino.js +50 -256
  38. package/sparkdream/commons/v1/tx.amino.d.ts +1 -123
  39. package/sparkdream/commons/v1/tx.amino.js +49 -262
  40. package/sparkdream/ecosystem/v1/tx.amino.d.ts +1 -13
  41. package/sparkdream/ecosystem/v1/tx.amino.js +50 -28
  42. package/sparkdream/federation/v1/tx.amino.d.ts +1 -128
  43. package/sparkdream/federation/v1/tx.amino.js +47 -176
  44. package/sparkdream/forum/v1/tx.amino.d.ts +1 -203
  45. package/sparkdream/forum/v1/tx.amino.js +50 -233
  46. package/sparkdream/futarchy/v1/tx.amino.d.ts +1 -38
  47. package/sparkdream/futarchy/v1/tx.amino.js +49 -38
  48. package/sparkdream/guardian/v1/tx.amino.d.ts +1 -7
  49. package/sparkdream/guardian/v1/tx.amino.js +49 -37
  50. package/sparkdream/name/v1/tx.amino.d.ts +1 -63
  51. package/sparkdream/name/v1/tx.amino.js +49 -63
  52. package/sparkdream/rep/v1/tx.amino.d.ts +1 -353
  53. package/sparkdream/rep/v1/tx.amino.js +47 -486
  54. package/sparkdream/reveal/v1/tx.amino.d.ts +1 -53
  55. package/sparkdream/reveal/v1/tx.amino.js +50 -75
  56. package/sparkdream/season/v1/tx.amino.d.ts +1 -218
  57. package/sparkdream/season/v1/tx.amino.js +47 -278
  58. package/sparkdream/service/v1/tx.amino.d.ts +1 -78
  59. package/sparkdream/service/v1/tx.amino.js +49 -78
  60. package/sparkdream/session/v1/tx.amino.d.ts +1 -93
  61. package/sparkdream/session/v1/tx.amino.js +48 -270
  62. package/sparkdream/shield/v1/tx.amino.d.ts +1 -28
  63. package/sparkdream/shield/v1/tx.amino.js +50 -82
  64. package/sparkdream/sparkdream/v1/tx.amino.d.ts +1 -8
  65. package/sparkdream/sparkdream/v1/tx.amino.js +49 -8
  66. package/sparkdream/split/v1/tx.amino.d.ts +1 -8
  67. package/sparkdream/split/v1/tx.amino.js +49 -8
  68. package/sparkdream/vault/v1/tx.amino.d.ts +1 -43
  69. package/sparkdream/vault/v1/tx.amino.js +49 -109
  70. package/varint.d.ts +1 -1
package/chain-amino.js ADDED
@@ -0,0 +1,670 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fillNonNullable = fillNonNullable;
4
+ exports.chainAminoConverters = chainAminoConverters;
5
+ exports.renderAminoJson = renderAminoJson;
6
+ /**
7
+ * Amino-JSON converters (the sign mode Keplr+Ledger use) for every sparkdream
8
+ * Msg, matching the chain's cosmossdk.io/x/tx@v0.14.0 signing/aminojson byte
9
+ * for byte.
10
+ *
11
+ * Instead of one hand-written converter per message (which drifted from the
12
+ * protos on every sync: missing messages, stale field sets, `[]` for empty
13
+ * lists, empty bytes as "", human-readable Dec strings, lost oneof wrappers),
14
+ * every module's AminoConverter map is built here from one schema:
15
+ *
16
+ * - toAmino encodes the message with its Telescope codec, decodes the
17
+ * protobuf bytes and renders them with aminojson's rules
18
+ * (json_marshal.go, encoder.go, any.go, time.go), as the chain does.
19
+ * - fromAmino is the exact inverse: amino JSON to protobuf bytes, decoded
20
+ * with the codec.
21
+ *
22
+ * The schema (amino-schema.ts) is exported by the chain repo
23
+ * (`go run ./cmd/aminogolden schema`): field names, kinds and the options
24
+ * aminojson acts on (dont_omitempty, cosmos_proto.scalar, amino.encoding,
25
+ * oneof names, gogoproto.nullable). __tests__/amino-golden.test.ts checks
26
+ * every Msg against the chain's own encoder.
27
+ *
28
+ * An Any whose inner type the schema does not describe (a cosmos-sdk message
29
+ * inside a proposal) is converted through the registry and AminoTypes given
30
+ * to configureNestedAminoConverter, as before.
31
+ */
32
+ const nested_amino_1 = require("./nested-amino");
33
+ const amino_schema_1 = require("./amino-schema");
34
+ const schema = amino_schema_1.aminoSchema;
35
+ const BUILTIN = new Set(["google.protobuf.Timestamp", "google.protobuf.Duration", "google.protobuf.Any"]);
36
+ const byAminoName = new Map();
37
+ for (const [name, md] of Object.entries(schema.messages))
38
+ if (md.a)
39
+ byAminoName.set(md.a, name);
40
+ function readVarint(buf, pos) {
41
+ let result = BigInt(0);
42
+ let shift = BigInt(0);
43
+ for (;;) {
44
+ if (pos.i >= buf.length)
45
+ throw new Error("truncated varint");
46
+ const b = buf[pos.i++];
47
+ result |= BigInt(b & 0x7f) << shift;
48
+ if ((b & 0x80) === 0)
49
+ return result;
50
+ shift += BigInt(7);
51
+ if (shift > BigInt(63))
52
+ throw new Error("varint overflow");
53
+ }
54
+ }
55
+ function readFixed(buf, pos, size) {
56
+ if (pos.i + size > buf.length)
57
+ throw new Error("truncated fixed");
58
+ let v = BigInt(0);
59
+ for (let j = size - 1; j >= 0; j--)
60
+ v = (v << BigInt(8)) | BigInt(buf[pos.i + j]);
61
+ pos.i += size;
62
+ return v;
63
+ }
64
+ function parseFields(buf) {
65
+ const out = new Map();
66
+ const pos = { i: 0 };
67
+ while (pos.i < buf.length) {
68
+ const tag = Number(readVarint(buf, pos));
69
+ const no = tag >>> 3;
70
+ const wire = tag & 7;
71
+ let v;
72
+ switch (wire) {
73
+ case 0:
74
+ v = { wire, num: readVarint(buf, pos) };
75
+ break;
76
+ case 1:
77
+ v = { wire, num: readFixed(buf, pos, 8) };
78
+ break;
79
+ case 5:
80
+ v = { wire, num: readFixed(buf, pos, 4) };
81
+ break;
82
+ case 2: {
83
+ const len = Number(readVarint(buf, pos));
84
+ if (pos.i + len > buf.length)
85
+ throw new Error("truncated bytes");
86
+ v = { wire, bytes: buf.subarray(pos.i, pos.i + len) };
87
+ pos.i += len;
88
+ break;
89
+ }
90
+ default:
91
+ throw new Error(`unsupported wire type ${wire}`);
92
+ }
93
+ const list = out.get(no);
94
+ if (list)
95
+ list.push(v);
96
+ else
97
+ out.set(no, [v]);
98
+ }
99
+ return out;
100
+ }
101
+ const VARINT_KINDS = new Set(["int32", "int64", "uint32", "uint64", "sint32", "sint64", "bool", "enum"]);
102
+ const FIXED32_KINDS = new Set(["fixed32", "sfixed32", "float"]);
103
+ const FIXED64_KINDS = new Set(["fixed64", "sfixed64", "double"]);
104
+ const NUMERIC_KINDS = new Set([...VARINT_KINDS, ...FIXED32_KINDS, ...FIXED64_KINDS]);
105
+ /** Scalar elements of a field, unpacking packed encodings. */
106
+ function scalarElements(f, values) {
107
+ const out = [];
108
+ for (const v of values) {
109
+ if (v.wire === 2 && NUMERIC_KINDS.has(f.k)) {
110
+ const pos = { i: 0 };
111
+ const b = v.bytes;
112
+ while (pos.i < b.length) {
113
+ if (VARINT_KINDS.has(f.k))
114
+ out.push(readVarint(b, pos));
115
+ else
116
+ out.push(readFixed(b, pos, FIXED32_KINDS.has(f.k) ? 4 : 8));
117
+ }
118
+ }
119
+ else {
120
+ out.push(v.num);
121
+ }
122
+ }
123
+ return out;
124
+ }
125
+ function concatBytes(parts) {
126
+ if (parts.length === 1)
127
+ return parts[0];
128
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
129
+ let o = 0;
130
+ for (const p of parts) {
131
+ out.set(p, o);
132
+ o += p.length;
133
+ }
134
+ return out;
135
+ }
136
+ // --------------------------------------------------------- wire encoding
137
+ class Writer {
138
+ parts = [];
139
+ varint(v) {
140
+ let n = BigInt.asUintN(64, v);
141
+ const bytes = [];
142
+ do {
143
+ let b = Number(n & BigInt(0x7f));
144
+ n >>= BigInt(7);
145
+ if (n > BigInt(0))
146
+ b |= 0x80;
147
+ bytes.push(b);
148
+ } while (n > BigInt(0));
149
+ this.parts.push(Uint8Array.from(bytes));
150
+ return this;
151
+ }
152
+ fixed(v, size) {
153
+ const out = new Uint8Array(size);
154
+ let n = BigInt.asUintN(size * 8, v);
155
+ for (let i = 0; i < size; i++) {
156
+ out[i] = Number(n & BigInt(0xff));
157
+ n >>= BigInt(8);
158
+ }
159
+ this.parts.push(out);
160
+ return this;
161
+ }
162
+ tag(no, wire) {
163
+ return this.varint(BigInt((no << 3) | wire));
164
+ }
165
+ bytes(no, b) {
166
+ this.tag(no, 2).varint(BigInt(b.length));
167
+ this.parts.push(b);
168
+ return this;
169
+ }
170
+ finish() {
171
+ return concatBytes(this.parts.length ? this.parts : [new Uint8Array()]);
172
+ }
173
+ }
174
+ // --------------------------------------------------------- value helpers
175
+ const utf8Decoder = new TextDecoder("utf-8", { fatal: true });
176
+ const utf8Encoder = new TextEncoder();
177
+ function base64(bytes) {
178
+ let s = "";
179
+ for (let i = 0; i < bytes.length; i++)
180
+ s += String.fromCharCode(bytes[i]);
181
+ return btoa(s);
182
+ }
183
+ function fromBase64(s) {
184
+ const bin = atob(s);
185
+ const out = new Uint8Array(bin.length);
186
+ for (let i = 0; i < bin.length; i++)
187
+ out[i] = bin.charCodeAt(i);
188
+ return out;
189
+ }
190
+ function zigzagDecode(u, bits) {
191
+ const v = BigInt.asUintN(bits, u);
192
+ return BigInt.asIntN(bits, (v >> BigInt(1)) ^ -(v & BigInt(1)));
193
+ }
194
+ function zigzagEncode(v, bits) {
195
+ const n = BigInt.asIntN(bits, v);
196
+ return BigInt.asUintN(bits, (n << BigInt(1)) ^ (n >> BigInt(bits - 1)));
197
+ }
198
+ function scalarJson(kind, n, bytes) {
199
+ const v = n ?? BigInt(0);
200
+ switch (kind) {
201
+ case "string":
202
+ return utf8Decoder.decode(bytes ?? new Uint8Array());
203
+ case "bytes":
204
+ // encoding/json marshals a nil []byte as null, a non-nil one as base64.
205
+ return bytes && bytes.length > 0 ? base64(bytes) : null;
206
+ case "bool":
207
+ return v !== BigInt(0);
208
+ case "int32":
209
+ case "enum":
210
+ case "sfixed32":
211
+ return Number(BigInt.asIntN(32, v));
212
+ case "uint32":
213
+ case "fixed32":
214
+ return Number(BigInt.asUintN(32, v));
215
+ case "sint32":
216
+ return Number(zigzagDecode(v, 32));
217
+ // 64-bit integers are quoted.
218
+ case "int64":
219
+ case "sfixed64":
220
+ return BigInt.asIntN(64, v).toString();
221
+ case "uint64":
222
+ case "fixed64":
223
+ return BigInt.asUintN(64, v).toString();
224
+ case "sint64":
225
+ return zigzagDecode(v, 64).toString();
226
+ }
227
+ // aminojson has no case for floats (marshal returns "unknown type").
228
+ throw new Error(`amino JSON cannot encode a ${kind} field`);
229
+ }
230
+ function isZeroScalar(kind, n, bytes) {
231
+ if (kind === "string" || kind === "bytes")
232
+ return !bytes || bytes.length === 0;
233
+ return (n ?? BigInt(0)) === BigInt(0);
234
+ }
235
+ /** math.LegacyDec.String() of an 18-decimal integer representation. */
236
+ function legacyDecString(atomics) {
237
+ if (!/^-?\d+$/.test(atomics))
238
+ throw new Error(`invalid LegacyDec ${JSON.stringify(atomics)}`);
239
+ const neg = atomics.startsWith("-");
240
+ let digits = BigInt(neg ? atomics.slice(1) : atomics).toString();
241
+ if (digits === "0")
242
+ return "0.000000000000000000";
243
+ digits = digits.padStart(19, "0");
244
+ return `${neg ? "-" : ""}${digits.slice(0, -18)}.${digits.slice(-18)}`;
245
+ }
246
+ /** Inverse of legacyDecString. */
247
+ function legacyDecAtomics(dec) {
248
+ const m = /^(-?)(\d+)(?:\.(\d{1,18}))?$/.exec(dec);
249
+ if (!m)
250
+ throw new Error(`invalid Dec ${JSON.stringify(dec)}`);
251
+ const atomics = BigInt(m[2] + (m[3] ?? "").padEnd(18, "0"));
252
+ return (m[1] && atomics !== BigInt(0) ? "-" : "") + atomics.toString();
253
+ }
254
+ function sortedJson(v) {
255
+ if (Array.isArray(v))
256
+ return v.map(sortedJson);
257
+ if (v && typeof v === "object") {
258
+ const o = v;
259
+ return Object.fromEntries(Object.keys(o).sort().map((k) => [k, sortedJson(o[k])]));
260
+ }
261
+ return v;
262
+ }
263
+ function rfc3339(seconds, nanos) {
264
+ if (nanos < 0)
265
+ throw new Error("nanos must be non-negative on timestamp");
266
+ const date = new Date(Number(seconds) * 1000);
267
+ if (Number.isNaN(date.getTime()))
268
+ throw new Error("timestamp out of range");
269
+ const base = date.toISOString().slice(0, 19);
270
+ if (nanos === 0)
271
+ return `${base}Z`;
272
+ return `${base}.${String(nanos).padStart(9, "0").replace(/0+$/, "")}Z`;
273
+ }
274
+ function parseRfc3339(s) {
275
+ const m = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?Z$/.exec(s);
276
+ if (!m)
277
+ throw new Error(`invalid timestamp ${JSON.stringify(s)}`);
278
+ const ms = Date.parse(`${m[1]}Z`);
279
+ return { seconds: BigInt(Math.floor(ms / 1000)), nanos: Number((m[2] ?? "").padEnd(9, "0")) };
280
+ }
281
+ // ---------------------------------------------------------------- render
282
+ function render(typeName, bytes, isAny) {
283
+ const md = schema.messages[typeName];
284
+ const name = isAny ? md?.a ?? `/${typeName}` : md?.a;
285
+ const value = renderMessage(typeName, bytes);
286
+ return name !== undefined ? { type: name, value } : value;
287
+ }
288
+ /** protoreflect Message.Has for a dynamic proto3 message. */
289
+ function fieldHas(f, values) {
290
+ if (values.length === 0)
291
+ return false;
292
+ if (f.k === "map")
293
+ return true;
294
+ if (f.r)
295
+ return NUMERIC_KINDS.has(f.k) ? scalarElements(f, values).length > 0 : true;
296
+ if (f.k === "message" || f.o || f.pr)
297
+ return true;
298
+ const last = values[values.length - 1];
299
+ return !isZeroScalar(f.k, last.num, last.bytes);
300
+ }
301
+ function renderMessage(typeName, bytes) {
302
+ switch (typeName) {
303
+ case "google.protobuf.Timestamp": {
304
+ const w = parseFields(bytes);
305
+ return rfc3339(BigInt.asIntN(64, w.get(1)?.at(-1)?.num ?? BigInt(0)), Number(BigInt.asIntN(32, w.get(2)?.at(-1)?.num ?? BigInt(0))));
306
+ }
307
+ case "google.protobuf.Duration": {
308
+ const w = parseFields(bytes);
309
+ const seconds = BigInt.asIntN(64, w.get(1)?.at(-1)?.num ?? BigInt(0));
310
+ const nanos = BigInt.asIntN(32, w.get(2)?.at(-1)?.num ?? BigInt(0));
311
+ return (nanos + seconds * BigInt(1_000_000_000)).toString();
312
+ }
313
+ case "google.protobuf.Any":
314
+ return renderAny(bytes);
315
+ }
316
+ const md = schema.messages[typeName];
317
+ if (!md)
318
+ throw new Error(`amino schema has no message ${typeName}`);
319
+ if (md.me)
320
+ throw new Error(`amino message_encoding ${md.me} (${typeName}) is not supported`);
321
+ const wire = parseFields(bytes);
322
+ const sortName = (f) => (f.o ? f.o[0] : f.n);
323
+ const fields = [...md.f].sort((a, b) => (sortName(a) < sortName(b) ? -1 : sortName(a) > sortName(b) ? 1 : 0));
324
+ const oneofSet = new Set(md.f.filter((f) => f.o && wire.has(f.no)).map((f) => f.o[0]));
325
+ const emptyOneofWritten = new Set();
326
+ const out = {};
327
+ for (const f of fields) {
328
+ const values = wire.get(f.no) ?? [];
329
+ let name = f.n;
330
+ let writeNil = false;
331
+ if (!fieldHas(f, values)) {
332
+ if (f.o && !oneofSet.has(f.o[0]) && !emptyOneofWritten.has(f.o[0])) {
333
+ name = f.o[0];
334
+ writeNil = true;
335
+ emptyOneofWritten.add(f.o[0]);
336
+ }
337
+ else if (!f.d) {
338
+ continue;
339
+ }
340
+ else if (f.k === "message" && !f.r) {
341
+ throw new Error(`not supported: dont_omit_empty=true on invalid (nil?) message field: ${f.n}`);
342
+ }
343
+ }
344
+ let value;
345
+ const encoder = fieldEncoder(f);
346
+ if (encoder)
347
+ value = encoder(values);
348
+ else if (writeNil)
349
+ value = null;
350
+ else
351
+ value = renderValue(f, values);
352
+ if (f.o && !writeNil)
353
+ out[f.o[0]] = { type: f.o[1], value: { [name]: value } };
354
+ else
355
+ out[name] = value;
356
+ }
357
+ return out;
358
+ }
359
+ /** encoder.go getFieldEncoder: amino.encoding first, then cosmos_proto.scalar. */
360
+ function fieldEncoder(f) {
361
+ if (f.e === "legacy_coins")
362
+ return (values) => (values.length === 0 ? [] : renderList(f, values));
363
+ if (f.e === "inline_json") {
364
+ return (values) => sortedJson(JSON.parse(values.length ? utf8Decoder.decode(values[values.length - 1].bytes) : ""));
365
+ }
366
+ if (f.sc === "int" || f.sc === "dec") {
367
+ if (f.r)
368
+ throw new Error(`unsupported repeated ${f.sc} scalar ${f.n}`);
369
+ return (values) => {
370
+ const last = values[values.length - 1];
371
+ const text = last ? utf8Decoder.decode(last.bytes) : "";
372
+ if (text === "")
373
+ return "0";
374
+ if (f.sc === "dec")
375
+ return legacyDecString(text);
376
+ // cosmosIntEncoder: a string goes through as-is, bytes are parsed.
377
+ return f.k === "bytes" ? BigInt(text).toString() : text;
378
+ };
379
+ }
380
+ return undefined;
381
+ }
382
+ function renderValue(f, values) {
383
+ if (f.k === "map")
384
+ throw new Error("maps are not supported");
385
+ if (f.r)
386
+ return values.length === 0 ? null : renderList(f, values);
387
+ if (f.k === "message")
388
+ return renderMessage(f.t, concatBytes(values.map((v) => v.bytes)));
389
+ const last = values[values.length - 1];
390
+ // dont_omitempty on an unset scalar renders the zero value.
391
+ if (!last)
392
+ return scalarJson(f.k, BigInt(0), f.k === "string" ? new Uint8Array() : undefined);
393
+ return scalarJson(f.k, last.num, last.bytes);
394
+ }
395
+ function renderList(f, values) {
396
+ if (f.k === "message")
397
+ return values.map((v) => renderMessage(f.t, v.bytes));
398
+ if (f.k === "string" || f.k === "bytes")
399
+ return values.map((v) => scalarJson(f.k, undefined, v.bytes));
400
+ return scalarElements(f, values).map((n) => scalarJson(f.k, n, undefined));
401
+ }
402
+ function renderAny(bytes) {
403
+ const w = parseFields(bytes);
404
+ const typeUrl = utf8Decoder.decode(w.get(1)?.at(-1)?.bytes ?? new Uint8Array());
405
+ const value = w.get(2)?.at(-1)?.bytes ?? new Uint8Array();
406
+ if (!typeUrl.startsWith("/"))
407
+ throw new Error(`can't resolve type URL ${typeUrl}`);
408
+ const typeName = typeUrl.slice(1);
409
+ if (typeName in schema.messages)
410
+ return render(typeName, value, true);
411
+ const cfg = (0, nested_amino_1.getNestedAminoConfig)();
412
+ const codec = cfg?.registry.lookupType(typeUrl);
413
+ if (!cfg || !codec) {
414
+ throw new Error(`can't resolve type URL ${typeUrl}: call configureNestedAminoConverter({registry, aminoTypes}) ` +
415
+ "with a registry and AminoTypes that know it");
416
+ }
417
+ return cfg.aminoTypes.toAmino({ typeUrl, value: codec.decode(value) });
418
+ }
419
+ // ---------------------------------------------------------------- encode
420
+ /** Amino JSON of a message back to its protobuf bytes (the inverse of renderMessage). */
421
+ function encodeMessage(typeName, json) {
422
+ const w = new Writer();
423
+ switch (typeName) {
424
+ case "google.protobuf.Timestamp": {
425
+ const { seconds, nanos } = parseRfc3339(json);
426
+ if (seconds !== BigInt(0))
427
+ w.tag(1, 0).varint(seconds);
428
+ if (nanos !== 0)
429
+ w.tag(2, 0).varint(BigInt(nanos));
430
+ return w.finish();
431
+ }
432
+ case "google.protobuf.Duration": {
433
+ const total = BigInt(json);
434
+ const seconds = total / BigInt(1_000_000_000);
435
+ const nanos = total % BigInt(1_000_000_000);
436
+ if (seconds !== BigInt(0))
437
+ w.tag(1, 0).varint(seconds);
438
+ if (nanos !== BigInt(0))
439
+ w.tag(2, 0).varint(nanos);
440
+ return w.finish();
441
+ }
442
+ case "google.protobuf.Any": {
443
+ const { typeUrl, value } = encodeAny(json);
444
+ w.bytes(1, utf8Encoder.encode(typeUrl));
445
+ if (value.length)
446
+ w.bytes(2, value);
447
+ return w.finish();
448
+ }
449
+ }
450
+ const md = schema.messages[typeName];
451
+ if (!md)
452
+ throw new Error(`amino schema has no message ${typeName}`);
453
+ if (md.me)
454
+ throw new Error(`amino message_encoding ${md.me} (${typeName}) is not supported`);
455
+ if (json === null || typeof json !== "object")
456
+ throw new Error(`${typeName}: expected an object`);
457
+ for (const f of md.f) {
458
+ let value;
459
+ let present = false;
460
+ if (f.o) {
461
+ const wrapper = json[f.o[0]];
462
+ if (!wrapper || wrapper.type !== f.o[1] || !wrapper.value || !(f.n in wrapper.value))
463
+ continue;
464
+ value = wrapper.value[f.n];
465
+ present = true; // a set oneof member keeps its presence even at zero
466
+ }
467
+ else {
468
+ value = json[f.n];
469
+ present = !!f.pr;
470
+ }
471
+ if (value === undefined || value === null)
472
+ continue;
473
+ encodeField(w, f, value, present);
474
+ }
475
+ return w.finish();
476
+ }
477
+ function encodeField(w, f, value, present) {
478
+ if (f.k === "map")
479
+ throw new Error("maps are not supported");
480
+ if (f.r) {
481
+ if (!Array.isArray(value))
482
+ throw new Error(`${f.n}: expected a list`);
483
+ if (NUMERIC_KINDS.has(f.k)) {
484
+ if (value.length === 0)
485
+ return;
486
+ const packed = new Writer();
487
+ for (const el of value)
488
+ writeNumeric(packed, f.k, el);
489
+ w.bytes(f.no, packed.finish());
490
+ return;
491
+ }
492
+ for (const el of value) {
493
+ if (f.k === "message")
494
+ w.bytes(f.no, encodeMessage(f.t, el));
495
+ else
496
+ w.bytes(f.no, scalarBytes(f, el));
497
+ }
498
+ return;
499
+ }
500
+ if (f.k === "message") {
501
+ w.bytes(f.no, encodeMessage(f.t, value));
502
+ return;
503
+ }
504
+ if (f.k === "string" || f.k === "bytes") {
505
+ let bytes = scalarBytes(f, value);
506
+ if (f.sc === "dec" && value === "0")
507
+ bytes = new Uint8Array(); // rendered from an empty Dec
508
+ if (bytes.length > 0 || present)
509
+ w.bytes(f.no, bytes);
510
+ return;
511
+ }
512
+ const n = numericValue(f.k, value);
513
+ if (n !== BigInt(0) || present) {
514
+ w.tag(f.no, FIXED32_KINDS.has(f.k) ? 5 : FIXED64_KINDS.has(f.k) ? 1 : 0);
515
+ writeNumeric(w, f.k, value);
516
+ }
517
+ }
518
+ function scalarBytes(f, value) {
519
+ if (f.k === "bytes") {
520
+ if (f.sc === "int" || f.sc === "dec")
521
+ return utf8Encoder.encode(f.sc === "dec" ? legacyDecAtomics(value) : String(value));
522
+ return fromBase64(value);
523
+ }
524
+ if (f.sc === "dec")
525
+ return utf8Encoder.encode(value === "0" ? "" : legacyDecAtomics(value));
526
+ return utf8Encoder.encode(String(value));
527
+ }
528
+ function numericValue(kind, value) {
529
+ if (kind === "bool")
530
+ return value ? BigInt(1) : BigInt(0);
531
+ if (kind === "float" || kind === "double")
532
+ throw new Error(`amino JSON cannot encode a ${kind} field`);
533
+ return BigInt(value);
534
+ }
535
+ function writeNumeric(w, kind, value) {
536
+ const n = numericValue(kind, value);
537
+ switch (kind) {
538
+ case "sint32":
539
+ w.varint(zigzagEncode(n, 32));
540
+ return;
541
+ case "sint64":
542
+ w.varint(zigzagEncode(n, 64));
543
+ return;
544
+ case "fixed32":
545
+ case "sfixed32":
546
+ w.fixed(n, 4);
547
+ return;
548
+ case "fixed64":
549
+ case "sfixed64":
550
+ w.fixed(n, 8);
551
+ return;
552
+ default:
553
+ w.varint(n);
554
+ }
555
+ }
556
+ function encodeAny(json) {
557
+ const type = json?.type;
558
+ if (!type)
559
+ throw new Error("Any: expected {type, value}");
560
+ const typeName = byAminoName.get(type) ?? (type.startsWith("/") && type.slice(1) in schema.messages ? type.slice(1) : undefined);
561
+ if (typeName)
562
+ return { typeUrl: `/${typeName}`, value: encodeMessage(typeName, json.value ?? {}) };
563
+ const cfg = (0, nested_amino_1.getNestedAminoConfig)();
564
+ if (!cfg)
565
+ throw new Error(`can't resolve amino type ${type}: call configureNestedAminoConverter first`);
566
+ const decoded = cfg.aminoTypes.fromAmino(json);
567
+ const codec = cfg.registry.lookupType(decoded.typeUrl);
568
+ if (!codec)
569
+ throw new Error(`No proto codec registered for inner type ${decoded.typeUrl}.`);
570
+ return { typeUrl: decoded.typeUrl, value: codec.encode(codec.fromPartial(decoded.value)).finish() };
571
+ }
572
+ // ------------------------------------------------------- non-nullable fill
573
+ /**
574
+ * Returns value with every dont_omitempty embedded message present (empty
575
+ * when left out), recursively. aminojson refuses to render an absent one, and
576
+ * Go clients never send one absent (they are gogoproto.nullable = false), but
577
+ * Telescope's fromPartial leaves them undefined.
578
+ * Filled on the plain value, before fromPartial, so the codec builds proper
579
+ * defaults; a Timestamp gets the epoch.
580
+ */
581
+ function fillNonNullable(typeName, value) {
582
+ const md = schema.messages[typeName];
583
+ if (!md || !value || typeof value !== "object")
584
+ return value;
585
+ const out = { ...value };
586
+ for (const f of md.f) {
587
+ if (f.k !== "message" || !f.j || !f.t)
588
+ continue;
589
+ const v = out[f.j];
590
+ if (f.r) {
591
+ if (Array.isArray(v) && !BUILTIN.has(f.t))
592
+ out[f.j] = v.map((el) => fillNonNullable(f.t, el));
593
+ continue;
594
+ }
595
+ if (v === undefined || v === null) {
596
+ // Only a dont_omitempty message must be present: aminojson refuses to
597
+ // render it absent. Others render the same either way, so stay untouched.
598
+ if (!f.d)
599
+ continue;
600
+ out[f.j] = f.t === "google.protobuf.Timestamp" ? new Date(0) : BUILTIN.has(f.t) ? {} : fillNonNullable(f.t, {});
601
+ continue;
602
+ }
603
+ if (!BUILTIN.has(f.t))
604
+ out[f.j] = fillNonNullable(f.t, v);
605
+ }
606
+ return out;
607
+ }
608
+ // --------------------------------------------------------- decode + prune
609
+ /**
610
+ * Telescope's decode fills every embedded message the bytes lack with a
611
+ * default (createBase): an empty Coin, which re-encodes as present, or
612
+ * `new Date()` for a Timestamp, which re-encodes as the current time. cosmjs
613
+ * builds the signed tx body by re-encoding fromAmino's result, so clear each
614
+ * embedded message the bytes did not carry, recursively: the body then
615
+ * encodes back to exactly these bytes.
616
+ */
617
+ function pruneAbsent(typeName, bytes, value) {
618
+ const md = schema.messages[typeName];
619
+ if (!md || !value || typeof value !== "object")
620
+ return value;
621
+ const wire = parseFields(bytes);
622
+ for (const f of md.f) {
623
+ if (f.k !== "message" || !f.j || !f.t)
624
+ continue;
625
+ const values = wire.get(f.no) ?? [];
626
+ if (f.r) {
627
+ const list = value[f.j];
628
+ if (Array.isArray(list) && !BUILTIN.has(f.t)) {
629
+ value[f.j] = list.map((el, i) => (values[i] ? pruneAbsent(f.t, values[i].bytes, el) : el));
630
+ }
631
+ continue;
632
+ }
633
+ if (values.length === 0)
634
+ value[f.j] = undefined;
635
+ else if (!BUILTIN.has(f.t))
636
+ value[f.j] = pruneAbsent(f.t, concatBytes(values.map((v) => v.bytes)), value[f.j]);
637
+ }
638
+ return value;
639
+ }
640
+ /**
641
+ * The AminoConverter map for every Msg of a proto package
642
+ * ("sparkdream.<module>.v1"), given the module's generated tx codecs.
643
+ */
644
+ function chainAminoConverters(pkg, txModule) {
645
+ const out = {};
646
+ for (const typeName of schema.msgs) {
647
+ if (!typeName.startsWith(`${pkg}.`))
648
+ continue;
649
+ const aminoType = schema.messages[typeName]?.a;
650
+ const codec = txModule[typeName.slice(pkg.length + 1)];
651
+ if (!aminoType || !codec)
652
+ continue;
653
+ out[`/${typeName}`] = {
654
+ aminoType,
655
+ toAmino: (value) => {
656
+ const bytes = codec.encode(codec.fromPartial(fillNonNullable(typeName, value))).finish();
657
+ return render(typeName, bytes, false).value;
658
+ },
659
+ fromAmino: (value) => {
660
+ const bytes = encodeMessage(typeName, value ?? {});
661
+ return pruneAbsent(typeName, bytes, codec.decode(bytes));
662
+ },
663
+ };
664
+ }
665
+ return out;
666
+ }
667
+ /** Amino JSON ({type, value}) of any message the schema describes, rendered from its protobuf bytes. */
668
+ function renderAminoJson(typeUrl, bytes) {
669
+ return render(typeUrl.replace(/^\//, ""), bytes, false);
670
+ }