diff --git a/CHANGELOG.md b/CHANGELOG.md index 474c0d7e0..e7a42cad4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,13 @@ A breaking change will get clearly marked in this log. * The `--headers ` flag of the `stellar-js generate` CLI and the `stellar-contract-bindings-typescript` plugin is deprecated in favor of `--rpc-header "Name: value"`. It still works, prints a warning, and no longer shows in `--help`. With both, `--rpc-header` wins on the same name ([#1897](https://github.com/stellar/js-stellar-sdk/pull/1897)). ### Fixed +* `Spec.parseEvent()` and the `parseEvent()` method of generated bindings no longer return the wrong event with fields dropped. Before, an earlier declaration with the same prefix topics could take an event that a later declaration fits. For example, the data `{ amount, memo }` parsed as `Mint { amount }` when `Mint` came before `MintMemo`, and the topics `[evt, from, to]` parsed as `Evt { from }` when `Evt` came before `EvtTo { from, to }`. Now a declaration whose topics and data have exactly the shape that soroban-sdk emits for it wins over a declaration that fits only loosely: + * Topics: one topic for each prefix topic and topic-list param. + * `map`: every key is a symbol that names a data param of the declaration. + * `vec`: the vec has exactly one element for each data param. + * Single value with no data params: the data is void. + + When no declaration fits exactly, the first declaration that fits loosely wins, as before, and the extra values are ignored. So older bindings can still read an event from a newer contract version that adds fields, and an event with an undeclared trailing topic, such as the SEP-11 asset topic of SAC events, still parses. If a later declaration declares that trailing topic, the later declaration wins, because the event bytes are the same for both. A `map` declaration no longer matches when a key is missing, except for an `Option`, `()` or `Val` param, because soroban-sdk leaves out only void values. Before, the data `{}` parsed as `Mint` with no `amount` ([#1900](https://github.com/stellar/js-stellar-sdk/pull/1900)). * The `--headers ` flag of the `stellar-js generate` CLI and the `stellar-contract-bindings-typescript` plugin rejects JSON that is not an object of valid header names and string values. Before, a string or an array became headers named `0`, `1` and so on, and an invalid name failed later with a Node error. The error no longer prints the JSON, since it may hold a secret ([#1897](https://github.com/stellar/js-stellar-sdk/pull/1897)). * `Spec.getFunc()` finds a function when a struct, union, enum or event with the same name comes before it in the spec. `Spec` also finds the type of a UDT value when another entry with the same name comes first. Before, `contract.Client` construction threw "is not a function", and so did `funcArgsToScVals()` and `funcResToNative()`. Encoding or decoding the UDT value threw "failed to parse udt". The error messages for a name that is missing or has no entry of the right kind stay the same ([#1871](https://github.com/stellar/js-stellar-sdk/pull/1871)). * `WebAuth.verifyChallengeTxThreshold()` no longer adds a stray `"` to the end of its "do not meet threshold" error message ([#1871](https://github.com/stellar/js-stellar-sdk/pull/1871)). diff --git a/docs/reference/contracts-client.md b/docs/reference/contracts-client.md index 381293606..9e216f6bf 100644 --- a/docs/reference/contracts-client.md +++ b/docs/reference/contracts-client.md @@ -1364,7 +1364,7 @@ a single topic filter row const topics = contractSpec.eventTopicFilter('transfer', { to: someAddress }); ``` -**Source:** [src/contract/spec.ts:1367](https://github.com/stellar/js-stellar-sdk/blob/main/src/contract/spec.ts#L1367) +**Source:** [src/contract/spec.ts:1380](https://github.com/stellar/js-stellar-sdk/blob/main/src/contract/spec.ts#L1380) ### `spec.findEntry(name)` @@ -1547,7 +1547,7 @@ the converted JSON schema - if the contract spec is invalid -**Source:** [src/contract/spec.ts:1391](https://github.com/stellar/js-stellar-sdk/blob/main/src/contract/spec.ts#L1391) +**Source:** [src/contract/spec.ts:1404](https://github.com/stellar/js-stellar-sdk/blob/main/src/contract/spec.ts#L1404) ### `spec.nativeToScVal(val, ty)` @@ -1597,11 +1597,24 @@ the parsed event (its name plus all decoded params — topic-list no event spec matches (e.g. when filtering a mixed stream of events from multiple contracts/specs) -Note that matching compares only the prefix topics and a minimum topic -count; if more than one event spec matches (in particular, events with -no prefix topics match on arity alone), the first declared spec whose -values decode successfully wins. A `vec` or `map` spec decodes only data -of that container type. +A spec matches when its prefix topics match and the event has at least +one topic for each prefix topic and topic-list param. If more than one +spec matches (in particular, events with no prefix topics match on arity +alone), the first declared exact fit whose values decode wins, and then +the first declared loose fit. A spec whose topics and data have exactly +the shape that soroban-sdk emits for it wins over a spec that fits only +loosely. The exact shape is one topic for each prefix topic and topic-list +param, and void data for a single-value spec with no data params, a vec +with one element for each data param, or a map whose keys are all symbols +that name a data param. A loose fit has more values, which are ignored: +trailing topics, data that is not void, extra vec elements, or extra map +keys. So older bindings can still read an event from a newer contract +version that adds fields, and an event with an undeclared trailing topic, +such as the SEP-11 asset topic of SAC events, still parses. But if a later +spec declares that trailing topic, the later spec wins, because the event +bytes are the same for both. A vec cannot have fewer elements than the +data params, and a map key can be missing only for a param of type +`Option`, `()` or `Val`. **Example** @@ -1612,7 +1625,7 @@ if (parsed) { } ``` -**Source:** [src/contract/spec.ts:1338](https://github.com/stellar/js-stellar-sdk/blob/main/src/contract/spec.ts#L1338) +**Source:** [src/contract/spec.ts:1351](https://github.com/stellar/js-stellar-sdk/blob/main/src/contract/spec.ts#L1351) ### `spec.scValStrToNative(scv, typeDef)` diff --git a/src/bindings/types.ts b/src/bindings/types.ts index a9bcc6674..0c702cf2c 100644 --- a/src/bindings/types.ts +++ b/src/bindings/types.ts @@ -405,8 +405,8 @@ ${members} 0, ); - // Map-format data entries may be absent from an emitted event's map, in - // which case parseEvent omits the key — so those fields are optional. + // Map-format data fields are optional. parseEvent omits a key only for an + // `Option`, `()` or `Val` param, so this is looser than needed. const dataIsMapFormat = event.dataFormat.value === ScSpecEventDataFormat.scSpecEventDataFormatMap.value; diff --git a/src/contract/event_spec.ts b/src/contract/event_spec.ts index 464f2c031..0bca9c018 100644 --- a/src/contract/event_spec.ts +++ b/src/contract/event_spec.ts @@ -123,17 +123,23 @@ function prefixTopicText(topic: ScVal): string | undefined { function matchesTopics( event: ScSpecEventV0, topics: ScVal[], + topicTexts: (string | undefined)[], ): ScSpecEventParamV0[] | undefined { const prefixTopics = event.prefixTopics; - const tlParams = topicListParams(event); - if (topics.length < prefixTopics.length + tlParams.length) { + if (topics.length < prefixTopics.length) { return undefined; } + // The prefix is checked first, so a declaration that does not match costs + // no param filtering. for (let i = 0; i < prefixTopics.length; i++) { - if (prefixTopicText(topics[i]) !== prefixTopics[i].toString()) { + if (topicTexts[i] !== prefixTopics[i].toString()) { return undefined; } } + const tlParams = topicListParams(event); + if (topics.length < prefixTopics.length + tlParams.length) { + return undefined; + } return tlParams; } @@ -147,11 +153,23 @@ function matchesTopics( * @param data - the event's data, as an `ScVal` or a base64 XDR string * @returns the parsed event, or `undefined` if no event spec matches * - * Matching compares only the prefix topics and a minimum topic count, so if - * more than one event spec matches (in particular, events with no prefix - * topics match on arity alone), the first declared spec whose values decode - * successfully wins. A `vec` or `map` spec decodes only data of that - * container type. + * A spec matches when its prefix topics match and the event has at least one + * topic for each prefix topic and topic-list param. If more than one spec + * matches (in particular, events with no prefix topics match on arity alone), + * the first declared exact fit whose values decode wins, and then the first + * declared loose fit. A spec whose topics and data have exactly the shape that + * soroban-sdk emits for it wins over a spec that fits only loosely. The exact + * shape is one topic for each prefix topic and topic-list param, and void data + * for a single-value spec with no data params, a vec with one element for each + * data param, or a map whose keys are all symbols that name a data param. A + * loose fit has more values, which are ignored: trailing topics, data that is + * not void, extra vec elements, or extra map keys. So older bindings can still + * read an event from a newer contract version that adds fields, and an event + * with an undeclared trailing topic, such as the SEP-11 asset topic of SAC + * events, still parses. But if a later spec declares that trailing topic, the + * later spec wins, because the event bytes are the same for both. A vec cannot + * have fewer elements than the data params, and a map key can be missing only + * for a param of type `Option`, `()` or `Val`. * @hidden */ export function parseEvent( @@ -172,19 +190,29 @@ export function parseEvent( } const specEvents = events(entries); + let loose: + | [ScSpecEventV0, ScSpecEventParamV0[], [ScSpecEventParamV0, ScVal][]][] + | undefined; + // Read once here, not once for each declaration. + const topicTexts = topicVals.map(prefixTopicText); for (const event of specEvents) { - const tlParams = matchesTopics(event, topicVals); + const tlParams = matchesTopics(event, topicVals, topicTexts); if (!tlParams) { continue; } // Checked before any decoding, so a wrong candidate costs no decode work. const dParams = dataParams(event); const dataPairs: [ScSpecEventParamV0, ScVal][] = []; + // soroban-sdk emits exactly this shape. Data with more values may come + // from a newer contract version, so it is a fallback. + let exact = true; switch (event.dataFormat.name) { case "scSpecEventDataFormatSingleValue": { const param = dParams[0]; if (param) { dataPairs.push([param, dataVal]); + } else if (dataVal.type !== "scvVoid") { + exact = false; } break; } @@ -196,6 +224,7 @@ export function parseEvent( if (vec.length < dParams.length) { continue; } + exact = vec.length === dParams.length; dParams.forEach((param, i) => { dataPairs.push([param, vec[i]]); }); @@ -205,9 +234,9 @@ export function parseEvent( if (dataVal.type !== "scvMap") { continue; } - // Missing keys are expected: a sparse map leaves out void fields. const map = dataVal.value ?? []; - dParams.forEach((param) => { + let missingRequired = false; + for (const param of dParams) { const name = param.name.toString(); const entry = map.find( (e) => @@ -215,8 +244,21 @@ export function parseEvent( ); if (entry) { dataPairs.push([param, entry.val]); + } else if ( + // A sparse map leaves out void values, so only a param that can + // hold void may be missing. + param.type.type !== "scSpecTypeOption" && + param.type.type !== "scSpecTypeVoid" && + param.type.type !== "scSpecTypeVal" + ) { + missingRequired = true; + break; } - }); + } + if (missingRequired) { + continue; + } + exact = dataPairs.length === map.length; break; } default: { @@ -225,39 +267,69 @@ export function parseEvent( throw new Error(`unknown event data format: ${unhandled}`); } } + // An undeclared trailing topic makes the fit loose, as extra data does. + if (topicVals.length !== event.prefixTopics.length + tlParams.length) { + exact = false; + } - // Topic matching is fuzzy (prefix symbols + a minimum topic count), so a - // candidate event may still turn out not to fit once its values are - // decoded — e.g. an unrelated contract's event sharing the same prefix. - // Treat any decode failure as a non-match and try the next candidate. - try { - const prefixLen = event.prefixTopics.length; - // Param names come from an untrusted, on-chain contract spec, so a - // param literally named "__proto__" must not be able to reach the - // object's prototype via normal property assignment. A null-prototype - // object stores it as a plain own property instead. - const dataOut: Record = Object.create(null); - tlParams.forEach((param, i) => { - const val = topicVals[prefixLen + i]; - dataOut[param.name.toString()] = spec.scValToNative(val, param.type); - }); - - dataPairs.forEach(([param, val]) => { - dataOut[param.name.toString()] = spec.scValToNative(val, param.type); - }); - - return { - name: event.name.toString(), - data: dataOut, - }; - } catch { - continue; + if (exact) { + const parsed = decodeEvent(spec, event, tlParams, topicVals, dataPairs); + if (parsed) { + return parsed; + } + } else { + // Decoded after the loop, so a collision costs no extra decode. + (loose ??= []).push([event, tlParams, dataPairs]); } } + // Declaration order decides among loose fits, as before. Ranking them by + // matched params would be a guess. + for (const [event, tlParams, dataPairs] of loose ?? []) { + const parsed = decodeEvent(spec, event, tlParams, topicVals, dataPairs); + if (parsed) { + return parsed; + } + } return undefined; } +// Topic matching is fuzzy (prefix symbols + a minimum topic count), so a +// candidate event may still turn out not to fit once its values are decoded — +// e.g. an unrelated contract's event sharing the same prefix. Any decode +// failure is a non-match, so the caller tries the next candidate. +function decodeEvent( + spec: Spec, + event: ScSpecEventV0, + tlParams: ScSpecEventParamV0[], + topicVals: ScVal[], + dataPairs: [ScSpecEventParamV0, ScVal][], +): ParsedEvent | undefined { + try { + const prefixLen = event.prefixTopics.length; + // Param names come from an untrusted, on-chain contract spec, so a param + // literally named "__proto__" must not be able to reach the object's + // prototype via normal property assignment. A null-prototype object + // stores it as a plain own property instead. + const dataOut: Record = Object.create(null); + tlParams.forEach((param, i) => { + const val = topicVals[prefixLen + i]; + dataOut[param.name.toString()] = spec.scValToNative(val, param.type); + }); + + dataPairs.forEach(([param, val]) => { + dataOut[param.name.toString()] = spec.scValToNative(val, param.type); + }); + + return { + name: event.name.toString(), + data: dataOut, + }; + } catch { + return undefined; + } +} + /** * Builds a `getEvents` topic filter (a single row of `Api.EventFilter.topics`) * for the named event: the event's prefix topics (base64-encoded `scvSymbol`s) diff --git a/src/contract/spec.ts b/src/contract/spec.ts index fdc2d1a67..49c8af409 100644 --- a/src/contract/spec.ts +++ b/src/contract/spec.ts @@ -1321,11 +1321,24 @@ export class Spec { * no event spec matches (e.g. when filtering a mixed stream of * events from multiple contracts/specs) * - * Note that matching compares only the prefix topics and a minimum topic - * count; if more than one event spec matches (in particular, events with - * no prefix topics match on arity alone), the first declared spec whose - * values decode successfully wins. A `vec` or `map` spec decodes only data - * of that container type. + * A spec matches when its prefix topics match and the event has at least + * one topic for each prefix topic and topic-list param. If more than one + * spec matches (in particular, events with no prefix topics match on arity + * alone), the first declared exact fit whose values decode wins, and then + * the first declared loose fit. A spec whose topics and data have exactly + * the shape that soroban-sdk emits for it wins over a spec that fits only + * loosely. The exact shape is one topic for each prefix topic and topic-list + * param, and void data for a single-value spec with no data params, a vec + * with one element for each data param, or a map whose keys are all symbols + * that name a data param. A loose fit has more values, which are ignored: + * trailing topics, data that is not void, extra vec elements, or extra map + * keys. So older bindings can still read an event from a newer contract + * version that adds fields, and an event with an undeclared trailing topic, + * such as the SEP-11 asset topic of SAC events, still parses. But if a later + * spec declares that trailing topic, the later spec wins, because the event + * bytes are the same for both. A vec cannot have fewer elements than the + * data params, and a map key can be missing only for a param of type + * `Option`, `()` or `Val`. * * @example * ```ts diff --git a/test/unit/spec/event_spec.test.ts b/test/unit/spec/event_spec.test.ts index c47ae975d..5a36a4e1b 100644 --- a/test/unit/spec/event_spec.test.ts +++ b/test/unit/spec/event_spec.test.ts @@ -393,7 +393,7 @@ describe("Spec events", () => { // vec data of entirely the wrong ScVal type expect(spec.parseEvent(swapTopics, xdr.ScVal.scvU32(1))).toBeUndefined(); - // map data with a non-symbol key does not throw; the param is omitted + // map data with a non-symbol key const mintTopics = [xdr.ScVal.scvSymbol("mint"), addr.toScVal()]; const weirdMap = xdr.ScVal.scvMap([ new xdr.ScMapEntry({ @@ -401,11 +401,7 @@ describe("Spec events", () => { val: xdr.ScVal.scvU32(7), }), ]); - const parsed = spec.parseEvent(mintTopics, weirdMap); - expect(parsed).toEqual({ - name: "mint", - data: { to: addr.toString() }, - }); + expect(spec.parseEvent(mintTopics, weirdMap)).toBeUndefined(); }); it("falls through to a later matching event when the first fails to decode", () => { @@ -578,6 +574,344 @@ describe("Spec events", () => { vecSpec.parseEvent(evtTopics, xdr.ScVal.scvVec(null)), ).toBeUndefined(); }); + + const optionU64 = xdr.ScSpecTypeDef.scSpecTypeOption( + new xdr.ScSpecTypeOption({ + valueType: xdr.ScSpecTypeDef.scSpecTypeU64(), + }), + ); + const entry = (key: string, val: xdr.ScVal) => + new xdr.ScMapEntry({ key: xdr.ScVal.scvSymbol(key), val }); + + describe("map keys", () => { + const keySpec = new Spec([ + declare("Mint", formats.scSpecEventDataFormatMap, [ + param("amount", i128Type, DATA), + param("to_muxed_id", optionU64, DATA), + ]), + declare("MintMemo", formats.scSpecEventDataFormatMap, [ + param("amount", i128Type, DATA), + param("memo", xdr.ScSpecTypeDef.scSpecTypeString(), DATA), + ]), + ]); + + it("skips a map declaration when a required key is missing", () => { + expect( + keySpec.parseEvent(evtTopics, xdr.ScVal.scvMap([])), + ).toBeUndefined(); + }); + + it("prefers a later declaration that lists every key", () => { + const data = xdr.ScVal.scvMap([ + entry("amount", amount), + entry("memo", xdr.ScVal.scvString("hi")), + ]); + expect(keySpec.parseEvent(evtTopics, data)).toEqual({ + name: "MintMemo", + data: { amount: 1000n, memo: "hi" }, + }); + }); + + it("falls back to the first declaration that fits when none lists every key", () => { + // For example, an event from a newer contract version. + const data = xdr.ScVal.scvMap([ + entry("amount", amount), + entry("extra", xdr.ScVal.scvU32(1)), + ]); + expect(keySpec.parseEvent(evtTopics, data)).toEqual({ + name: "Mint", + data: { amount: 1000n }, + }); + }); + + it("ignores a map key that names a topic-list param", () => { + const topicSpec = new Spec([ + declare("evt", formats.scSpecEventDataFormatMap, [ + param("to", u32Type, TOPIC), + param("a", u32Type, DATA), + ]), + ]); + const data = xdr.ScVal.scvMap([ + entry("a", xdr.ScVal.scvU32(1)), + entry("to", xdr.ScVal.scvU32(2)), + ]); + expect( + topicSpec.parseEvent([...evtTopics, xdr.ScVal.scvU32(9)], data), + ).toEqual({ name: "evt", data: { to: 9, a: 1 } }); + }); + + it("treats a key that is not a symbol as an undeclared key", () => { + const data = xdr.ScVal.scvMap([ + entry("amount", amount), + new xdr.ScMapEntry({ + key: xdr.ScVal.scvU32(1), + val: xdr.ScVal.scvU32(2), + }), + ]); + expect(keySpec.parseEvent(evtTopics, data)).toEqual({ + name: "Mint", + data: { amount: 1000n }, + }); + }); + + it("accepts a missing key for a param that can be void", () => { + // The sparse map drops every void value: None, () and a void Val. + const voidSpec = new Spec([ + declare("evt", formats.scSpecEventDataFormatMap, [ + param("a", u32Type, DATA), + param("o", optionU64, DATA), + param("v", xdr.ScSpecTypeDef.scSpecTypeVoid(), DATA), + param("x", xdr.ScSpecTypeDef.scSpecTypeVal(), DATA), + ]), + ]); + const data = xdr.ScVal.scvMap([entry("a", xdr.ScVal.scvU32(1))]); + expect(voidSpec.parseEvent(evtTopics, data)).toEqual({ + name: "evt", + data: { a: 1 }, + }); + }); + + it("accepts a void value for a param that can be void", () => { + // A dense map (sparse = false, or an older soroban-sdk) writes every + // key, with void for None, () and a void Val. + const voidSpec = new Spec([ + declare("evt", formats.scSpecEventDataFormatMap, [ + param("a", u32Type, DATA), + param("o", optionU64, DATA), + param("v", xdr.ScSpecTypeDef.scSpecTypeVoid(), DATA), + param("x", xdr.ScSpecTypeDef.scSpecTypeVal(), DATA), + ]), + ]); + const data = xdr.ScVal.scvMap([ + entry("a", xdr.ScVal.scvU32(1)), + entry("o", xdr.ScVal.scvVoid()), + entry("v", xdr.ScVal.scvVoid()), + entry("x", xdr.ScVal.scvVoid()), + ]); + expect(voidSpec.parseEvent(evtTopics, data)).toEqual({ + name: "evt", + data: { a: 1, o: null, v: null, x: null }, + }); + }); + }); + + it("prefers a later declaration over a single-value declaration with no data params for data that is not void", () => { + const pingSpec = new Spec([ + declare("Ping", formats.scSpecEventDataFormatSingleValue), + declare("PingWithInfo", formats.scSpecEventDataFormatMap, [ + param("info", u32Type, DATA), + ]), + ]); + const data = xdr.ScVal.scvMap([entry("info", xdr.ScVal.scvU32(5))]); + + expect(pingSpec.parseEvent(evtTopics, data)).toEqual({ + name: "PingWithInfo", + data: { info: 5 }, + }); + expect(pingSpec.parseEvent(evtTopics, xdr.ScVal.scvVoid())).toEqual({ + name: "Ping", + data: {}, + }); + + const pingOnly = new Spec([ + declare("Ping", formats.scSpecEventDataFormatSingleValue), + ]); + expect(pingOnly.parseEvent(evtTopics, data)).toEqual({ + name: "Ping", + data: {}, + }); + }); + + it("prefers a vec declaration with one element for each data param", () => { + const vecSpec = new Spec([ + declare("Evt", formats.scSpecEventDataFormatVec, [ + param("a", u32Type, DATA), + ]), + declare("Evt2", formats.scSpecEventDataFormatVec, [ + param("a", u32Type, DATA), + param("b", u32Type, DATA), + ]), + ]); + const vec = (...values: number[]) => + xdr.ScVal.scvVec(values.map((v) => xdr.ScVal.scvU32(v))); + + expect(vecSpec.parseEvent(evtTopics, vec(1))).toEqual({ + name: "Evt", + data: { a: 1 }, + }); + expect(vecSpec.parseEvent(evtTopics, vec(1, 2))).toEqual({ + name: "Evt2", + data: { a: 1, b: 2 }, + }); + // No declaration fits exactly, so the first one that fits wins. + expect(vecSpec.parseEvent(evtTopics, vec(1, 2, 3))).toEqual({ + name: "Evt", + data: { a: 1 }, + }); + }); + + it("tries the next declaration when a declaration fails to decode", () => { + // The UDT is not in the spec, so decoding a value of this type throws. + const missingUdt = xdr.ScSpecTypeDef.scSpecTypeUdt( + new xdr.ScSpecTypeUdt({ name: "Missing" }), + ); + const failSpec = new Spec([ + declare("BadLoose", formats.scSpecEventDataFormatMap, [ + param("a", missingUdt, DATA), + ]), + declare("GoodLoose", formats.scSpecEventDataFormatMap, [ + param("a", u32Type, DATA), + ]), + declare("BadExact", formats.scSpecEventDataFormatMap, [ + param("a", missingUdt, DATA), + param("b", u32Type, DATA), + ]), + ]); + const data = xdr.ScVal.scvMap([ + entry("a", xdr.ScVal.scvU32(1)), + entry("b", xdr.ScVal.scvU32(2)), + ]); + + expect(failSpec.parseEvent(evtTopics, data)).toEqual({ + name: "GoodLoose", + data: { a: 1 }, + }); + }); + }); + + describe("topic count", () => { + const declare = ( + name: string, + prefixTopics: string[], + params: xdr.ScSpecEventParamV0[], + dataFormat = xdr.ScSpecEventDataFormat.scSpecEventDataFormatSingleValue, + ): xdr.ScSpecEntry => + entryFor( + new xdr.ScSpecEventV0({ + doc: "", + lib: "", + name, + prefixTopics, + params, + dataFormat, + }), + ); + const to = Address.fromString( + "GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD", + ); + const amount = param("amount", u32Type, DATA); + const data = xdr.ScVal.scvU32(5); + + it("prefers a later declaration that declares every topic", () => { + const evt = declare( + "Evt", + ["evt"], + [param("from", addrType, TOPIC), amount], + ); + const evtTo = declare( + "EvtTo", + ["evt"], + [param("from", addrType, TOPIC), param("to", addrType, TOPIC), amount], + ); + const topics = [xdr.ScVal.scvSymbol("evt"), addr.toScVal(), to.toScVal()]; + const expected = { + name: "EvtTo", + data: { from: addr.toString(), to: to.toString(), amount: 5 }, + }; + + expect(new Spec([evt, evtTo]).parseEvent(topics, data)).toEqual(expected); + expect(new Spec([evtTo, evt]).parseEvent(topics, data)).toEqual(expected); + }); + + it("prefers a later declaration with a longer prefix", () => { + const spec = new Spec([ + declare("A", ["a"], [amount]), + declare("AB", ["a", "b"], [amount]), + ]); + const topics = [xdr.ScVal.scvSymbol("a"), xdr.ScVal.scvSymbol("b")]; + + expect(spec.parseEvent(topics, data)).toEqual({ + name: "AB", + data: { amount: 5 }, + }); + }); + + it("prefers a later declaration that declares a trailing topic", () => { + // Both declarations fit the same bytes. The declaration that declares + // the trailing topic wins, even when the contract emitted Transfer with + // an undeclared SAC asset topic. + const spec = new Spec([ + declare( + "Transfer", + ["transfer"], + [ + param("from", addrType, TOPIC), + param("to", addrType, TOPIC), + amount, + ], + ), + declare( + "TransferTagged", + ["transfer"], + [ + param("from", addrType, TOPIC), + param("to", addrType, TOPIC), + param("tag", xdr.ScSpecTypeDef.scSpecTypeVal(), TOPIC), + amount, + ], + ), + ]); + const topics = [ + xdr.ScVal.scvSymbol("transfer"), + addr.toScVal(), + to.toScVal(), + xdr.ScVal.scvString("native"), + ]; + + expect(spec.parseEvent(topics, data)).toEqual({ + name: "TransferTagged", + data: { + from: addr.toString(), + to: to.toString(), + tag: "native", + amount: 5, + }, + }); + }); + + it("uses declaration order when the topics fit one declaration and the data fits the other", () => { + const map = xdr.ScSpecEventDataFormat.scSpecEventDataFormatMap; + const spec = new Spec([ + declare( + "TopicsFit", + ["evt"], + [param("x", u32Type, TOPIC), param("a", u32Type, DATA)], + map, + ), + declare( + "DataFits", + ["evt"], + [param("a", u32Type, DATA), param("b", u32Type, DATA)], + map, + ), + ]); + const topics = [xdr.ScVal.scvSymbol("evt"), xdr.ScVal.scvU32(9)]; + const mapData = xdr.ScVal.scvMap([ + new xdr.ScMapEntry({ + key: xdr.ScVal.scvSymbol("a"), + val: xdr.ScVal.scvU32(1), + }), + new xdr.ScMapEntry({ + key: xdr.ScVal.scvSymbol("b"), + val: xdr.ScVal.scvU32(2), + }), + ]); + + expect(spec.parseEvent(topics, mapData)).toEqual({ + name: "TopicsFit", + data: { x: 9, a: 1 }, + }); + }); }); it("accepts base64 XDR strings for topics and data", () => {