Skip to content

feat(swift-sdk): typed DPNS contested-name browsing for voters - #4328

Merged
QuantumExplorer merged 2 commits into
v4.2-devfrom
feat/swift-sdk-dpns-contest-browse
Aug 7, 2026
Merged

QuantumExplorer merged 2 commits into
v4.2-devfrom
feat/swift-sdk-dpns-contest-browse

Conversation

@QuantumExplorer

@QuantumExplorer QuantumExplorer commented Aug 7, 2026 •

Copy link
Copy Markdown
Member

Why

The Swift SDK could already cast a masternode contested-resource vote (SDK.castContestedResourceVote), but it had no usable way to find something to vote on. A masternode operator browsing DPNS username contests was stuck between two unsuitable APIs:

  • ManagedPlatformWallet.fetchContestVoteState(identityId:label:) is identity-scoped — it answers "is MY pending name being contested" and returns nil for any label the given identity is not contending in.

  • dpnsGetContestedNonResolvedUsernames / dpnsGetContestedVoteState return [String: Any] bags, and they discard the tally the FFI already provides as an integer, re-emitting it as a debug description:

    // PlatformQueryExtensions.swift:1227
    contenderDict["votes"] = "ResourceVote { vote_choice: TowardsIdentity, strength: \(contender.vote_count) }"

    The C struct right there carries uint32_t vote_count.

The iOS wallet's voting screen needs the network-wide view. This adds it.

What

New Sources/SwiftDashSDK/Voting/:

API Purpose
SDK.dpnsActiveContests(limit:) Every open contest with contenders, tallies, end time — read directly off DashSDKContestedNamesList, so tallies stay integers
SDK.dpnsContestVoteState(normalizedLabel:limit:) One contest's full state incl. DPNSContestOutcome (.ongoing / .noWinner / .wonBy / .locked)
SDK.dpnsContestIsOpen(normalizedLabel:) Pre-flight before broadcasting
SDK.dpnsNormalizeLabel(_:) dash_sdk_dpns_normalize_username, plus a locallyNormalizedLabel mirror for callers with no live handle
DPNSVotePoll The fixed DPNS poll coordinates, shared by these reads and the existing write path

Models: DPNSContest, DPNSContender, DPNSContestVoteState, DPNSContestOutcome.

Notes

  • Purely additive. No Rust or FFI change, so no build_ios.sh / xcframework rebuild and no rev bump. Existing untyped wrappers are untouched (they have several SwiftExampleApp call sites).
  • Label normalization is load-bearing and documented on every entry point: Platform indexes vote polls under the homograph-safe form only, so addressing a poll with a raw label silently misses.
  • DPNSContender deliberately does not expose the contender's own spelling of the label. Platform returns it only inside the serialized domain document, which the FFI hands over as opaque hex; decoding needs the contract's document-type schema. Rather than ship an always-nil field, the type documents why it is absent.
  • dpnsContestVoteState returns nil rather than an empty state when Platform holds no contenders, so callers can't mistake "no poll" for "a live contest with zero votes".

Testing

Compiled as part of a clean dashpay build of the iOS wallet (ARCHS=arm64, iOS Simulator), which consumes this package locally and is the first consumer of all four new APIs. Runtime verification happens in the wallet PR's testnet smoke, where testnet's 90-minute contests make a full contest lifecycle observable in one sitting.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added Swift SDK support for browsing active DPNS contested-username polls.
    • Added contest models with vote totals, leading contenders, outcomes, and resolution status.
    • Added APIs to normalize labels, retrieve detailed vote states, and check whether contests are open.
    • Added support for identifying contests through normalized labels and poll index values.
    • Improved handling of unavailable or malformed contest data with clear results and errors.

Adds the read surface a masternode operator needs to browse and vote on
contested DPNS usernames, which the existing Swift API did not cover:

- `SDK.dpnsActiveContests(limit:)` — every open contest with contenders,
  tallies, and end time, read straight off the FFI's
  `DashSDKContestedNamesList`. The pre-existing
  `dpnsGetContestedNonResolvedUsernames` wrapper is unusable for this: it
  discards the `uint32_t vote_count` the FFI already provides and emits
  `"ResourceVote { … strength: N }"` as a string, forcing callers to parse a
  number back out of a debug description.
- `SDK.dpnsContestVoteState(normalizedLabel:limit:)` — one contest's
  contenders, abstain/lock tallies and resolution outcome, decoded into
  `DPNSContestVoteState` / `DPNSContestOutcome`. Returns `nil` (rather than an
  empty-looking live contest) when Platform holds no contenders for the label.
- `SDK.dpnsContestIsOpen(normalizedLabel:)` — pre-flight so a vote on a closed
  poll fails immediately instead of after a long broadcast retry.
- `SDK.dpnsNormalizeLabel(_:)` over `dash_sdk_dpns_normalize_username`, plus a
  `locallyNormalizedLabel` mirror for callers with no live handle (search
  filtering). Platform indexes vote polls under the homograph-normalized label
  only, so addressing a poll with a raw label silently misses.
