Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ A breaking change will get clearly marked in this log.
* The `--headers <json>` 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 <json>` 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)).
Expand Down
29 changes: 21 additions & 8 deletions docs/reference/contracts-client.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)`

Expand Down Expand Up @@ -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)`

Expand Down Expand Up @@ -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**

Expand All @@ -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)`

Expand Down
4 changes: 2 additions & 2 deletions src/bindings/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
148 changes: 110 additions & 38 deletions src/contract/event_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -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(
Expand All @@ -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;
}
Expand All @@ -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]]);
});
Expand All @@ -205,18 +234,31 @@ 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) =>
e.key.type === "scvSymbol" && e.key.value.toString() === name,
);
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: {
Expand All @@ -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<string, any> = 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<string, any> = 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)
Expand Down
23 changes: 18 additions & 5 deletions src/contract/spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading