From dd045429fd5c798a93e9ad06870833a331545446 Mon Sep 17 00:00:00 2001 From: Iveta Date: Fri, 13 Nov 2026 10:10:56 -0500 Subject: [PATCH 1/4] fix(contract): skip event declarations that do not fit the data --- CHANGELOG.md | 6 ++ docs/reference/contracts-client.md | 14 ++-- src/contract/event_spec.ts | 30 ++++++-- src/contract/spec.ts | 8 +- test/unit/spec/event_spec.test.ts | 117 +++++++++++++++++++++++++++-- 5 files changed, 156 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c70a9185..957f10306 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,12 @@ A breaking change will get clearly marked in this log. * Updated the production `smol-toml` dependency from `^1.6.1` to `^1.9.1`. Version 1.9.0 fixes a slow `parse()` that a hostile `stellar.toml` can trigger ([GHSA-r4xh-jqrq-34v2](https://github.com/advisories/GHSA-r4xh-jqrq-34v2)). Some parse errors in a `StellarToml.Resolver.resolve()` rejection have new wording, for example `illegal leading zero` instead of `leading zeroes are not allowed` ([#1887](https://github.com/stellar/js-stellar-sdk/pull/1887)). ### 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 did not fit it. For example, the data `{ amount, memo }` parsed as `Mint { amount }` when `Mint` came before `MintMemo`. Now a declaration matches only data of the shape that soroban-sdk emits for it: + * `map`: every key is a data param of the declaration. A key can be missing only for an `Option`, `()` or `Val` param, because soroban-sdk leaves out void values. + * `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, `parseEvent()` returns `undefined`. This includes data from a newer contract version that has fields the spec does not declare. Before, such data parsed with the new fields dropped. * `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)). * `rpc.Server.getClaimableBalance()` rejects an ID that contains non-hex characters or more than 72 hex characters with a `TypeError`. Before, it passed the ID to the decoder, which threw an `XdrError`. Every hex ID of 64 to 72 characters works as before ([#1847](https://github.com/stellar/js-stellar-sdk/pull/1847)). diff --git a/docs/reference/contracts-client.md b/docs/reference/contracts-client.md index 381293606..c95ae248f 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:1371](https://github.com/stellar/js-stellar-sdk/blob/main/src/contract/spec.ts#L1371) ### `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:1395](https://github.com/stellar/js-stellar-sdk/blob/main/src/contract/spec.ts#L1395) ### `spec.nativeToScVal(val, ty)` @@ -1600,8 +1600,12 @@ the parsed event (its name plus all decoded params — topic-list 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. +values decode successfully wins. The data must also have a shape that +soroban-sdk emits for the spec. A single-value spec with no data params +takes only void data. A `vec` spec takes only a vec with one element for +each data param. A `map` spec takes only a map whose keys are all data +param names. A key can be missing only for a param of type `Option`, `()` +or `Val`. **Example** @@ -1612,7 +1616,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:1342](https://github.com/stellar/js-stellar-sdk/blob/main/src/contract/spec.ts#L1342) ### `spec.scValStrToNative(scv, typeDef)` diff --git a/src/contract/event_spec.ts b/src/contract/event_spec.ts index 464f2c031..7841ee850 100644 --- a/src/contract/event_spec.ts +++ b/src/contract/event_spec.ts @@ -150,8 +150,11 @@ function matchesTopics( * 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. + * successfully wins. The data must also have a shape that soroban-sdk emits + * for the spec. A single-value spec with no data params takes only void data. + * A `vec` spec takes only a vec with one element for each data param. A `map` + * spec takes only a map whose keys are all data param names. A key can be + * missing only for a param of type `Option`, `()` or `Val`. * @hidden */ export function parseEvent( @@ -185,6 +188,8 @@ export function parseEvent( const param = dParams[0]; if (param) { dataPairs.push([param, dataVal]); + } else if (dataVal.type !== "scvVoid") { + continue; } break; } @@ -193,7 +198,7 @@ export function parseEvent( continue; } const vec = dataVal.value ?? []; - if (vec.length < dParams.length) { + if (vec.length !== dParams.length) { continue; } dParams.forEach((param, i) => { @@ -205,9 +210,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 +220,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; } - }); + } + // soroban-sdk writes only declared keys, so each key must match a + // param. + if (missingRequired || dataPairs.length !== map.length) { + continue; + } break; } default: { diff --git a/src/contract/spec.ts b/src/contract/spec.ts index fdc2d1a67..232124821 100644 --- a/src/contract/spec.ts +++ b/src/contract/spec.ts @@ -1324,8 +1324,12 @@ export class Spec { * 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. + * values decode successfully wins. The data must also have a shape that + * soroban-sdk emits for the spec. A single-value spec with no data params + * takes only void data. A `vec` spec takes only a vec with one element for + * each data param. A `map` spec takes only a map whose keys are all data + * param names. A 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..090651c01 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,115 @@ 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("skips a map declaration when the map has an undeclared 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("skips a map declaration when a key is not a symbol", () => { + 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)).toBeUndefined(); + }); + + 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("skips a single-value declaration with no data params when the data 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: {}, + }); + }); + + it("skips a vec declaration when the vec length differs from its data params", () => { + 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 }, + }); + expect(vecSpec.parseEvent(evtTopics, vec(1, 2, 3))).toBeUndefined(); + }); }); it("accepts base64 XDR strings for topics and data", () => { From 31d6842b7fa1eee2304b65331f6e7b38129b6ce9 Mon Sep 17 00:00:00 2001 From: Iveta Date: Fri, 13 Nov 2026 10:49:15 -0500 Subject: [PATCH 2/4] fix(contract): state symbol map keys and pin event shape tests --- CHANGELOG.md | 4 +-- docs/reference/contracts-client.md | 6 ++-- src/contract/event_spec.ts | 5 ++-- src/contract/spec.ts | 6 ++-- test/unit/spec/event_spec.test.ts | 48 ++++++++++++++++++++++++++++++ 5 files changed, 59 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 957f10306..e58ce95fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,11 +16,11 @@ A breaking change will get clearly marked in this log. ### 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 did not fit it. For example, the data `{ amount, memo }` parsed as `Mint { amount }` when `Mint` came before `MintMemo`. Now a declaration matches only data of the shape that soroban-sdk emits for it: - * `map`: every key is a data param of the declaration. A key can be missing only for an `Option`, `()` or `Val` param, because soroban-sdk leaves out void values. + * `map`: every key is a symbol that names a data param of the declaration. A key can be missing only for an `Option`, `()` or `Val` param, because soroban-sdk leaves out void values. * `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, `parseEvent()` returns `undefined`. This includes data from a newer contract version that has fields the spec does not declare. Before, such data parsed with the new fields dropped. + When no declaration fits, `parseEvent()` returns `undefined`. This includes data from a newer contract version that has fields the spec does not declare. Before, such data parsed with the new fields dropped ([#1900](https://github.com/stellar/js-stellar-sdk/pull/1900)). * `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)). * `rpc.Server.getClaimableBalance()` rejects an ID that contains non-hex characters or more than 72 hex characters with a `TypeError`. Before, it passed the ID to the decoder, which threw an `XdrError`. Every hex ID of 64 to 72 characters works as before ([#1847](https://github.com/stellar/js-stellar-sdk/pull/1847)). diff --git a/docs/reference/contracts-client.md b/docs/reference/contracts-client.md index c95ae248f..c2b196531 100644 --- a/docs/reference/contracts-client.md +++ b/docs/reference/contracts-client.md @@ -1603,9 +1603,9 @@ no prefix topics match on arity alone), the first declared spec whose values decode successfully wins. The data must also have a shape that soroban-sdk emits for the spec. A single-value spec with no data params takes only void data. A `vec` spec takes only a vec with one element for -each data param. A `map` spec takes only a map whose keys are all data -param names. A key can be missing only for a param of type `Option`, `()` -or `Val`. +each data param. A `map` spec takes only a map whose keys are all symbols +that name a data param. A key can be missing only for a param of type +`Option`, `()` or `Val`. **Example** diff --git a/src/contract/event_spec.ts b/src/contract/event_spec.ts index 7841ee850..eacbe175f 100644 --- a/src/contract/event_spec.ts +++ b/src/contract/event_spec.ts @@ -153,8 +153,8 @@ function matchesTopics( * successfully wins. The data must also have a shape that soroban-sdk emits * for the spec. A single-value spec with no data params takes only void data. * A `vec` spec takes only a vec with one element for each data param. A `map` - * spec takes only a map whose keys are all data param names. A key can be - * missing only for a param of type `Option`, `()` or `Val`. + * spec takes only a map whose keys are all symbols that name a data param. A + * key can be missing only for a param of type `Option`, `()` or `Val`. * @hidden */ export function parseEvent( @@ -228,6 +228,7 @@ export function parseEvent( param.type.type !== "scSpecTypeVal" ) { missingRequired = true; + break; } } // soroban-sdk writes only declared keys, so each key must match a diff --git a/src/contract/spec.ts b/src/contract/spec.ts index 232124821..d833636e8 100644 --- a/src/contract/spec.ts +++ b/src/contract/spec.ts @@ -1327,9 +1327,9 @@ export class Spec { * values decode successfully wins. The data must also have a shape that * soroban-sdk emits for the spec. A single-value spec with no data params * takes only void data. A `vec` spec takes only a vec with one element for - * each data param. A `map` spec takes only a map whose keys are all data - * param names. A key can be missing only for a param of type `Option`, `()` - * or `Val`. + * each data param. A `map` spec takes only a map whose keys are all symbols + * that name a data param. A 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 090651c01..c7bd08f10 100644 --- a/test/unit/spec/event_spec.test.ts +++ b/test/unit/spec/event_spec.test.ts @@ -612,6 +612,31 @@ describe("Spec events", () => { }); }); + it("returns undefined when no declaration 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)).toBeUndefined(); + }); + + it("does not accept a topic-list param name as a map key", () => { + 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), + ).toBeUndefined(); + }); + it("skips a map declaration when a key is not a symbol", () => { const data = xdr.ScVal.scvMap([ entry("amount", amount), @@ -639,6 +664,29 @@ describe("Spec events", () => { 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("skips a single-value declaration with no data params when the data is not void", () => { From e3873330635bf41dcc083fc4222595b838e522fd Mon Sep 17 00:00:00 2001 From: Iveta Date: Fri, 13 Nov 2026 15:43:36 -0500 Subject: [PATCH 3/4] fix(contract): keep loose event matches as a fallback --- CHANGELOG.md | 6 +- docs/reference/contracts-client.md | 22 +++--- src/contract/event_spec.ts | 108 +++++++++++++++++++---------- src/contract/spec.ts | 16 +++-- test/unit/spec/event_spec.test.ts | 66 +++++++++++++++--- 5 files changed, 154 insertions(+), 64 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e58ce95fa..1a10137e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,12 +15,12 @@ A breaking change will get clearly marked in this log. * Updated the production `smol-toml` dependency from `^1.6.1` to `^1.9.1`. Version 1.9.0 fixes a slow `parse()` that a hostile `stellar.toml` can trigger ([GHSA-r4xh-jqrq-34v2](https://github.com/advisories/GHSA-r4xh-jqrq-34v2)). Some parse errors in a `StellarToml.Resolver.resolve()` rejection have new wording, for example `illegal leading zero` instead of `leading zeroes are not allowed` ([#1887](https://github.com/stellar/js-stellar-sdk/pull/1887)). ### 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 did not fit it. For example, the data `{ amount, memo }` parsed as `Mint { amount }` when `Mint` came before `MintMemo`. Now a declaration matches only data of the shape that soroban-sdk emits for it: - * `map`: every key is a symbol that names a data param of the declaration. A key can be missing only for an `Option`, `()` or `Val` param, because soroban-sdk leaves out void values. +* `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`. Now a declaration whose data has exactly the shape that soroban-sdk emits for it wins over a declaration that fits only loosely: + * `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, `parseEvent()` returns `undefined`. This includes data from a newer contract version that has fields the spec does not declare. Before, such data parsed with the new fields dropped ([#1900](https://github.com/stellar/js-stellar-sdk/pull/1900)). + 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. 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)). * `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)). * `rpc.Server.getClaimableBalance()` rejects an ID that contains non-hex characters or more than 72 hex characters with a `TypeError`. Before, it passed the ID to the decoder, which threw an `XdrError`. Every hex ID of 64 to 72 characters works as before ([#1847](https://github.com/stellar/js-stellar-sdk/pull/1847)). diff --git a/docs/reference/contracts-client.md b/docs/reference/contracts-client.md index c2b196531..343f0d0e5 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:1371](https://github.com/stellar/js-stellar-sdk/blob/main/src/contract/spec.ts#L1371) +**Source:** [src/contract/spec.ts:1375](https://github.com/stellar/js-stellar-sdk/blob/main/src/contract/spec.ts#L1375) ### `spec.findEntry(name)` @@ -1547,7 +1547,7 @@ the converted JSON schema - if the contract spec is invalid -**Source:** [src/contract/spec.ts:1395](https://github.com/stellar/js-stellar-sdk/blob/main/src/contract/spec.ts#L1395) +**Source:** [src/contract/spec.ts:1399](https://github.com/stellar/js-stellar-sdk/blob/main/src/contract/spec.ts#L1399) ### `spec.nativeToScVal(val, ty)` @@ -1600,12 +1600,16 @@ the parsed event (its name plus all decoded params — topic-list 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. The data must also have a shape that -soroban-sdk emits for the spec. A single-value spec with no data params -takes only void data. A `vec` spec takes only a vec with one element for -each data param. A `map` spec takes only a map whose keys are all symbols -that name a data param. A key can be missing only for a param of type -`Option`, `()` or `Val`. +values decode successfully wins. A spec whose data has exactly the shape +that soroban-sdk emits for it wins over a spec that fits only loosely. +The exact shape is 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: 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. 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** @@ -1616,7 +1620,7 @@ if (parsed) { } ``` -**Source:** [src/contract/spec.ts:1342](https://github.com/stellar/js-stellar-sdk/blob/main/src/contract/spec.ts#L1342) +**Source:** [src/contract/spec.ts:1346](https://github.com/stellar/js-stellar-sdk/blob/main/src/contract/spec.ts#L1346) ### `spec.scValStrToNative(scv, typeDef)` diff --git a/src/contract/event_spec.ts b/src/contract/event_spec.ts index eacbe175f..f6dceee3a 100644 --- a/src/contract/event_spec.ts +++ b/src/contract/event_spec.ts @@ -150,11 +150,15 @@ function matchesTopics( * 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. The data must also have a shape that soroban-sdk emits - * for the spec. A single-value spec with no data params takes only void data. - * A `vec` spec takes only a vec with one element for each data param. A `map` - * spec takes only a map whose keys are all symbols that name a data param. A - * key can be missing only for a param of type `Option`, `()` or `Val`. + * successfully wins. A spec whose data has exactly the shape that soroban-sdk + * emits for it wins over a spec that fits only loosely. The exact shape is + * 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: 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. 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( @@ -175,6 +179,9 @@ export function parseEvent( } const specEvents = events(entries); + let loose: + | [ScSpecEventV0, ScSpecEventParamV0[], [ScSpecEventParamV0, ScVal][]][] + | undefined; for (const event of specEvents) { const tlParams = matchesTopics(event, topicVals); if (!tlParams) { @@ -183,13 +190,16 @@ export function parseEvent( // 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") { - continue; + exact = false; } break; } @@ -198,9 +208,10 @@ export function parseEvent( continue; } const vec = dataVal.value ?? []; - if (vec.length !== dParams.length) { + if (vec.length < dParams.length) { continue; } + exact = vec.length === dParams.length; dParams.forEach((param, i) => { dataPairs.push([param, vec[i]]); }); @@ -231,11 +242,10 @@ export function parseEvent( break; } } - // soroban-sdk writes only declared keys, so each key must match a - // param. - if (missingRequired || dataPairs.length !== map.length) { + if (missingRequired) { continue; } + exact = dataPairs.length === map.length; break; } default: { @@ -245,38 +255,64 @@ export function parseEvent( } } - // 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 d833636e8..ed29e0377 100644 --- a/src/contract/spec.ts +++ b/src/contract/spec.ts @@ -1324,12 +1324,16 @@ export class Spec { * 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. The data must also have a shape that - * soroban-sdk emits for the spec. A single-value spec with no data params - * takes only void data. A `vec` spec takes only a vec with one element for - * each data param. A `map` spec takes only a map whose keys are all symbols - * that name a data param. A key can be missing only for a param of type - * `Option`, `()` or `Val`. + * values decode successfully wins. A spec whose data has exactly the shape + * that soroban-sdk emits for it wins over a spec that fits only loosely. + * The exact shape is 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: 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. 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 c7bd08f10..06038091a 100644 --- a/test/unit/spec/event_spec.test.ts +++ b/test/unit/spec/event_spec.test.ts @@ -601,7 +601,7 @@ describe("Spec events", () => { ).toBeUndefined(); }); - it("skips a map declaration when the map has an undeclared key", () => { + it("prefers a later declaration that lists every key", () => { const data = xdr.ScVal.scvMap([ entry("amount", amount), entry("memo", xdr.ScVal.scvString("hi")), @@ -612,16 +612,19 @@ describe("Spec events", () => { }); }); - it("returns undefined when no declaration lists every key", () => { + 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)).toBeUndefined(); + expect(keySpec.parseEvent(evtTopics, data)).toEqual({ + name: "Mint", + data: { amount: 1000n }, + }); }); - it("does not accept a topic-list param name as a map key", () => { + it("ignores a map key that names a topic-list param", () => { const topicSpec = new Spec([ declare("evt", formats.scSpecEventDataFormatMap, [ param("to", u32Type, TOPIC), @@ -634,10 +637,10 @@ describe("Spec events", () => { ]); expect( topicSpec.parseEvent([...evtTopics, xdr.ScVal.scvU32(9)], data), - ).toBeUndefined(); + ).toEqual({ name: "evt", data: { to: 9, a: 1 } }); }); - it("skips a map declaration when a key is not a symbol", () => { + it("treats a key that is not a symbol as an undeclared key", () => { const data = xdr.ScVal.scvMap([ entry("amount", amount), new xdr.ScMapEntry({ @@ -645,7 +648,10 @@ describe("Spec events", () => { val: xdr.ScVal.scvU32(2), }), ]); - expect(keySpec.parseEvent(evtTopics, data)).toBeUndefined(); + expect(keySpec.parseEvent(evtTopics, data)).toEqual({ + name: "Mint", + data: { amount: 1000n }, + }); }); it("accepts a missing key for a param that can be void", () => { @@ -689,7 +695,7 @@ describe("Spec events", () => { }); }); - it("skips a single-value declaration with no data params when the data is not void", () => { + 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, [ @@ -706,9 +712,17 @@ describe("Spec events", () => { name: "Ping", data: {}, }); + + const pingOnly = new Spec([ + declare("Ping", formats.scSpecEventDataFormatSingleValue), + ]); + expect(pingOnly.parseEvent(evtTopics, data)).toEqual({ + name: "Ping", + data: {}, + }); }); - it("skips a vec declaration when the vec length differs from its data params", () => { + it("prefers a vec declaration with one element for each data param", () => { const vecSpec = new Spec([ declare("Evt", formats.scSpecEventDataFormatVec, [ param("a", u32Type, DATA), @@ -729,7 +743,39 @@ describe("Spec events", () => { name: "Evt2", data: { a: 1, b: 2 }, }); - expect(vecSpec.parseEvent(evtTopics, vec(1, 2, 3))).toBeUndefined(); + // 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 }, + }); }); }); From eba0a16ba9e8fc5020aa134f5db111e0f6123975 Mon Sep 17 00:00:00 2001 From: Iveta Date: Tue, 24 Nov 2026 10:06:38 -0500 Subject: [PATCH 4/4] fix(contract): count topics in the exact event match --- CHANGELOG.md | 5 +- docs/reference/contracts-client.md | 37 ++++---- src/bindings/types.ts | 4 +- src/contract/event_spec.ts | 43 ++++++--- src/contract/spec.ts | 31 ++++--- test/unit/spec/event_spec.test.ts | 135 +++++++++++++++++++++++++++++ 6 files changed, 209 insertions(+), 46 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a10137e7..23c81bae0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,12 +15,13 @@ A breaking change will get clearly marked in this log. * Updated the production `smol-toml` dependency from `^1.6.1` to `^1.9.1`. Version 1.9.0 fixes a slow `parse()` that a hostile `stellar.toml` can trigger ([GHSA-r4xh-jqrq-34v2](https://github.com/advisories/GHSA-r4xh-jqrq-34v2)). Some parse errors in a `StellarToml.Resolver.resolve()` rejection have new wording, for example `illegal leading zero` instead of `leading zeroes are not allowed` ([#1887](https://github.com/stellar/js-stellar-sdk/pull/1887)). ### 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`. Now a declaration whose data has exactly the shape that soroban-sdk emits for it wins over a declaration that fits only loosely: +* `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. 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)). + 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)). * `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)). * `rpc.Server.getClaimableBalance()` rejects an ID that contains non-hex characters or more than 72 hex characters with a `TypeError`. Before, it passed the ID to the decoder, which threw an `XdrError`. Every hex ID of 64 to 72 characters works as before ([#1847](https://github.com/stellar/js-stellar-sdk/pull/1847)). diff --git a/docs/reference/contracts-client.md b/docs/reference/contracts-client.md index 343f0d0e5..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:1375](https://github.com/stellar/js-stellar-sdk/blob/main/src/contract/spec.ts#L1375) +**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:1399](https://github.com/stellar/js-stellar-sdk/blob/main/src/contract/spec.ts#L1399) +**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,19 +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 spec whose data has exactly the shape -that soroban-sdk emits for it wins over a spec that fits only loosely. -The exact shape is 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: 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. 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`. +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** @@ -1620,7 +1625,7 @@ if (parsed) { } ``` -**Source:** [src/contract/spec.ts:1346](https://github.com/stellar/js-stellar-sdk/blob/main/src/contract/spec.ts#L1346) +**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 f6dceee3a..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,16 +153,21 @@ 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 spec whose data has exactly the shape that soroban-sdk - * emits for it wins over a spec that fits only loosely. The exact shape is - * 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: data that is + * 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. A vec cannot + * 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 @@ -182,8 +193,10 @@ export function parseEvent( 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; } @@ -254,6 +267,10 @@ 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; + } if (exact) { const parsed = decodeEvent(spec, event, tlParams, topicVals, dataPairs); diff --git a/src/contract/spec.ts b/src/contract/spec.ts index ed29e0377..49c8af409 100644 --- a/src/contract/spec.ts +++ b/src/contract/spec.ts @@ -1321,19 +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 spec whose data has exactly the shape - * that soroban-sdk emits for it wins over a spec that fits only loosely. - * The exact shape is 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: 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. 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`. + * 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 06038091a..5a36a4e1b 100644 --- a/test/unit/spec/event_spec.test.ts +++ b/test/unit/spec/event_spec.test.ts @@ -779,6 +779,141 @@ describe("Spec events", () => { }); }); + 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", () => { const event = new xdr.ScSpecEventV0({ doc: "",