- `DPNSVotePoll` — the fixed `(DPNS contract, "domain",
  "parentNameAndLabel", ["dash", label])` coordinates, shared by these reads
  and by the existing `castContestedResourceVote` write path.

Purely additive; no Rust or FFI change, so no xcframework rebuild.

`ManagedPlatformWallet.fetchContestVoteState(identityId:label:)` stays as-is —
it is identity-scoped ("is MY name contested") and returns nothing for a label
the identity is not contending in, so it cannot serve a voter browsing
contests.

Co-Authored-By: Claude Opus 5 <[email protected]>
@github-actions github-actions Bot added this to the v4.2.0 milestone Aug 7, 2026
@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 3fe9160f-b512-485a-9bb6-4bdd564553ff

📥 Commits

Reviewing files that changed from the base of the PR and between 60f14b3 and b23c690.

📒 Files selected for processing (3)
  • packages/swift-sdk/Sources/SwiftDashSDK/Voting/DPNSContest.swift
  • packages/swift-sdk/Sources/SwiftDashSDK/Voting/SDK+DPNSContests.swift
  • packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DPNSContestDecoderTests.swift
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/swift-sdk/Sources/SwiftDashSDK/Voting/DPNSContest.swift
  • packages/swift-sdk/Sources/SwiftDashSDK/Voting/SDK+DPNSContests.swift

📝 Walkthrough

Walkthrough

The Swift SDK adds typed DPNS contest models and FFI-backed APIs for label normalization, active contest listing, vote-state retrieval, outcome decoding, and open-contest checks.

Changes

DPNS contest browsing

Layer / File(s) Summary
Contest models and poll indexing
packages/swift-sdk/Sources/SwiftDashSDK/Voting/DPNSContest.swift
Defines DPNS poll constants and public models for contests, contenders, outcomes, and vote states. Derived properties expose identifiers, total votes, leading contenders, and resolution state.
Label normalization and active contest listing
packages/swift-sdk/Sources/SwiftDashSDK/Voting/SDK+DPNSContests.swift
Adds FFI-backed label normalization and lists active unresolved contests with vote tallies, resolution metadata, and normalized-label sorting.
Vote-state decoding and open checks
packages/swift-sdk/Sources/SwiftDashSDK/Voting/SDK+DPNSContests.swift, packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DPNSContestDecoderTests.swift
Retrieves and decodes contest vote state, handles absent or malformed data, maps contest outcomes and timestamps, reports whether a contest is open, and validates decoding and derived properties with hermetic tests.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant SDK
  participant DPNSVotePoll
  participant FFI
  participant ContestStateDecoder
  SDK->>DPNSVotePoll: construct normalized-label index values
  SDK->>FFI: query DPNS contest vote state
  FFI-->>SDK: return serialized vote-state data
  SDK->>ContestStateDecoder: decode tallies, outcome, and resolution time
  ContestStateDecoder-->>SDK: return DPNSContestVoteState
Loading

Suggested reviewers: shumkov, llbartekll, zocolini

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: typed Swift SDK support for browsing contested DPNS names before voting.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/swift-sdk-dpns-contest-browse

Comment @coderabbitai help to get the list of available commands.

@thepastaclaw

thepastaclaw commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

🕓 Ready for review — next in queue (commit b23c690)
Queue position: 1/1
ETA: start ~12:20 UTC · complete ~12:39 UTC (median 19m across 30 recent reviews; 2 slots)
Queued 10m ago · Last checked: 2026-08-07 12:20 UTC

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (2)
packages/swift-sdk/Sources/SwiftDashSDK/Voting/SDK+DPNSContests.swift (1)

35-49: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use 2-space indentation.

These lines use 4-space indentation. Reformat this file to the repository EditorConfig setting. As per coding guidelines, non-Rust files use 2-space indentation.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/swift-sdk/Sources/SwiftDashSDK/Voting/SDK`+DPNSContests.swift around
lines 35 - 49, Reformat the body of dpnsNormalizeLabel to use 2-space
indentation throughout, including its closure, conditionals, guard, and return
statements, without changing behavior.

Source: Coding guidelines

packages/swift-sdk/Sources/SwiftDashSDK/Voting/DPNSContest.swift (1)

27-29: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Apply the repository indentation rule.

  • packages/swift-sdk/Sources/SwiftDashSDK/Voting/DPNSContest.swift#L27-L29: use 2-space indentation.
  • packages/swift-sdk/Sources/SwiftDashSDK/Voting/SDK+DPNSContests.swift#L35-L49: use 2-space indentation.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/swift-sdk/Sources/SwiftDashSDK/Voting/DPNSContest.swift` around
lines 27 - 29, Apply the repository’s 2-space indentation rule to the
`indexValues` implementation in
packages/swift-sdk/Sources/SwiftDashSDK/Voting/DPNSContest.swift lines 27-29 and
the affected code in
packages/swift-sdk/Sources/SwiftDashSDK/Voting/SDK+DPNSContests.swift lines
35-49, without changing behavior.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/swift-sdk/Sources/SwiftDashSDK/Voting/DPNSContest.swift`:
- Around line 10-29: Replace DPNSVotePoll’s constants and indexValues in
DPNSContest.swift with the Rust-owned DPNS FFI operation, preserving Rust as the
source of protocol behavior. In SDK+DPNSContests.swift, remove
locallyNormalizedLabel, call the FFI operation for normalization/index
construction, and propagate normalization failures instead of applying Swift
fallback logic. Reindent both cited Swift files using two-space indentation:
packages/swift-sdk/Sources/SwiftDashSDK/Voting/DPNSContest.swift lines 10-29 and
packages/swift-sdk/Sources/SwiftDashSDK/Voting/SDK+DPNSContests.swift lines
35-66.

In `@packages/swift-sdk/Sources/SwiftDashSDK/Voting/SDK`+DPNSContests.swift:
- Around line 201-243: Add deterministic unit tests for decodeVoteState covering
ongoing, NoWinner, Locked, WonByIdentity, missing or malformed fields, resolved
timestamps, and NSNumber tally conversion, including the expected normalized
label and contender values. Exercise each winner_info representation and verify
ongoing states do not produce resolvedAt while valid terminal timestamps are
converted correctly.
- Around line 35-49: Update dpnsNormalizeLabel(_:) to stop calling
locallyNormalizedLabel(_:) on FFI errors or missing data; instead propagate the
FFI failure by making the method throwing and returning the appropriate error,
or use a Rust-owned fallback path. Preserve successful result conversion and
memory cleanup, and remove the Swift normalization fallback from this method.
- Around line 153-159: Update the DPNS contest resolution logic in isResolved to
return true for the .noWinner outcome, matching the Rust FFI mapping of
“NoWinner” to FinishedVoteOutcome.NoPreviousWinner. Add a regression test
verifying contests with .noWinner are treated as resolved and not open by
dpnsContestIsOpen.

---

Nitpick comments:
In `@packages/swift-sdk/Sources/SwiftDashSDK/Voting/DPNSContest.swift`:
- Around line 27-29: Apply the repository’s 2-space indentation rule to the
`indexValues` implementation in
packages/swift-sdk/Sources/SwiftDashSDK/Voting/DPNSContest.swift lines 27-29 and
the affected code in
packages/swift-sdk/Sources/SwiftDashSDK/Voting/SDK+DPNSContests.swift lines
35-49, without changing behavior.

In `@packages/swift-sdk/Sources/SwiftDashSDK/Voting/SDK`+DPNSContests.swift:
- Around line 35-49: Reformat the body of dpnsNormalizeLabel to use 2-space
indentation throughout, including its closure, conditionals, guard, and return
statements, without changing behavior.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 6b851ab8-6443-4892-ab5e-c4dff2ff3ac1

📥 Commits

Reviewing files that changed from the base of the PR and between 963f0d2 and 60f14b3.

📒 Files selected for processing (2)
  • packages/swift-sdk/Sources/SwiftDashSDK/Voting/DPNSContest.swift
  • packages/swift-sdk/Sources/SwiftDashSDK/Voting/SDK+DPNSContests.swift

Review follow-up on #4328.

`DPNSContestVoteState.isResolved` returned `false` for `.noWinner`, so
`dpnsContestIsOpen` reported a settled contest as still open. That is the one
thing the pre-flight exists to prevent: the caller would broadcast a
`MasternodeVote` into a poll that can no longer accept it and get back the long
opaque retry the check was added to avoid.

`Contenders.winner` is `Option<(winner_info, finished_at_block_info)>` and
drive-abci wraps every variant — `NoWinner` included — in a `FinishedVoteInfo`
(`rs-drive-abci/src/query/voting/contested_resource_vote_state/v0/mod.rs:197`,
mapping it to `FinishedVoteOutcome::NoPreviousWinner`). So the *presence* of
winner info, not its value, separates a live contest from a settled one.
`.noWinner` now reports resolved, and both the enum and `isResolved` document
why.

Also in this commit:

- Remove the `locallyNormalizedLabel` Swift fallback and make
  `dpnsNormalizeLabel(_:)` throw. Homograph normalization is protocol behavior
  owned by Rust; a second copy of the mapping in Swift would drift from
  `convert_to_homograph_safe_chars` and silently address a poll that does not
  exist. Callers with no handle now get an explicit failure rather than a
  plausible-looking substitute.
- Reindent the new files to the repo's two-space `.editorconfig` width.
- Add `DPNSContestDecoderTests` — 19 hermetic cases over the JSON→model
  boundary: every outcome branch (ongoing / NoWinner / Locked / WonByIdentity),
  unknown and malformed winner payloads, `resolvedAt` presence and the
  zero-timestamp case, missing fields, contenders without an id or tally, and
  `UInt32` tally conversion at the top of the range.

Co-Authored-By: Claude Opus 5 <[email protected]>
@QuantumExplorer
QuantumExplorer merged commit 96af88d into v4.2-dev Aug 7, 2026
16 checks passed
@QuantumExplorer
QuantumExplorer deleted the feat/swift-sdk-dpns-contest-browse branch August 7, 2026 12:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants