From b8cdb7f6a42be8c5485b2840d98f73b7d45ff6e4 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Fri, 13 Nov 2026 06:40:52 +0700 Subject: [PATCH 1/3] feat(sdk): multiple choice decision proposals in rs-sdk, wasm-sdk and js-evo-sdk Multiple choice proposals (PV15) had no client helpers: an app assembled the proposal, its choices and the vote from generic document and contested vote calls, and had to know that a vote for a choice carries the choice's document id where a contest among identities carries an identity id. rs-dpp names the contest a proposal's choices run in from the proposal's id alone and maps a multiple choice answer (a choice, abstain, none of the choices) to the resource vote the contest takes. rs-sdk builds a proposal, its edit and a choice, gives the proposal's processing fee and the fund a choice pays, lists proposals, and reads the vote, the kept choice and a masternode's answer. wasm-sdk and js-evo-sdk (sdk.decisionProposals.multipleChoice) bind them. The contested vote state paging loop of get_contested_dpns_vote_state and the contender count of prefunded_voting_balance_to_join are now shared functions taking the poll; both keep their behaviour. Co-Authored-By: Claude Fable 5.2 --- docs/protocol/decision-proposals.md | 23 +- packages/js-evo-sdk/README.md | 59 + .../src/decision-proposals/facade.ts | 7 + .../multiple-choice-facade.ts | 131 ++ packages/js-evo-sdk/src/sdk.ts | 1 + .../facades/multiple-choice-proposals.spec.ts | 169 +++ packages/rs-dpp/src/decision_proposal/mod.rs | 5 + .../src/decision_proposal/multiple_choice.rs | 275 ++++ .../rs-sdk/src/platform/decision_proposals.rs | 85 +- .../decision_proposals/multiple_choice.rs | 1257 +++++++++++++++++ .../src/platform/documents/contest_fund.rs | 17 +- .../platform/documents/contest_vote_state.rs | 76 + packages/rs-sdk/src/platform/documents/mod.rs | 1 + .../dpns_usernames/contested_queries.rs | 46 +- packages/wasm-sdk/src/decision_proposals.rs | 5 + .../src/decision_proposals/multiple_choice.rs | 639 +++++++++ .../wasm-sdk/src/queries/voting/yes_no.rs | 4 +- .../unit/multiple-choice-proposals.spec.ts | 174 +++ 18 files changed, 2901 insertions(+), 73 deletions(-) create mode 100644 packages/js-evo-sdk/src/decision-proposals/multiple-choice-facade.ts create mode 100644 packages/js-evo-sdk/tests/unit/facades/multiple-choice-proposals.spec.ts create mode 100644 packages/rs-dpp/src/decision_proposal/multiple_choice.rs create mode 100644 packages/rs-sdk/src/platform/decision_proposals/multiple_choice.rs create mode 100644 packages/rs-sdk/src/platform/documents/contest_vote_state.rs create mode 100644 packages/wasm-sdk/src/decision_proposals/multiple_choice.rs create mode 100644 packages/wasm-sdk/tests/unit/multiple-choice-proposals.spec.ts diff --git a/docs/protocol/decision-proposals.md b/docs/protocol/decision-proposals.md index 7918a3e0b60..9cc64feb53a 100644 --- a/docs/protocol/decision-proposals.md +++ b/docs/protocol/decision-proposals.md @@ -406,5 +406,24 @@ A multiple choice proposal and its choices are ordinary documents and an ordinary contest: the SDKs' document create builds both (a `choice` create is given its contest fund like any contested create), and their contested resource queries and masternode vote read and answer the vote, with a choice's document -id wherever they name a contender by an identity id. They have no helpers of -their own yet. +id wherever they name a contender by an identity id. + +The Rust SDK (`dash_sdk::platform::decision_proposals::multiple_choice`) and the +JavaScript SDKs (`sdk.decisionProposals.multipleChoice` in `@dashevo/evo-sdk`, +the `*MultipleChoiceProposal*` methods of `@dashevo/wasm-sdk`) have helpers over +those: + +- build a proposal, its edit and a choice as documents to create or replace; +- give the proposal's processing fee and the fund a choice entered now pays; +- list proposals by owner and by creation time; +- read the vote by the proposal's id: every choice with its tally while it + runs, the result with every choice's final tally afterwards, and the choice + that was kept; +- build a masternode's vote from a choice's document id, abstain, or none of + the choices (a lock), and read the answer a masternode gave. + +The contest a proposal's choices run in is named from the proposal's id alone +(`dpp::decision_proposal::multiple_choice::multiple_choice_proposal_vote_poll`). +The helpers write what they are given: which descriptions, texts and choices +Platform takes is checked by the contract, on chain. The mobile SDKs have no +multiple choice helpers yet. diff --git a/packages/js-evo-sdk/README.md b/packages/js-evo-sdk/README.md index 3eb85e86b09..0660fbd9fd4 100644 --- a/packages/js-evo-sdk/README.md +++ b/packages/js-evo-sdk/README.md @@ -148,6 +148,7 @@ The SDK organises its API into domain-specific facades, each accessible as a pro | [`sdk.encryptedFor`](src/encrypted-for/facade.ts) | Encrypt and decrypt the byte properties a document type declares `encryptedFor`, for any contract | | [`sdk.moderationCharters`](src/moderation-charters/facade.ts) | Read a contract's seated charter, its team, proposals and join requests; build join and resignation requests | | [`sdk.decisionProposals`](src/decision-proposals/facade.ts) | Build, edit, list and read decision proposals; read their polls and vote on them as a masternode | +| [`sdk.decisionProposals.multipleChoice`](src/decision-proposals/multiple-choice-facade.ts) | Build, edit, list and read multiple choice proposals and their choices; read the vote among the choices and vote in it as a masternode | A `wallet` namespace is also exported with utilities for BIP39 mnemonic generation and validation, BIP44/DIP9/DIP13 key derivation (path helpers included), extended-key conversion (`xprvToXpub`, `deriveChildPublicKey`), key-pair generation and import (`generateKeyPair`, `keyPairFromWif`, `keyPairFromHex`), public-key-to-address conversion, address validation, message signing, and Dashpay contact-key derivation. See [`src/wallet/functions.ts`](src/wallet/functions.ts) for the full list. @@ -579,6 +580,64 @@ const answer = await sdk.decisionProposals.masternodeVote(proTxHash, proposal.id `sdk.voting.masternodeVote` also answers a yes/no poll as `sdk.voting.votePollsByEndDate` lists it, with `voteChoice: 'yes' | 'no' | 'abstain'`. +### Multiple choice proposals + +A question with more than two answers is a `multipleChoiceProposal` document of the same contract, and each answer is a `choice` document. The choices contend in a masternode vote that the first choice opens, and the one with the most votes is kept. `sdk.decisionProposals.multipleChoice` builds both for `sdk.documents`, and reads and answers the vote by the proposal's id. A choice is named by its document id, in a vote and in the vote's state: + +```ts +const multipleChoice = sdk.decisionProposals.multipleChoice; + +// Described by a document of an elected-moderation contract, at a url, or both. +// The owner pays the processing fee on top of the fees; the create does not state it. +const fee = await multipleChoice.processingFee(); // 0.2 Dash, in credits +const draft = await multipleChoice.build({ + ownerId: identity.id, + title: 'Which block size?', + descriptionDocument: { id: postId, contractId: forumContractId, documentType: 'post' }, + url: 'https://forum.dash.org/t/block-size', + open: true, // anyone may enter choices; false leaves them to the owner +}); +const proposal = await sdk.documents.create({ document: draft, identityKey, signer }); + +// The title, url and description document can be edited for two hours; `open` never changes +const edited = await multipleChoice.buildEdit(proposal, { title: 'Which block size, then?' }); +await sdk.documents.replace({ document: edited, identityKey, signer }); + +// A choice pays the contest fund, which the create states itself +const fund = await multipleChoice.choiceFund(proposal.id); // 0.1 Dash until the vote holds 250 choices +const choiceDraft = await multipleChoice.buildChoice({ + ownerId: identity.id, + proposalId: proposal.id, + title: 'Double it', + description: 'Twice the size it is today.', +}); +const choice = await sdk.documents.create({ document: choiceDraft, identityKey, signer }); + +// An identity's proposals; every proposal, newest first +const mine = await multipleChoice.byOwner({ ownerId: identity.id }); +const latest = await multipleChoice.byCreatedAt({ limit: 10 }); + +// The vote: every choice with its tally while it runs, its result once it ended +const vote = await multipleChoice.voteState(proposal.id); +for (const [choiceId, { choice: document, voteTally }] of vote.choices) { + console.log(choiceId, document?.properties.title, voteTally); +} +if (vote.result) console.log(vote.result.keptChoiceId?.toBase58()); +const kept = await multipleChoice.keptChoice(proposal.id); + +// A masternode answers with a choice's document id, 'abstain' or 'noneOfTheChoices' +await multipleChoice.vote({ + masternodeProTxHash: proTxHash, + proposalId: proposal.id, + voteChoice: { choiceId: choice.id }, + votingKey, + signer: votingSigner, +}); +const given = await multipleChoice.masternodeVote(proTxHash, proposal.id); +``` + +`multipleChoice.votePoll(proposal.id)` gives the vote as a vote poll for `sdk.voting` and the contested resource queries. + ## Immutable properties (`immutable`) From protocol version 14 a mutable document type can freeze some of its top-level properties with the doctype-level `immutable` list, while the rest of the document stays replaceable. An entry naming a property freezes it at creation. An entry `{ property, when }` freezes it for any replace its condition holds for: the condition takes the grammar of a `propertyConstraints` rule, is judged on the document the replace writes (whose `$updatedAt` is the replace's block time), and reads the stored document through `$old.` paths. diff --git a/packages/js-evo-sdk/src/decision-proposals/facade.ts b/packages/js-evo-sdk/src/decision-proposals/facade.ts index b614a51ce00..efbbfc06850 100644 --- a/packages/js-evo-sdk/src/decision-proposals/facade.ts +++ b/packages/js-evo-sdk/src/decision-proposals/facade.ts @@ -1,17 +1,24 @@ import * as wasm from '../wasm.js'; import type { EvoSDK } from '../sdk.js'; +import { MultipleChoiceProposalsFacade } from './multiple-choice-facade.js'; /** * Decision proposals (protocol version 15): yes/no questions any identity puts to the * masternodes. A proposal is a `proposal` document of the decision proposals system contract; * creating it opens its vote poll, and its owner pays the decision proposal fund, 0.5 Dash. * Nothing acts on a result. Every read is a proved query. + * + * A question with more than two answers is a multiple choice proposal: see `multipleChoice`. */ export class DecisionProposalsFacade { private sdk: EvoSDK; + /** Multiple choice proposals, their choices and the vote among them. */ + public multipleChoice: MultipleChoiceProposalsFacade; + constructor(sdk: EvoSDK) { this.sdk = sdk; + this.multipleChoice = new MultipleChoiceProposalsFacade(sdk); } /** diff --git a/packages/js-evo-sdk/src/decision-proposals/multiple-choice-facade.ts b/packages/js-evo-sdk/src/decision-proposals/multiple-choice-facade.ts new file mode 100644 index 00000000000..2c39fd6f02e --- /dev/null +++ b/packages/js-evo-sdk/src/decision-proposals/multiple-choice-facade.ts @@ -0,0 +1,131 @@ +import * as wasm from '../wasm.js'; +import type { EvoSDK } from '../sdk.js'; + +/** + * Multiple choice proposals (protocol version 15): questions whose answers are the choices + * entered for them. A proposal is a `multipleChoiceProposal` document and an answer a `choice` + * document of the decision proposals system contract. The choices contend in a masternode + * vote that the first choice opens, and the one with the most votes is kept. A choice is named + * by its document id, in a vote and in the vote's state. Every read is a proved query. + */ +export class MultipleChoiceProposalsFacade { + private sdk: EvoSDK; + + constructor(sdk: EvoSDK) { + this.sdk = sdk; + } + + /** + * Builds a proposal to create with `sdk.documents.create`, which returns the stored proposal + * with its final id. Its owner pays the processing fee `processingFee()` gives on top of the + * fees. + */ + async build(options: wasm.MultipleChoiceProposalOptions): Promise { + const w = await this.sdk.getWasmSdkConnected(); + return w.buildMultipleChoiceProposal(options); + } + + /** + * A proposal with a new title, url or description document and its next revision, to replace + * with `sdk.documents.replace`. Platform accepts the edit for two hours after the proposal + * is created. + */ + async buildEdit( + proposal: wasm.Document, + edit: wasm.MultipleChoiceProposalEdit, + ): Promise { + const w = await this.sdk.getWasmSdkConnected(); + return w.buildMultipleChoiceProposalEdit(proposal, edit); + } + + /** + * Builds a choice to create with `sdk.documents.create`, which states the contest fund and + * returns the stored choice with its final id, the id a vote towards it carries. + */ + async buildChoice(options: wasm.MultipleChoiceProposalChoiceOptions): Promise { + const w = await this.sdk.getWasmSdkConnected(); + return w.buildMultipleChoiceProposalChoice(options); + } + + /** What creating one proposal adds to the processing fee of its batch, in credits. */ + async processingFee(): Promise { + const w = await this.sdk.getWasmSdkConnected(); + return w.getMultipleChoiceProposalProcessingFee(); + } + + /** The fund a choice entered now for a proposal pays, in credits. */ + async choiceFund(proposalId: wasm.IdentifierLike): Promise { + const w = await this.sdk.getWasmSdkConnected(); + return w.getMultipleChoiceProposalChoiceFund(proposalId); + } + + /** A proposal by id, or undefined when there is none. */ + async get(proposalId: wasm.IdentifierLike): Promise { + const w = await this.sdk.getWasmSdkConnected(); + return w.getMultipleChoiceProposal(proposalId); + } + + /** One page of an identity's proposals, by creation time. */ + async byOwner( + query: wasm.DecisionProposalsByOwnerQuery, + ): Promise> { + const w = await this.sdk.getWasmSdkConnected(); + return w.getMultipleChoiceProposalsByOwner(query); + } + + /** One page of every proposal, newest first. */ + async byCreatedAt( + query?: wasm.DecisionProposalsPageQuery, + ): Promise> { + const w = await this.sdk.getWasmSdkConnected(); + return w.getMultipleChoiceProposalsByCreatedAt(query); + } + + /** + * The vote among a proposal's choices as a vote poll, for `sdk.voting` and the contested + * resource queries. + */ + async votePoll(proposalId: wasm.IdentifierLike): Promise { + const w = await this.sdk.getWasmSdkConnected(); + return w.getMultipleChoiceProposalVotePoll(proposalId); + } + + /** + * The vote among a proposal's choices: every choice with its tally while the vote runs, and + * its result with every choice's final tally once it ended. + */ + async voteState(proposalId: wasm.IdentifierLike): Promise { + const w = await this.sdk.getWasmSdkConnected(); + return w.getMultipleChoiceProposalVote(proposalId); + } + + /** + * The choice the finished vote of a proposal kept, or undefined while the vote runs and when + * it kept none. + */ + async keptChoice(proposalId: wasm.IdentifierLike): Promise { + const w = await this.sdk.getWasmSdkConnected(); + return w.getMultipleChoiceProposalKeptChoice(proposalId); + } + + /** + * The answer a masternode gave in the vote among a proposal's choices, or undefined when it + * has not voted in it or the vote ended. + */ + async masternodeVote( + proTxHash: wasm.IdentifierLike, + proposalId: wasm.IdentifierLike, + ): Promise { + const w = await this.sdk.getWasmSdkConnected(); + return w.getMasternodeMultipleChoiceProposalVote(proTxHash, proposalId); + } + + /** + * Votes in the vote among a proposal's choices for a masternode, and returns the vote as + * Platform recorded it. + */ + async vote(options: wasm.MultipleChoiceProposalVoteOptions): Promise { + const w = await this.sdk.getWasmSdkConnected(); + return w.multipleChoiceProposalVote(options); + } +} diff --git a/packages/js-evo-sdk/src/sdk.ts b/packages/js-evo-sdk/src/sdk.ts index e59e2843d58..b23507852d7 100644 --- a/packages/js-evo-sdk/src/sdk.ts +++ b/packages/js-evo-sdk/src/sdk.ts @@ -460,6 +460,7 @@ export { ShieldedFacade } from './shielded/facade.js'; export { EncryptedForFacade } from './encrypted-for/facade.js'; export { ModerationChartersFacade } from './moderation-charters/facade.js'; export { DecisionProposalsFacade } from './decision-proposals/facade.js'; +export { MultipleChoiceProposalsFacade } from './decision-proposals/multiple-choice-facade.js'; export { PrivateDocumentsFacade } from './private-documents/facade.js'; export { wallet } from './wallet/functions.js'; export * from './wasm.js'; diff --git a/packages/js-evo-sdk/tests/unit/facades/multiple-choice-proposals.spec.ts b/packages/js-evo-sdk/tests/unit/facades/multiple-choice-proposals.spec.ts new file mode 100644 index 00000000000..70d95e4655e --- /dev/null +++ b/packages/js-evo-sdk/tests/unit/facades/multiple-choice-proposals.spec.ts @@ -0,0 +1,169 @@ +import type { SinonStub } from 'sinon'; +import init, * as wasmSDKPackage from '@dashevo/wasm-sdk'; +import { EvoSDK } from '../../../dist/sdk.js'; + +describe('MultipleChoiceProposalsFacade', () => { + let wasmSdk: wasmSDKPackage.WasmSdk; + let client: EvoSDK; + + let buildMultipleChoiceProposalStub: SinonStub; + let buildMultipleChoiceProposalEditStub: SinonStub; + let buildMultipleChoiceProposalChoiceStub: SinonStub; + let getMultipleChoiceProposalProcessingFeeStub: SinonStub; + let getMultipleChoiceProposalChoiceFundStub: SinonStub; + let getMultipleChoiceProposalStub: SinonStub; + let getMultipleChoiceProposalsByOwnerStub: SinonStub; + let getMultipleChoiceProposalsByCreatedAtStub: SinonStub; + let getMultipleChoiceProposalVotePollStub: SinonStub; + let getMultipleChoiceProposalVoteStub: SinonStub; + let getMultipleChoiceProposalKeptChoiceStub: SinonStub; + let getMasternodeMultipleChoiceProposalVoteStub: SinonStub; + let multipleChoiceProposalVoteStub: SinonStub; + + const ownerId = '5mjGWa9mruHnLBht3ntBi8CZ6sNk3hZZsQMgTvgQobjS'; + const proposalId = '4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF'; + const choiceId = 'GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec'; + const proTxHash = 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2'; + + beforeEach(async function setup() { + await init(); + const builder = wasmSDKPackage.WasmSdkBuilder.testnet(); + wasmSdk = await builder.build(); + client = EvoSDK.fromWasm(wasmSdk); + + buildMultipleChoiceProposalStub = this.sinon.stub(wasmSdk, 'buildMultipleChoiceProposal').resolves({}); + buildMultipleChoiceProposalEditStub = this.sinon.stub(wasmSdk, 'buildMultipleChoiceProposalEdit').returns({}); + buildMultipleChoiceProposalChoiceStub = this.sinon.stub(wasmSdk, 'buildMultipleChoiceProposalChoice').resolves({}); + getMultipleChoiceProposalProcessingFeeStub = this.sinon.stub(wasmSdk, 'getMultipleChoiceProposalProcessingFee').resolves(20_000_000_000n); + getMultipleChoiceProposalChoiceFundStub = this.sinon.stub(wasmSdk, 'getMultipleChoiceProposalChoiceFund').resolves(10_000_000_000n); + getMultipleChoiceProposalStub = this.sinon.stub(wasmSdk, 'getMultipleChoiceProposal').resolves(undefined); + getMultipleChoiceProposalsByOwnerStub = this.sinon.stub(wasmSdk, 'getMultipleChoiceProposalsByOwner').resolves(new Map()); + getMultipleChoiceProposalsByCreatedAtStub = this.sinon.stub(wasmSdk, 'getMultipleChoiceProposalsByCreatedAt').resolves(new Map()); + getMultipleChoiceProposalVotePollStub = this.sinon.stub(wasmSdk, 'getMultipleChoiceProposalVotePoll').returns({}); + getMultipleChoiceProposalVoteStub = this.sinon.stub(wasmSdk, 'getMultipleChoiceProposalVote').resolves({ choices: new Map() }); + getMultipleChoiceProposalKeptChoiceStub = this.sinon.stub(wasmSdk, 'getMultipleChoiceProposalKeptChoice').resolves(undefined); + getMasternodeMultipleChoiceProposalVoteStub = this.sinon.stub(wasmSdk, 'getMasternodeMultipleChoiceProposalVote').resolves(undefined); + multipleChoiceProposalVoteStub = this.sinon.stub(wasmSdk, 'multipleChoiceProposalVote').resolves({}); + }); + + describe('build()', () => { + it('should forward the options to buildMultipleChoiceProposal', async () => { + const options = { + ownerId, + title: 'Which block size?', + descriptionDocument: { id: choiceId, contractId: ownerId, documentType: 'post' }, + url: 'https://forum.dash.org/t/block-size', + open: true, + }; + await client.decisionProposals.multipleChoice.build(options); + expect(buildMultipleChoiceProposalStub).to.be.calledOnceWithExactly(options); + }); + }); + + describe('buildEdit()', () => { + it('should forward the proposal and the edit to buildMultipleChoiceProposalEdit', async () => { + const proposal = {} as wasmSDKPackage.Document; + const edit = { title: 'Which block size, then?', descriptionDocument: null }; + await client.decisionProposals.multipleChoice.buildEdit(proposal, edit); + expect(buildMultipleChoiceProposalEditStub).to.be.calledOnceWithExactly(proposal, edit); + }); + }); + + describe('buildChoice()', () => { + it('should forward the options to buildMultipleChoiceProposalChoice', async () => { + const options = { ownerId, proposalId, title: 'Double it' }; + await client.decisionProposals.multipleChoice.buildChoice(options); + expect(buildMultipleChoiceProposalChoiceStub).to.be.calledOnceWithExactly(options); + }); + }); + + describe('processingFee()', () => { + it('should return the fee getMultipleChoiceProposalProcessingFee gives', async () => { + const fee = await client.decisionProposals.multipleChoice.processingFee(); + expect(getMultipleChoiceProposalProcessingFeeStub).to.be.calledOnceWithExactly(); + expect(fee).to.equal(20_000_000_000n); + }); + }); + + describe('choiceFund()', () => { + it('should forward the proposal id to getMultipleChoiceProposalChoiceFund', async () => { + const fund = await client.decisionProposals.multipleChoice.choiceFund(proposalId); + expect(getMultipleChoiceProposalChoiceFundStub).to.be.calledOnceWithExactly(proposalId); + expect(fund).to.equal(10_000_000_000n); + }); + }); + + describe('get()', () => { + it('should forward the proposal id to getMultipleChoiceProposal', async () => { + const result = await client.decisionProposals.multipleChoice.get(proposalId); + expect(getMultipleChoiceProposalStub).to.be.calledOnceWithExactly(proposalId); + expect(result).to.equal(undefined); + }); + }); + + describe('byOwner()', () => { + it('should forward the query to getMultipleChoiceProposalsByOwner', async () => { + const query = { ownerId, startAfter: proposalId }; + const result = await client.decisionProposals.multipleChoice.byOwner(query); + expect(getMultipleChoiceProposalsByOwnerStub).to.be.calledOnceWithExactly(query); + expect(result).to.be.instanceOf(Map); + }); + }); + + describe('byCreatedAt()', () => { + it('should forward the query to getMultipleChoiceProposalsByCreatedAt', async () => { + const query = { limit: 5 }; + await client.decisionProposals.multipleChoice.byCreatedAt(query); + expect(getMultipleChoiceProposalsByCreatedAtStub).to.be.calledOnceWithExactly(query); + }); + + it('should list from the start without a query', async () => { + await client.decisionProposals.multipleChoice.byCreatedAt(); + expect(getMultipleChoiceProposalsByCreatedAtStub).to.be.calledOnceWithExactly(undefined); + }); + }); + + describe('votePoll()', () => { + it('should forward the proposal id to getMultipleChoiceProposalVotePoll', async () => { + await client.decisionProposals.multipleChoice.votePoll(proposalId); + expect(getMultipleChoiceProposalVotePollStub).to.be.calledOnceWithExactly(proposalId); + }); + }); + + describe('voteState()', () => { + it('should forward the proposal id to getMultipleChoiceProposalVote', async () => { + const vote = await client.decisionProposals.multipleChoice.voteState(proposalId); + expect(getMultipleChoiceProposalVoteStub).to.be.calledOnceWithExactly(proposalId); + expect(vote.choices).to.be.instanceOf(Map); + }); + }); + + describe('keptChoice()', () => { + it('should forward the proposal id to getMultipleChoiceProposalKeptChoice', async () => { + await client.decisionProposals.multipleChoice.keptChoice(proposalId); + expect(getMultipleChoiceProposalKeptChoiceStub).to.be.calledOnceWithExactly(proposalId); + }); + }); + + describe('masternodeVote()', () => { + it('should forward the masternode and the proposal to getMasternodeMultipleChoiceProposalVote', async () => { + await client.decisionProposals.multipleChoice.masternodeVote(proTxHash, proposalId); + expect(getMasternodeMultipleChoiceProposalVoteStub) + .to.be.calledOnceWithExactly(proTxHash, proposalId); + }); + }); + + describe('vote()', () => { + it('should forward the options to multipleChoiceProposalVote', async () => { + const options = { + masternodeProTxHash: proTxHash, + proposalId, + voteChoice: { choiceId }, + votingKey: {} as wasmSDKPackage.IdentityPublicKey, + signer: {} as wasmSDKPackage.IdentitySigner, + }; + await client.decisionProposals.multipleChoice.vote(options); + expect(multipleChoiceProposalVoteStub).to.be.calledOnceWithExactly(options); + }); + }); +}); diff --git a/packages/rs-dpp/src/decision_proposal/mod.rs b/packages/rs-dpp/src/decision_proposal/mod.rs index ae87e9a5f47..1e0abe405a4 100644 --- a/packages/rs-dpp/src/decision_proposal/mod.rs +++ b/packages/rs-dpp/src/decision_proposal/mod.rs @@ -9,6 +9,11 @@ //! //! [`DecisionProposalVotePoll::from_proposal`] reads the poll a proposal opens from its id and //! properties. Consensus uses it to open the poll, and clients to name the poll they query. +//! +//! A multiple choice proposal opens no yes/no poll: its choices contend in a masternode vote +//! among documents, which [`multiple_choice`] names for clients. + +pub mod multiple_choice; use crate::balances::credits::Credits; use crate::consensus::basic::decision_proposal::InvalidDecisionProposalRuleError; diff --git a/packages/rs-dpp/src/decision_proposal/multiple_choice.rs b/packages/rs-dpp/src/decision_proposal/multiple_choice.rs new file mode 100644 index 00000000000..0c30fb6e89c --- /dev/null +++ b/packages/rs-dpp/src/decision_proposal/multiple_choice.rs @@ -0,0 +1,275 @@ +//! Multiple choice proposals (protocol version 15): what clients name them and their vote by. +//! +//! A multiple choice proposal is a `multipleChoiceProposal` document of the decision proposals +//! contract; its answers are `choice` documents, which contend in a masternode vote among +//! documents (`ContestedIndexResolution::MasternodeVoteOnDocuments`). The vote is keyed by the +//! proposal's id ([`multiple_choice_proposal_vote_poll`]), and a choice is named in it by its +//! own document id, wherever a contest among identities names a contender by an identity id +//! ([`MultipleChoiceVoteChoice`]). + +use crate::decision_proposal::DECISION_PROPOSALS_CONTRACT_ID; +use crate::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; +use crate::voting::vote_polls::contested_document_resource_vote_poll::ContestedDocumentResourceVotePoll; +use crate::voting::vote_polls::VotePoll; +use crate::voting::votes::resource_vote::v0::ResourceVoteV0; +use crate::voting::votes::resource_vote::ResourceVote; +use crate::voting::votes::Vote; +use platform_value::{Identifier, Value}; + +/// The name of the choice document type: an answer to a multiple choice proposal. +pub const CHOICE_DOCUMENT_TYPE_NAME: &str = "choice"; + +/// The contested index every choice falls under, on the proposal it answers. A choice's create +/// states its contest fund under this name. +pub const CHOICE_CONTEST_INDEX_NAME: &str = "byProposal"; + +/// The properties of a multiple choice proposal. +pub mod proposal_properties { + /// The question, in one line. Editable for two hours after the proposal is created. + pub const TITLE: &str = "title"; + /// The document saying what is being decided; optional, given with the two properties + /// naming where it lives and only with them. Editable for two hours. + pub const DESCRIPTION_ID: &str = "descriptionId"; + /// The contract the description document lives in. + pub const DESCRIPTION_CONTRACT_ID: &str = "descriptionContractId"; + /// The document type of the description document. + pub const DESCRIPTION_DOCUMENT_TYPE: &str = "descriptionDocumentType"; + /// Where what is being decided is described or discussed; optional, required of a proposal + /// that points at no description document. Editable for two hours. + pub const URL: &str = "url"; + /// Whether anyone may enter choices; only the proposal's owner may when it is false. + /// Never changes. + pub const OPEN: &str = "open"; +} + +/// The properties of a choice. +pub mod choice_properties { + /// The multiple choice proposal the choice answers. + pub const PROPOSAL_ID: &str = "proposalId"; + /// The answer, in one line. + pub const TITLE: &str = "title"; + /// What voting for the answer means; optional. + pub const DESCRIPTION: &str = "description"; +} + +/// Whether a document of `document_type_name` in the contract `contract_id` is a choice: a +/// `choice` of the decision proposals contract. Its create joins the vote among the choices of +/// the proposal it answers, or opens it. +pub fn is_choice(contract_id: &Identifier, document_type_name: &str) -> bool { + *contract_id == DECISION_PROPOSALS_CONTRACT_ID + && document_type_name == CHOICE_DOCUMENT_TYPE_NAME +} + +/// The vote among the choices of the multiple choice proposal `proposal_id`: the contest of +/// the `choice` type's `byProposal` index at that proposal, as a choice's create derives it +/// from its `proposalId`. The contested resource queries take it, and a masternode's vote +/// names it. Known from the proposal's id alone, whether or not a choice has opened the vote. +pub fn multiple_choice_proposal_vote_poll( + proposal_id: Identifier, +) -> ContestedDocumentResourceVotePoll { + ContestedDocumentResourceVotePoll { + contract_id: DECISION_PROPOSALS_CONTRACT_ID, + document_type_name: CHOICE_DOCUMENT_TYPE_NAME.to_string(), + index_name: CHOICE_CONTEST_INDEX_NAME.to_string(), + index_values: vec![Value::Identifier(proposal_id.to_buffer())], + } +} + +/// A masternode's answer in the vote among a multiple choice proposal's choices. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MultipleChoiceVoteChoice { + /// For the choice with this document id. The id of the identity that entered the choice + /// names no contender here, and a vote carrying it is refused. + Choice(Identifier), + /// For no choice and against none. + Abstain, + /// None of the choices: when these votes outnumber the leading choice, no choice is kept + /// and none can be entered for the proposal again. + NoneOfTheChoices, +} + +impl From for ResourceVoteChoice { + /// The resource vote choice the contest takes: a choice's document id travels where a + /// contest among identities carries an identity id, and none of the choices is a lock. + fn from(vote_choice: MultipleChoiceVoteChoice) -> Self { + match vote_choice { + MultipleChoiceVoteChoice::Choice(choice_id) => { + ResourceVoteChoice::TowardsIdentity(choice_id) + } + MultipleChoiceVoteChoice::Abstain => ResourceVoteChoice::Abstain, + MultipleChoiceVoteChoice::NoneOfTheChoices => ResourceVoteChoice::Lock, + } + } +} + +/// A masternode's vote `vote_choice` in the vote among the choices of the multiple choice +/// proposal `proposal_id`, to sign as a masternode vote transition. +pub fn multiple_choice_proposal_vote( + proposal_id: Identifier, + vote_choice: MultipleChoiceVoteChoice, +) -> Vote { + Vote::ResourceVote(ResourceVote::V0(ResourceVoteV0 { + vote_poll: VotePoll::ContestedDocumentResourceVotePoll(multiple_choice_proposal_vote_poll( + proposal_id, + )), + resource_vote_choice: vote_choice.into(), + })) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::decision_proposal::{ + is_multiple_choice_proposal, MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME, + }; + + #[test] + fn should_recognize_only_the_choice_of_the_decision_proposals_contract() { + assert!(is_choice( + &DECISION_PROPOSALS_CONTRACT_ID, + CHOICE_DOCUMENT_TYPE_NAME + )); + assert!(!is_choice( + &DECISION_PROPOSALS_CONTRACT_ID, + MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME + )); + assert!(!is_choice( + &Identifier::new([1; 32]), + CHOICE_DOCUMENT_TYPE_NAME + )); + assert!(!is_multiple_choice_proposal( + &DECISION_PROPOSALS_CONTRACT_ID, + CHOICE_DOCUMENT_TYPE_NAME + )); + } + + #[test] + fn should_vote_towards_a_choice_by_its_document_id() { + let proposal_id = Identifier::new([7; 32]); + let choice_id = Identifier::new([9; 32]); + let answers = [ + ( + MultipleChoiceVoteChoice::Choice(choice_id), + ResourceVoteChoice::TowardsIdentity(choice_id), + ), + ( + MultipleChoiceVoteChoice::Abstain, + ResourceVoteChoice::Abstain, + ), + ( + MultipleChoiceVoteChoice::NoneOfTheChoices, + ResourceVoteChoice::Lock, + ), + ]; + for (vote_choice, resource_vote_choice) in answers { + assert_eq!( + multiple_choice_proposal_vote(proposal_id, vote_choice), + Vote::ResourceVote(ResourceVote::V0(ResourceVoteV0 { + vote_poll: VotePoll::ContestedDocumentResourceVotePoll( + multiple_choice_proposal_vote_poll(proposal_id) + ), + resource_vote_choice, + })), + "{vote_choice:?}" + ); + } + } + + #[cfg(feature = "decision-proposals-contract")] + #[test] + fn should_name_the_types_and_properties_as_the_contract_crate_does() { + use data_contracts::decision_proposals_contract::v1::document_types::{ + choice, multiple_choice_proposal, + }; + + assert_eq!( + MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME, + multiple_choice_proposal::NAME + ); + assert_eq!( + proposal_properties::TITLE, + multiple_choice_proposal::properties::TITLE + ); + assert_eq!( + proposal_properties::DESCRIPTION_ID, + multiple_choice_proposal::properties::DESCRIPTION_ID + ); + assert_eq!( + proposal_properties::DESCRIPTION_CONTRACT_ID, + multiple_choice_proposal::properties::DESCRIPTION_CONTRACT_ID + ); + assert_eq!( + proposal_properties::DESCRIPTION_DOCUMENT_TYPE, + multiple_choice_proposal::properties::DESCRIPTION_DOCUMENT_TYPE + ); + assert_eq!( + proposal_properties::URL, + multiple_choice_proposal::properties::URL + ); + assert_eq!( + proposal_properties::OPEN, + multiple_choice_proposal::properties::OPEN + ); + assert_eq!(CHOICE_DOCUMENT_TYPE_NAME, choice::NAME); + assert_eq!(CHOICE_CONTEST_INDEX_NAME, choice::indexes::BY_PROPOSAL); + assert_eq!( + choice_properties::PROPOSAL_ID, + choice::properties::PROPOSAL_ID + ); + assert_eq!(choice_properties::TITLE, choice::properties::TITLE); + assert_eq!( + choice_properties::DESCRIPTION, + choice::properties::DESCRIPTION + ); + } + + /// The poll named from the proposal's id alone is the one a choice's create derives from + /// its `proposalId`, in whichever form the create writes the id. + #[cfg(feature = "decision-proposals-contract")] + #[test] + fn should_name_the_vote_a_choice_joins_by_the_proposal_id_alone() { + use crate::data_contract::accessors::v0::DataContractV0Getters; + use crate::data_contract::document_type::methods::DocumentTypeV0Methods; + use crate::document::{Document, DocumentV0}; + use crate::system_data_contracts::{load_system_data_contract, SystemDataContract}; + use platform_version::version::PlatformVersion; + use std::collections::BTreeMap; + + let platform_version = PlatformVersion::latest(); + let contract = + load_system_data_contract(SystemDataContract::DecisionProposals, platform_version) + .expect("the contract loads at the latest version"); + let document_type = contract + .document_type_for_name(CHOICE_DOCUMENT_TYPE_NAME) + .expect("the choice type"); + let proposal_id = Identifier::new([7; 32]); + let forms = [ + Value::Identifier(proposal_id.to_buffer()), + Value::Bytes32(proposal_id.to_buffer()), + Value::Bytes(proposal_id.to_vec()), + ]; + for proposal_id_value in forms { + let choice: Document = DocumentV0 { + properties: BTreeMap::from([ + ( + choice_properties::PROPOSAL_ID.to_string(), + proposal_id_value.clone(), + ), + ( + choice_properties::TITLE.to_string(), + Value::Text("Double it".to_string()), + ), + ]), + ..Default::default() + } + .into(); + assert_eq!( + document_type + .contested_vote_poll_for_document(&choice, platform_version) + .expect("active"), + Some(multiple_choice_proposal_vote_poll(proposal_id)), + "{proposal_id_value:?}" + ); + } + } +} diff --git a/packages/rs-sdk/src/platform/decision_proposals.rs b/packages/rs-sdk/src/platform/decision_proposals.rs index f029b639a1a..62cc96a64ea 100644 --- a/packages/rs-sdk/src/platform/decision_proposals.rs +++ b/packages/rs-sdk/src/platform/decision_proposals.rs @@ -24,6 +24,11 @@ //! for the poll's status and tallies, and to //! [`MasternodeYesNoVoteQuery::new`](crate::platform::yes_no_vote_polls::MasternodeYesNoVoteQuery::new) //! for a masternode's answer. +//! +//! A question with more than two answers is a multiple choice proposal, whose answers are +//! choices that contend in a masternode vote: see [`multiple_choice`]. + +pub mod multiple_choice; use crate::platform::documents::document_query::DocumentQuery; use crate::platform::documents::page::DocumentsPage; @@ -83,14 +88,14 @@ pub struct DecisionProposalEdit { pub url: Option>, } -/// A proposal ready to be put with +/// A proposal, or a choice of a multiple choice proposal, ready to be put with /// [`PutDocument`](crate::platform::transition::put_document::PutDocument): the document and /// the entropy its id derives from, which the put must reuse. #[derive(Debug, Clone)] pub struct DecisionProposalDocument { /// The document. Its id is a placeholder until it is put: from protocol version 14 the id - /// also commits to the identity contract nonce of the create transition. The poll is named - /// by the id of the document the put returns. + /// also commits to the identity contract nonce of the create transition. A proposal's poll, + /// and a choice in its vote, are named by the id of the document the put returns. pub document: Document, /// The entropy the document id derives from. pub entropy: Bytes32, @@ -181,9 +186,6 @@ pub fn build_decision_proposal_document( input: &DecisionProposalInput, entropy: Bytes32, ) -> Result { - let document_type = contract - .document_type_for_name(PROPOSAL_DOCUMENT_TYPE_NAME) - .map_err(|e| Error::Protocol(e.into()))?; let mut properties = BTreeMap::from([ ( properties::TITLE.to_string(), @@ -206,11 +208,32 @@ pub fn build_decision_proposal_document( if let Some(url) = &input.url { properties.insert(properties::URL.to_string(), Value::Text(url.clone())); } + new_document( + contract, + PROPOSAL_DOCUMENT_TYPE_NAME, + owner_id, + properties, + entropy, + ) +} + +/// A new `document_type_name` document of `owner_id` in `contract` holding `properties`, with +/// its id derived from `entropy` and its first revision when the type keeps one. +fn new_document( + contract: &DataContract, + document_type_name: &str, + owner_id: Identifier, + properties: BTreeMap, + entropy: Bytes32, +) -> Result { + let document_type = contract + .document_type_for_name(document_type_name) + .map_err(|e| Error::Protocol(e.into()))?; let document = DocumentV0 { id: Document::generate_document_id_v0( &contract.id(), &owner_id, - PROPOSAL_DOCUMENT_TYPE_NAME, + document_type_name, entropy.as_slice(), ), owner_id, @@ -303,13 +326,15 @@ fn proposals_by_end_date_query( ) } -/// The query for the proposals of `owner_id`, by creation time (`byOwner`), one page of them. +/// The query for the `document_type_name` documents of `owner_id`, by creation time (`byOwner`), +/// one page of them. fn proposals_by_owner_query( contract: Arc, + document_type_name: &str, owner_id: Identifier, page: DocumentsPage, ) -> Result { - let query = DocumentQuery::new(contract, PROPOSAL_DOCUMENT_TYPE_NAME)? + let query = DocumentQuery::new(contract, document_type_name)? .with_where(WhereClause { field: "$ownerId".to_string(), operator: WhereOperator::Equal, @@ -324,16 +349,17 @@ fn proposals_by_owner_query( paged(query, page) } -/// The query for every proposal, newest first (`byCreatedAt`), one page of them. +/// The query for every `document_type_name` document, newest first (`byCreatedAt`), one page +/// of them. fn proposals_by_created_at_query( contract: Arc, + document_type_name: &str, page: DocumentsPage, ) -> Result { - let query = - DocumentQuery::new(contract, PROPOSAL_DOCUMENT_TYPE_NAME)?.with_order_by(OrderClause { - field: "$createdAt".to_string(), - ascending: false, - }); + let query = DocumentQuery::new(contract, document_type_name)?.with_order_by(OrderClause { + field: "$createdAt".to_string(), + ascending: false, + }); paged(query, page) } @@ -415,7 +441,11 @@ impl Sdk { page: DocumentsPage, ) -> Result { let contract = self.fetch_decision_proposals_contract().await?; - Document::fetch_many(self, proposals_by_owner_query(contract, owner_id, page)?).await + Document::fetch_many( + self, + proposals_by_owner_query(contract, PROPOSAL_DOCUMENT_TYPE_NAME, owner_id, page)?, + ) + .await } /// One page of every proposal, newest first. [`DocumentsPage::after`] gives the next page. @@ -424,7 +454,11 @@ impl Sdk { page: DocumentsPage, ) -> Result { let contract = self.fetch_decision_proposals_contract().await?; - Document::fetch_many(self, proposals_by_created_at_query(contract, page)?).await + Document::fetch_many( + self, + proposals_by_created_at_query(contract, PROPOSAL_DOCUMENT_TYPE_NAME, page)?, + ) + .await } /// A masternode's answer `vote_choice` on the proposal `proposal_id`, to put with @@ -804,13 +838,22 @@ mod tests { } assert_eq!( served_through( - &proposals_by_owner_query(contract.clone(), Identifier::from([3; 32]), page) - .expect("builds") + &proposals_by_owner_query( + contract.clone(), + PROPOSAL_DOCUMENT_TYPE_NAME, + Identifier::from([3; 32]), + page + ) + .expect("builds") ), "byOwner" ); - let by_created_at = - proposals_by_created_at_query(contract, DocumentsPage::default()).expect("builds"); + let by_created_at = proposals_by_created_at_query( + contract, + PROPOSAL_DOCUMENT_TYPE_NAME, + DocumentsPage::default(), + ) + .expect("builds"); assert_eq!(served_through(&by_created_at), "byCreatedAt"); assert_eq!(by_created_at.limit, 100); assert_eq!(by_created_at.start, None); diff --git a/packages/rs-sdk/src/platform/decision_proposals/multiple_choice.rs b/packages/rs-sdk/src/platform/decision_proposals/multiple_choice.rs new file mode 100644 index 00000000000..2dda70d0be1 --- /dev/null +++ b/packages/rs-sdk/src/platform/decision_proposals/multiple_choice.rs @@ -0,0 +1,1257 @@ +//! Multiple choice proposals (protocol version 15): questions whose answers are the choices +//! entered for them. A proposal is a `multipleChoiceProposal` document of the decision +//! proposals system contract and an answer is a `choice` document; the choices contend in a +//! masternode vote that the first choice opens, and the one with the most votes is kept. +//! +//! * [`Sdk::build_multiple_choice_proposal`] builds a proposal, put like any document create +//! with [`PutDocument`](crate::platform::transition::put_document::PutDocument). Its owner +//! pays the multiple choice proposal processing fee +//! ([`Sdk::multiple_choice_proposal_processing_fee`]) on top of the fees; the create does +//! not state it. +//! * [`build_multiple_choice_proposal_edit`] gives a proposal a new title, url or description +//! document, put as a replace, for two hours after the proposal is created. +//! * [`Sdk::build_choice`] builds an answer to a proposal, put like any document create. The +//! put states the contest fund ([`Sdk::choice_fund_to_join`]), which its owner pays. Anyone +//! enters choices for an open proposal, and only its owner for one that is not. +//! * [`Sdk::fetch_multiple_choice_proposal`] reads a proposal by id, and two listings read +//! them a page at a time: [`Sdk::fetch_multiple_choice_proposals_by_owner`] in filing order +//! and [`Sdk::fetch_multiple_choice_proposals_by_created_at`] newest first. +//! [`MultipleChoiceProposal::from_document`] reads a proposal's properties. +//! * [`Sdk::fetch_multiple_choice_proposal_vote`] reads the vote: the choices with their +//! tallies while it runs, and its outcome with every choice's tally afterwards. +//! [`Sdk::fetch_kept_choice`] reads the choice a finished vote kept. +//! * [`multiple_choice_proposal_vote`] builds a masternode's answer, put with +//! [`PutVote`](crate::platform::transition::vote::PutVote), and +//! [`Sdk::fetch_masternode_multiple_choice_vote`] reads the answer a masternode gave. +//! +//! A choice is named by its document id wherever a contest among identities names a contender +//! by an identity id: in a vote ([`MultipleChoiceVoteChoice::Choice`]), in the vote's state and +//! in its winner. The vote itself is the contest [`multiple_choice_proposal_vote_poll`] names +//! from the proposal's id, which the contested resource queries take as it is. + +use super::{ + new_document, proposals_by_created_at_query, proposals_by_owner_query, DecisionProposalDocument, +}; +use crate::platform::documents::document_query::DocumentQuery; +use crate::platform::documents::page::DocumentsPage; +use crate::platform::query::VoteQuery; +use crate::platform::{DataContract, Document, Fetch, FetchMany, Identifier}; +use crate::{Error, Sdk}; +use dpp::block::block_info::BlockInfo; +use dpp::data_contract::accessors::v0::DataContractV0Getters; +use dpp::decision_proposal::multiple_choice::{ + choice_properties, proposal_properties, CHOICE_DOCUMENT_TYPE_NAME, +}; +pub use dpp::decision_proposal::multiple_choice::{ + multiple_choice_proposal_vote, multiple_choice_proposal_vote_poll, MultipleChoiceVoteChoice, +}; +use dpp::decision_proposal::{ + is_multiple_choice_proposal, multiple_choice_proposal_processing_fee, + MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME, +}; +use dpp::document::document_methods::DocumentMethodsV0; +use dpp::document::{DocumentV0Getters, DocumentV0Setters}; +use dpp::fee::Credits; +use dpp::platform_value::btreemap_extensions::BTreeValueMapHelper; +use dpp::platform_value::{Bytes32, Value}; +use dpp::secp256k1::rand::rngs::StdRng; +use dpp::secp256k1::rand::{Rng, SeedableRng}; +use dpp::version::feature_initial_protocol_versions::DECISION_PROPOSALS_CONTRACT_INITIAL_PROTOCOL_VERSION; +use dpp::version::PlatformVersion; +use dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; +use dpp::voting::vote_info_storage::contested_document_vote_poll_winner_info::ContestedDocumentVotePollWinnerInfo; +use dpp::voting::vote_polls::VotePoll; +use dpp::voting::votes::resource_vote::accessors::v0::ResourceVoteGettersV0; +use dpp::voting::votes::Vote; +use drive::query::{WhereClause, WhereOperator}; +use drive_proof_verifier::types::{Contenders, Documents}; +use std::collections::BTreeMap; +use std::sync::Arc; + +/// The document a multiple choice proposal points at for what is being decided. Platform +/// refuses one that is not of a moderated type the elected team of its contract may delete. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DescriptionDocument { + /// The document. + pub id: Identifier, + /// The contract it lives in, one whose moderators the masternodes elect. + pub contract_id: Identifier, + /// Its document type. + pub document_type: String, +} + +/// What a new multiple choice proposal asks. Platform refuses a proposal that gives neither a +/// description document nor a url. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MultipleChoiceProposalInput { + /// The question, in one line: 1 to 128 characters. + pub title: String, + /// The document saying what is being decided. + pub description_document: Option, + /// Where what is being decided is described, for a proposal that points at no description + /// document, or where it is discussed, for one that does: a URI of at most 512 characters. + pub url: Option, + /// Whether anyone may enter choices; only the proposal's owner may when it is false. It + /// never changes. + pub open: bool, +} + +/// What a multiple choice proposal changes to. A field left `None` keeps its value. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct MultipleChoiceProposalEdit { + /// The new title. + pub title: Option, + /// The new description document: `Some(Some(document))` points the proposal at it, + /// `Some(None)` leaves the proposal described at its url alone. + pub description_document: Option>, + /// The new url: `Some(Some(url))` sets it, `Some(None)` removes it. + pub url: Option>, +} + +/// A multiple choice proposal: its document and the properties read out of it. +#[derive(Debug, Clone, PartialEq)] +pub struct MultipleChoiceProposal { + /// The `multipleChoiceProposal` document. + pub document: Document, + /// The question, in one line. + pub title: String, + /// The document saying what is being decided, when the proposal points at one. + pub description_document: Option, + /// Where what is being decided is described or discussed. Nothing on chain moderates it. + pub url: Option, + /// Whether anyone may enter choices; only the proposal's owner may when it is false. + pub open: bool, +} + +impl MultipleChoiceProposal { + /// Reads a proposal out of a `multipleChoiceProposal` document. + pub fn from_document(document: Document) -> Result { + let malformed = |error: dpp::platform_value::Error| { + Error::Generic(format!( + "multiple choice proposal {} is malformed: {error}", + document.id() + )) + }; + let properties = document.properties(); + let description_document = properties + .get_optional_identifier(proposal_properties::DESCRIPTION_ID) + .map_err(malformed)? + .map(|id| { + Ok::<_, Error>(DescriptionDocument { + id, + contract_id: properties + .get_identifier(proposal_properties::DESCRIPTION_CONTRACT_ID) + .map_err(malformed)?, + document_type: properties + .get_string(proposal_properties::DESCRIPTION_DOCUMENT_TYPE) + .map_err(malformed)?, + }) + }) + .transpose()?; + Ok(Self { + title: properties + .get_string(proposal_properties::TITLE) + .map_err(malformed)?, + description_document, + url: properties + .get_optional_string(proposal_properties::URL) + .map_err(malformed)?, + open: properties + .get_bool(proposal_properties::OPEN) + .map_err(malformed)?, + document, + }) + } + + /// The proposal's id, which its choices and its vote name it by. + pub fn id(&self) -> Identifier { + self.document.id() + } + + /// The proposer, the only identity that enters choices when the proposal is not open. + pub fn owner_id(&self) -> Identifier { + self.document.owner_id() + } +} + +/// An answer to enter for a multiple choice proposal. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ChoiceInput { + /// The proposal the choice answers. + pub proposal_id: Identifier, + /// The answer, in one line: 1 to 128 characters. + pub title: String, + /// What voting for the answer means: 1 to 4096 characters. + pub description: Option, +} + +/// A choice: its document and the properties read out of it. +#[derive(Debug, Clone, PartialEq)] +pub struct Choice { + /// The `choice` document. + pub document: Document, + /// The proposal the choice answers. + pub proposal_id: Identifier, + /// The answer, in one line. + pub title: String, + /// What voting for the answer means. + pub description: Option, +} + +impl Choice { + /// Reads a choice out of a `choice` document. + pub fn from_document(document: Document) -> Result { + let malformed = |error: dpp::platform_value::Error| { + Error::Generic(format!("choice {} is malformed: {error}", document.id())) + }; + let properties = document.properties(); + Ok(Self { + proposal_id: properties + .get_identifier(choice_properties::PROPOSAL_ID) + .map_err(malformed)?, + title: properties + .get_string(choice_properties::TITLE) + .map_err(malformed)?, + description: properties + .get_optional_string(choice_properties::DESCRIPTION) + .map_err(malformed)?, + document, + }) + } + + /// The choice's id, which a vote towards it carries. + pub fn id(&self) -> Identifier { + self.document.id() + } + + /// The identity that entered the choice. + pub fn owner_id(&self) -> Identifier { + self.document.owner_id() + } +} + +/// A choice in the vote among a proposal's choices. +#[derive(Debug, Clone, PartialEq)] +pub struct ChoiceInVote { + /// The choice, while the vote runs. `None` once it ended: the choices that were not kept + /// are no longer in state, and the one that was kept is an ordinary document + /// ([`Sdk::fetch_kept_choice`]). + pub choice: Option, + /// The votes towards the choice: so far while the vote runs, final once it ended. + pub vote_tally: Option, +} + +/// The vote among a multiple choice proposal's choices. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct MultipleChoiceProposalVote { + /// The choices by their document ids. Empty for a proposal no choice was entered for. + pub choices: BTreeMap, + /// The abstaining votes. + pub abstain_vote_tally: Option, + /// The votes for none of the choices. + pub none_of_the_choices_vote_tally: Option, + /// How the vote ended and at which block; `None` while it runs. A winner is named by the + /// document id of the choice that was kept; locked means none of the choices was. + pub winner: Option<(ContestedDocumentVotePollWinnerInfo, BlockInfo)>, +} + +impl MultipleChoiceProposalVote { + /// Reads the vote out of the state of its contest, as the contested resource vote state + /// query returns it, with `contract` the decision proposals contract. + pub fn from_contenders( + contract: &DataContract, + contenders: Contenders, + platform_version: &PlatformVersion, + ) -> Result { + let document_type = contract + .document_type_for_name(CHOICE_DOCUMENT_TYPE_NAME) + .map_err(|e| Error::Protocol(e.into()))?; + let choices = contenders + .to_contenders(&document_type.to_owned_document_type(), platform_version)? + .into_iter() + .map(|(choice_id, contender)| { + let (document, vote_tally) = (contender.document().clone(), contender.vote_tally()); + Ok(( + choice_id, + ChoiceInVote { + choice: document.map(Choice::from_document).transpose()?, + vote_tally, + }, + )) + }) + .collect::>()?; + Ok(Self { + choices, + abstain_vote_tally: contenders.abstain_vote_tally, + none_of_the_choices_vote_tally: contenders.lock_vote_tally, + winner: contenders.winner, + }) + } + + /// The document id of the choice the vote kept; `None` while the vote runs, and when it + /// kept none. + pub fn kept_choice_id(&self) -> Option { + match self.winner { + Some((ContestedDocumentVotePollWinnerInfo::WonByIdentity(choice_id), _)) => { + Some(choice_id) + } + _ => None, + } + } +} + +/// The properties naming the description document `description_document`. +fn description_document_properties( + description_document: &DescriptionDocument, +) -> [(&'static str, Value); 3] { + [ + ( + proposal_properties::DESCRIPTION_ID, + Value::Identifier(description_document.id.to_buffer()), + ), + ( + proposal_properties::DESCRIPTION_CONTRACT_ID, + Value::Identifier(description_document.contract_id.to_buffer()), + ), + ( + proposal_properties::DESCRIPTION_DOCUMENT_TYPE, + Value::Text(description_document.document_type.clone()), + ), + ] +} + +/// Builds a multiple choice proposal of `owner_id` asking what `input` says, in `contract`, +/// the decision proposals contract, with its id derived from `entropy`. +pub fn build_multiple_choice_proposal_document( + contract: &DataContract, + owner_id: Identifier, + input: &MultipleChoiceProposalInput, + entropy: Bytes32, +) -> Result { + let mut properties = BTreeMap::from([ + ( + proposal_properties::TITLE.to_string(), + Value::Text(input.title.clone()), + ), + ( + proposal_properties::OPEN.to_string(), + Value::Bool(input.open), + ), + ]); + if let Some(description_document) = &input.description_document { + properties.extend( + description_document_properties(description_document) + .map(|(name, value)| (name.to_string(), value)), + ); + } + if let Some(url) = &input.url { + properties.insert( + proposal_properties::URL.to_string(), + Value::Text(url.clone()), + ); + } + new_document( + contract, + MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME, + owner_id, + properties, + entropy, + ) +} + +/// `proposal`, a `document_type_name` document of the contract `data_contract_id`, with what +/// `edit` changes and its next revision, ready to be put as a replace. Anything but a multiple +/// choice proposal is refused, as is an edit that leaves the proposal as it is: a replace that +/// changes nothing still pays its fees. Consensus refuses the replace more than two hours +/// after the proposal was created, one that leaves the proposal with neither a description +/// document nor a url, and any change to whether it is open. +pub fn build_multiple_choice_proposal_edit( + data_contract_id: &Identifier, + document_type_name: &str, + proposal: &Document, + edit: &MultipleChoiceProposalEdit, +) -> Result { + if !is_multiple_choice_proposal(data_contract_id, document_type_name) { + return Err(Error::Generic(format!( + "a {document_type_name} document of contract {data_contract_id} is not a multiple \ + choice proposal" + ))); + } + let mut document = proposal.clone(); + if let Some(title) = &edit.title { + document.set(proposal_properties::TITLE, Value::Text(title.clone())); + } + match &edit.description_document { + Some(Some(description_document)) => { + for (name, value) in description_document_properties(description_document) { + document.set(name, value); + } + } + Some(None) => { + for name in [ + proposal_properties::DESCRIPTION_ID, + proposal_properties::DESCRIPTION_CONTRACT_ID, + proposal_properties::DESCRIPTION_DOCUMENT_TYPE, + ] { + document.remove(name); + } + } + None => {} + } + match &edit.url { + Some(Some(url)) => document.set(proposal_properties::URL, Value::Text(url.clone())), + Some(None) => { + document.remove(proposal_properties::URL); + } + None => {} + } + if document.properties() == proposal.properties() { + return Err(Error::Generic(format!( + "the edit of multiple choice proposal {} changes nothing", + proposal.id() + ))); + } + document.increment_revision()?; + Ok(document) +} + +/// Builds a choice of `owner_id` answering what `input` says, in `contract`, the decision +/// proposals contract, with its id derived from `entropy`. +pub fn build_choice_document( + contract: &DataContract, + owner_id: Identifier, + input: &ChoiceInput, + entropy: Bytes32, +) -> Result { + let mut properties = BTreeMap::from([ + ( + choice_properties::PROPOSAL_ID.to_string(), + Value::Identifier(input.proposal_id.to_buffer()), + ), + ( + choice_properties::TITLE.to_string(), + Value::Text(input.title.clone()), + ), + ]); + if let Some(description) = &input.description { + properties.insert( + choice_properties::DESCRIPTION.to_string(), + Value::Text(description.clone()), + ); + } + new_document( + contract, + CHOICE_DOCUMENT_TYPE_NAME, + owner_id, + properties, + entropy, + ) +} + +/// The query for the choice the finished vote of the proposal `proposal_id` kept, which the +/// `byProposal` index holds as the one choice of that proposal. +fn kept_choice_query( + contract: Arc, + proposal_id: Identifier, +) -> Result { + Ok( + DocumentQuery::new(contract, CHOICE_DOCUMENT_TYPE_NAME)?.with_where(WhereClause { + field: choice_properties::PROPOSAL_ID.to_string(), + operator: WhereOperator::Equal, + value: Value::Identifier(proposal_id.to_buffer()), + }), + ) +} + +/// The answer the recorded `vote` gives in the vote among the choices of the proposal +/// `proposal_id`; `None` for a vote on anything else. +fn multiple_choice_vote_choice_of( + vote: &Vote, + proposal_id: Identifier, +) -> Option { + let Vote::ResourceVote(resource_vote) = vote else { + return None; + }; + let VotePoll::ContestedDocumentResourceVotePoll(vote_poll) = resource_vote.vote_poll() else { + return None; + }; + if *vote_poll != multiple_choice_proposal_vote_poll(proposal_id) { + return None; + } + Some(match resource_vote.resource_vote_choice() { + ResourceVoteChoice::TowardsIdentity(choice_id) => { + MultipleChoiceVoteChoice::Choice(choice_id) + } + ResourceVoteChoice::Abstain => MultipleChoiceVoteChoice::Abstain, + ResourceVoteChoice::Lock => MultipleChoiceVoteChoice::NoneOfTheChoices, + }) +} + +impl Sdk { + /// Builds a multiple choice proposal of `owner_id` asking what `input` says (see + /// [`build_multiple_choice_proposal_document`]). The result is put like any document + /// create; the owner pays [`Self::multiple_choice_proposal_processing_fee`] on top of the + /// fees. + pub async fn build_multiple_choice_proposal( + &self, + owner_id: Identifier, + input: &MultipleChoiceProposalInput, + ) -> Result { + let contract = self.fetch_decision_proposals_contract().await?; + let entropy = Bytes32::new(StdRng::from_os_rng().random()); + build_multiple_choice_proposal_document(&contract, owner_id, input, entropy) + } + + /// Builds a choice of `owner_id` answering what `input` says (see + /// [`build_choice_document`]). The result is put like any document create, which states + /// the contest fund; the owner pays it ([`Self::choice_fund_to_join`]) on top of the fees. + /// The first choice opens the vote, and later ones join it while its join window is open. + pub async fn build_choice( + &self, + owner_id: Identifier, + input: &ChoiceInput, + ) -> Result { + let contract = self.fetch_decision_proposals_contract().await?; + let entropy = Bytes32::new(StdRng::from_os_rng().random()); + build_choice_document(&contract, owner_id, input, entropy) + } + + /// What creating one multiple choice proposal adds to the processing fee of its batch, in + /// credits. The create does not state it: whoever pays the fees pays it, and an identity + /// whose balance does not cover it creates no proposal. + pub async fn multiple_choice_proposal_processing_fee(&self) -> Result { + self.require_protocol_version( + DECISION_PROPOSALS_CONTRACT_INITIAL_PROTOCOL_VERSION, + "the multiple choice proposal processing fee", + ) + .await?; + Ok(multiple_choice_proposal_processing_fee(self.version())) + } + + /// The fund a choice entered now for the proposal `proposal_id` pays, in credits: the + /// contest's fund, doubled once the vote holds 250 choices and again for every 50 more + /// (see [`Self::contest_fund_to_join`]). A put of a choice reads it and states it itself. + pub async fn choice_fund_to_join(&self, proposal_id: Identifier) -> Result { + self.require_protocol_version( + DECISION_PROPOSALS_CONTRACT_INITIAL_PROTOCOL_VERSION, + "the vote among a multiple choice proposal's choices", + ) + .await?; + self.contest_fund_to_join_vote_poll(&multiple_choice_proposal_vote_poll(proposal_id)) + .await + } + + /// The multiple choice proposal with id `proposal_id`, `None` when there is none. + pub async fn fetch_multiple_choice_proposal( + &self, + proposal_id: Identifier, + ) -> Result, Error> { + let contract = self.fetch_decision_proposals_contract().await?; + let query = DocumentQuery::new(contract, MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME)? + .with_document_id(&proposal_id); + Document::fetch(self, query).await + } + + /// One page of the multiple choice proposals of `owner_id`, by creation time. + /// [`DocumentsPage::after`] gives the next page. + pub async fn fetch_multiple_choice_proposals_by_owner( + &self, + owner_id: Identifier, + page: DocumentsPage, + ) -> Result { + let contract = self.fetch_decision_proposals_contract().await?; + Document::fetch_many( + self, + proposals_by_owner_query( + contract, + MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME, + owner_id, + page, + )?, + ) + .await + } + + /// One page of every multiple choice proposal, newest first. [`DocumentsPage::after`] + /// gives the next page. + pub async fn fetch_multiple_choice_proposals_by_created_at( + &self, + page: DocumentsPage, + ) -> Result { + let contract = self.fetch_decision_proposals_contract().await?; + Document::fetch_many( + self, + proposals_by_created_at_query( + contract, + MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME, + page, + )?, + ) + .await + } + + /// The vote among the choices of the proposal `proposal_id`: every choice with its tally + /// while the vote runs, and its outcome with every choice's final tally once it ended. A + /// proposal no choice was entered for has an empty vote. The choices are read in pages of + /// 100, so a vote of `n` choices costs `n / 100 + 1` proved queries. + pub async fn fetch_multiple_choice_proposal_vote( + &self, + proposal_id: Identifier, + ) -> Result { + let contract = self.fetch_decision_proposals_contract().await?; + let contenders = self + .fetch_contested_resource_vote_state( + &multiple_choice_proposal_vote_poll(proposal_id), + None, + ) + .await?; + MultipleChoiceProposalVote::from_contenders(&contract, contenders, self.version()) + } + + /// The choice the finished vote of the proposal `proposal_id` kept, stored as an ordinary + /// document under the identity that entered it. `None` while the vote runs, for a vote + /// that kept none of the choices, and for a proposal no choice was entered for. + pub async fn fetch_kept_choice( + &self, + proposal_id: Identifier, + ) -> Result, Error> { + let contract = self.fetch_decision_proposals_contract().await?; + Document::fetch(self, kept_choice_query(contract, proposal_id)?).await + } + + /// The answer the masternode `pro_tx_hash` gave in the vote among the choices of the + /// proposal `proposal_id`. `None` when the masternode has not voted in it, and once the + /// vote ended. + pub async fn fetch_masternode_multiple_choice_vote( + &self, + pro_tx_hash: Identifier, + proposal_id: Identifier, + ) -> Result, Error> { + self.require_protocol_version( + DECISION_PROPOSALS_CONTRACT_INITIAL_PROTOCOL_VERSION, + "the vote among a multiple choice proposal's choices", + ) + .await?; + let vote_poll_id = multiple_choice_proposal_vote_poll(proposal_id).unique_id()?; + let vote = Vote::fetch(self, VoteQuery::new(pro_tx_hash, vote_poll_id)).await?; + // The query starts at the poll's id, so it may answer with the masternode's vote on a + // later poll + Ok(vote.and_then(|vote| multiple_choice_vote_choice_of(&vote, proposal_id))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use dpp::data_contract::document_type::methods::DocumentTypeV0Methods; + use dpp::data_contract::validate_document::DataContractDocumentValidationMethodsV0; + use dpp::decision_proposal::multiple_choice::CHOICE_CONTEST_INDEX_NAME; + use dpp::decision_proposal::DECISION_PROPOSALS_CONTRACT_ID; + use dpp::document::serialization_traits::DocumentPlatformConversionMethodsV0; + use dpp::document::INITIAL_REVISION; + use dpp::system_data_contracts::{load_system_data_contract, SystemDataContract}; + use dpp::voting::contender_structs::{ + ContenderWithSerializedDocument, ContenderWithSerializedDocumentV0, + }; + use dpp::voting::vote_polls::contested_document_resource_vote_poll::ContestedDocumentResourceVotePoll; + use dpp::voting::votes::resource_vote::v0::ResourceVoteV0; + use dpp::voting::votes::resource_vote::ResourceVote; + use drive::config::DEFAULT_QUERY_LIMIT; + use drive::query::vote_poll_vote_state_query::{ + ContestedDocumentVotePollDriveQuery, ContestedDocumentVotePollDriveQueryResultType, + }; + use drive::query::DriveDocumentQuery; + + fn proposals_contract() -> Arc { + Arc::new( + load_system_data_contract( + SystemDataContract::DecisionProposals, + PlatformVersion::latest(), + ) + .expect("the decision proposals contract loads at the latest version"), + ) + } + + fn description_document() -> DescriptionDocument { + DescriptionDocument { + id: Identifier::from([5; 32]), + contract_id: Identifier::from([6; 32]), + document_type: "post".to_string(), + } + } + + fn input() -> MultipleChoiceProposalInput { + MultipleChoiceProposalInput { + title: "Which block size?".to_string(), + description_document: Some(description_document()), + url: Some("https://forum.dash.org/t/block-size".to_string()), + open: true, + } + } + + /// `document` with the system fields the platform fills in when it stores the create. + fn stored(document: &Document) -> Document { + let mut document = document.clone(); + document.set_created_at(Some(1_700_000_000_000)); + document.set_updated_at(Some(1_700_000_000_000)); + document + } + + fn built_proposal(input: &MultipleChoiceProposalInput) -> Document { + build_multiple_choice_proposal_document( + &proposals_contract(), + Identifier::from([3; 32]), + input, + Bytes32::new([9; 32]), + ) + .expect("builds") + .document + } + + fn built_choice(description: Option<&str>) -> Document { + build_choice_document( + &proposals_contract(), + Identifier::from([4; 32]), + &ChoiceInput { + proposal_id: Identifier::from([7; 32]), + title: "Double it".to_string(), + description: description.map(str::to_string), + }, + Bytes32::new([8; 32]), + ) + .expect("builds") + .document + } + + #[test] + fn should_build_a_multiple_choice_proposal_the_schema_accepts() { + let platform_version = PlatformVersion::latest(); + let contract = proposals_contract(); + let described = [ + input(), + MultipleChoiceProposalInput { + url: None, + ..input() + }, + MultipleChoiceProposalInput { + description_document: None, + open: false, + ..input() + }, + ]; + for input in described { + let built = build_multiple_choice_proposal_document( + &contract, + Identifier::from([3; 32]), + &input, + Bytes32::new([9; 32]), + ) + .expect("builds"); + assert_eq!(built.entropy, Bytes32::new([9; 32])); + assert_eq!(built.document.revision(), Some(INITIAL_REVISION)); + assert_eq!( + built.document.id(), + Document::generate_document_id_v0( + &DECISION_PROPOSALS_CONTRACT_ID, + &Identifier::from([3; 32]), + MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME, + &[9; 32], + ) + ); + let document = stored(&built.document); + let validation = contract + .validate_document( + MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME, + &document, + platform_version, + ) + .expect("validates"); + assert!(validation.is_valid(), "{input:?}: {:?}", validation.errors); + + // A multiple choice proposal opens no poll, so its create states no fund + let document_type = contract + .document_type_for_name(MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME) + .expect("the multiple choice proposal type"); + assert_eq!( + document_type + .prefunded_voting_balance_for_document(&built.document, platform_version) + .expect("active"), + None + ); + + let proposal = MultipleChoiceProposal::from_document(document.clone()).expect("reads"); + assert_eq!( + proposal, + MultipleChoiceProposal { + document, + title: input.title, + description_document: input.description_document, + url: input.url, + open: input.open, + } + ); + assert_eq!(proposal.owner_id(), Identifier::from([3; 32])); + } + } + + /// The builder writes what it is given: which descriptions Platform takes is the + /// contract's to say, so a proposal described nowhere is built and left to it. + #[test] + fn should_leave_out_the_description_document_and_url_not_given() { + let document = built_proposal(&MultipleChoiceProposalInput { + description_document: None, + url: None, + ..input() + }); + for property in [ + proposal_properties::DESCRIPTION_ID, + proposal_properties::DESCRIPTION_CONTRACT_ID, + proposal_properties::DESCRIPTION_DOCUMENT_TYPE, + proposal_properties::URL, + ] { + assert!(document.get(property).is_none(), "{property}"); + } + + let mut no_document_type = built_proposal(&input()); + no_document_type.remove(proposal_properties::DESCRIPTION_DOCUMENT_TYPE); + assert!(MultipleChoiceProposal::from_document(no_document_type).is_err()); + } + + fn edit_proposal( + proposal: &Document, + edit: MultipleChoiceProposalEdit, + ) -> Result { + build_multiple_choice_proposal_edit( + &DECISION_PROPOSALS_CONTRACT_ID, + MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME, + proposal, + &edit, + ) + } + + #[test] + fn should_edit_the_title_url_and_description_document_and_never_whether_it_is_open() { + let proposal = stored(&built_proposal(&input())); + + let retitled = edit_proposal( + &proposal, + MultipleChoiceProposalEdit { + title: Some("Which block size, then?".to_string()), + ..Default::default() + }, + ) + .expect("edits"); + assert_eq!(retitled.id(), proposal.id()); + assert_eq!(retitled.revision(), Some(INITIAL_REVISION + 1)); + let read = MultipleChoiceProposal::from_document(retitled).expect("reads"); + assert_eq!(read.title, "Which block size, then?"); + assert_eq!(read.description_document, Some(description_document())); + assert_eq!(read.url, input().url); + assert!(read.open); + + let elsewhere = DescriptionDocument { + id: Identifier::from([1; 32]), + contract_id: Identifier::from([2; 32]), + document_type: "note".to_string(), + }; + let pointed_elsewhere = edit_proposal( + &proposal, + MultipleChoiceProposalEdit { + description_document: Some(Some(elsewhere.clone())), + url: Some(None), + ..Default::default() + }, + ) + .expect("edits"); + let read = MultipleChoiceProposal::from_document(pointed_elsewhere).expect("reads"); + assert_eq!(read.description_document, Some(elsewhere)); + assert_eq!(read.url, None); + + // All three properties naming the description document go together + let at_its_url = edit_proposal( + &proposal, + MultipleChoiceProposalEdit { + description_document: Some(None), + ..Default::default() + }, + ) + .expect("edits"); + for property in [ + proposal_properties::DESCRIPTION_ID, + proposal_properties::DESCRIPTION_CONTRACT_ID, + proposal_properties::DESCRIPTION_DOCUMENT_TYPE, + ] { + assert!(at_its_url.get(property).is_none(), "{property}"); + } + let read = MultipleChoiceProposal::from_document(at_its_url).expect("reads"); + assert_eq!(read.description_document, None); + assert_eq!(read.url, input().url); + } + + #[test] + fn should_refuse_an_edit_that_changes_nothing_or_is_not_of_a_multiple_choice_proposal() { + let proposal = stored(&built_proposal(&input())); + let unchanged = [ + MultipleChoiceProposalEdit::default(), + MultipleChoiceProposalEdit { + title: Some(input().title), + description_document: Some(Some(description_document())), + url: Some(input().url), + }, + ]; + for edit in unchanged { + let error = edit_proposal(&proposal, edit.clone()).expect_err("changes nothing"); + assert!(error.to_string().contains("changes nothing"), "{edit:?}"); + } + + let edit = MultipleChoiceProposalEdit { + title: Some("Another question?".to_string()), + ..Default::default() + }; + for (data_contract_id, document_type_name) in [ + ( + Identifier::from([1; 32]), + MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME, + ), + (DECISION_PROPOSALS_CONTRACT_ID, "proposal"), + (DECISION_PROPOSALS_CONTRACT_ID, CHOICE_DOCUMENT_TYPE_NAME), + ] { + let error = build_multiple_choice_proposal_edit( + &data_contract_id, + document_type_name, + &proposal, + &edit, + ) + .expect_err("not a multiple choice proposal"); + assert!( + error + .to_string() + .contains("is not a multiple choice proposal"), + "{document_type_name} of {data_contract_id}: {error}" + ); + } + } + + #[test] + fn should_build_a_choice_the_schema_accepts_and_the_vote_of_its_proposal_takes() { + let platform_version = PlatformVersion::latest(); + let contract = proposals_contract(); + let document_type = contract + .document_type_for_name(CHOICE_DOCUMENT_TYPE_NAME) + .expect("the choice type"); + for description in [Some("Twice the size it is today."), None] { + let built = built_choice(description); + assert_eq!(built.revision(), None); + let mut document = built.clone(); + document.set_created_at(Some(1_700_000_000_000)); + let validation = contract + .validate_document(CHOICE_DOCUMENT_TYPE_NAME, &document, platform_version) + .expect("validates"); + assert!(validation.is_valid(), "{:?}", validation.errors); + + // The choice joins the vote its proposal's id names, and its create states the + // fund of that contest under the contested index + assert_eq!( + document_type + .contested_vote_poll_for_document(&built, platform_version) + .expect("active"), + Some(multiple_choice_proposal_vote_poll(Identifier::from( + [7; 32] + ))) + ); + let (fund_name, fund) = document_type + .prefunded_voting_balance_for_document(&built, platform_version) + .expect("active") + .expect("a contested create states a fund"); + assert_eq!(fund_name, CHOICE_CONTEST_INDEX_NAME); + assert_eq!( + fund, + multiple_choice_proposal_vote_poll(Identifier::from([7; 32])) + .required_vote_resolution_fund_to_join(0, platform_version) + ); + + let choice = Choice::from_document(document.clone()).expect("reads"); + assert_eq!( + choice, + Choice { + document, + proposal_id: Identifier::from([7; 32]), + title: "Double it".to_string(), + description: description.map(str::to_string), + } + ); + assert_eq!(choice.owner_id(), Identifier::from([4; 32])); + } + } + + /// A contender of the vote with `vote_tally` votes: the choice `document`, when the vote + /// still holds it. + fn contender( + choice_id: Identifier, + document: Option<&Document>, + vote_tally: u32, + ) -> (Identifier, ContenderWithSerializedDocument) { + let contract = proposals_contract(); + let document_type = contract + .document_type_for_name(CHOICE_DOCUMENT_TYPE_NAME) + .expect("the choice type"); + let serialized_document = document.map(|document| { + document + .serialize(document_type, &contract, PlatformVersion::latest()) + .expect("serializes") + }); + ( + choice_id, + ContenderWithSerializedDocumentV0 { + identity_id: choice_id, + serialized_document, + vote_tally: Some(vote_tally), + } + .into(), + ) + } + + #[test] + fn should_read_a_running_vote_with_its_choices_and_a_finished_one_with_its_tallies() { + let platform_version = PlatformVersion::latest(); + let contract = proposals_contract(); + let mut double = built_choice(Some("Twice the size it is today.")); + double.set_created_at(Some(1_700_000_000_000)); + let keep_id = Identifier::from([2; 32]); + + let running = MultipleChoiceProposalVote::from_contenders( + &contract, + Contenders { + winner: None, + contenders: BTreeMap::from([contender(double.id(), Some(&double), 12)]), + abstain_vote_tally: Some(3), + lock_vote_tally: Some(1), + }, + platform_version, + ) + .expect("reads"); + assert_eq!( + running, + MultipleChoiceProposalVote { + choices: BTreeMap::from([( + double.id(), + ChoiceInVote { + choice: Some(Choice::from_document(double.clone()).expect("reads")), + vote_tally: Some(12), + } + )]), + abstain_vote_tally: Some(3), + none_of_the_choices_vote_tally: Some(1), + winner: None, + } + ); + assert_eq!(running.kept_choice_id(), None); + + // Once the vote ended its record names the choices by id alone + let finished = MultipleChoiceProposalVote::from_contenders( + &contract, + Contenders { + winner: Some(( + ContestedDocumentVotePollWinnerInfo::WonByIdentity(double.id()), + BlockInfo::default(), + )), + contenders: BTreeMap::from([ + contender(double.id(), None, 12), + contender(keep_id, None, 4), + ]), + abstain_vote_tally: Some(3), + lock_vote_tally: Some(1), + }, + platform_version, + ) + .expect("reads"); + assert_eq!(finished.kept_choice_id(), Some(double.id())); + assert_eq!( + finished.choices[&keep_id], + ChoiceInVote { + choice: None, + vote_tally: Some(4), + } + ); + + let none_kept = MultipleChoiceProposalVote { + winner: Some(( + ContestedDocumentVotePollWinnerInfo::Locked, + BlockInfo::default(), + )), + ..Default::default() + }; + assert_eq!(none_kept.kept_choice_id(), None); + } + + /// The index `query` is served through, and that a proof of it can be verified: the path + /// query the verifier rebuilds constructs. + fn served_through(query: &DocumentQuery) -> String { + let platform_version = PlatformVersion::latest(); + let drive_query = DriveDocumentQuery::try_from(query).expect("converts"); + drive_query + .construct_path_query(None, platform_version) + .expect("a provable path query"); + drive_query + .find_best_index(platform_version) + .expect("an index serves it") + .name + .clone() + } + + #[test] + fn should_serve_every_listing_through_the_index_the_schema_declares_for_it() { + let contract = proposals_contract(); + let page = DocumentsPage { + limit: Some(20), + start_after: Some(Identifier::from([5; 32])), + }; + let by_owner = proposals_by_owner_query( + contract.clone(), + MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME, + Identifier::from([3; 32]), + page, + ) + .expect("builds"); + assert_eq!(served_through(&by_owner), "byOwner"); + assert_eq!(by_owner.limit, 20); + let by_created_at = proposals_by_created_at_query( + contract.clone(), + MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME, + DocumentsPage::default(), + ) + .expect("builds"); + assert_eq!(served_through(&by_created_at), "byCreatedAt"); + assert_eq!(by_created_at.limit, 100); + assert_eq!( + served_through( + &kept_choice_query(contract, Identifier::from([7; 32])).expect("builds") + ), + CHOICE_CONTEST_INDEX_NAME + ); + } + + #[test] + fn should_read_a_masternode_answer_only_from_a_vote_on_the_proposal() { + let proposal_id = Identifier::from([7; 32]); + let choice_id = Identifier::from([9; 32]); + for vote_choice in [ + MultipleChoiceVoteChoice::Choice(choice_id), + MultipleChoiceVoteChoice::Abstain, + MultipleChoiceVoteChoice::NoneOfTheChoices, + ] { + let vote = multiple_choice_proposal_vote(proposal_id, vote_choice); + assert_eq!( + multiple_choice_vote_choice_of(&vote, proposal_id), + Some(vote_choice) + ); + // The vote query starts at the poll's id and may answer with a later poll's vote + assert_eq!( + multiple_choice_vote_choice_of(&vote, Identifier::from([8; 32])), + None + ); + } + let on_another_contest = Vote::ResourceVote(ResourceVote::V0(ResourceVoteV0 { + vote_poll: VotePoll::ContestedDocumentResourceVotePoll( + ContestedDocumentResourceVotePoll { + index_name: "parentNameAndLabel".to_string(), + ..multiple_choice_proposal_vote_poll(proposal_id) + }, + ), + resource_vote_choice: ResourceVoteChoice::Abstain, + })); + assert_eq!( + multiple_choice_vote_choice_of(&on_another_contest, proposal_id), + None + ); + } + + /// The fund of a choice and the vote are read from the contest the proposal's id names. + #[tokio::test] + async fn should_read_the_choice_fund_and_the_vote_from_the_contest_of_the_proposal() { + let mut sdk = crate::SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .build() + .expect("a mock sdk"); + let proposal_id = Identifier::from([7; 32]); + let mut double = built_choice(Some("Twice the size it is today.")); + double.set_created_at(Some(1_700_000_000_000)); + let state = || Contenders { + winner: None, + contenders: BTreeMap::from([contender(double.id(), Some(&double), 12)]), + abstain_vote_tally: Some(3), + lock_vote_tally: Some(1), + }; + let contest_query = |result_type, with_other_tallies| ContestedDocumentVotePollDriveQuery { + vote_poll: multiple_choice_proposal_vote_poll(proposal_id), + result_type, + offset: None, + limit: Some(DEFAULT_QUERY_LIMIT), + start_at: None, + allow_include_locked_and_abstaining_vote_tally: with_other_tallies, + }; + sdk.mock() + .expect_fetch_many::<_, ContenderWithSerializedDocument, _, Contenders>( + contest_query( + ContestedDocumentVotePollDriveQueryResultType::VoteTally, + false, + ), + Some(state()), + ) + .await + .expect("registers the tallies"); + sdk.mock() + .expect_fetch_many::<_, ContenderWithSerializedDocument, _, Contenders>( + contest_query( + ContestedDocumentVotePollDriveQueryResultType::DocumentsAndVoteTally, + true, + ), + Some(state()), + ) + .await + .expect("registers the vote state"); + // One choice entered: the next pays the contest's fund, not yet doubled + assert_eq!( + sdk.choice_fund_to_join(proposal_id).await.expect("reads"), + 10_000_000_000 + ); + // The mock SDK holds no system contract, so the vote is read as + // `fetch_multiple_choice_proposal_vote` reads it, with the contract given + let contenders = sdk + .fetch_contested_resource_vote_state( + &multiple_choice_proposal_vote_poll(proposal_id), + None, + ) + .await + .expect("reads"); + let vote = MultipleChoiceProposalVote::from_contenders( + &proposals_contract(), + contenders, + sdk.version(), + ) + .expect("reads"); + assert_eq!(vote.choices.len(), 1); + assert_eq!( + vote.choices[&double.id()], + ChoiceInVote { + choice: Some(Choice::from_document(double.clone()).expect("reads")), + vote_tally: Some(12), + } + ); + assert_eq!(vote.none_of_the_choices_vote_tally, Some(1)); + } + + #[tokio::test] + async fn should_price_a_multiple_choice_proposal_by_the_fee_schedule() { + let sdk = crate::SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .build() + .expect("a mock sdk"); + assert_eq!( + sdk.multiple_choice_proposal_processing_fee() + .await + .expect("active"), + 20_000_000_000 + ); + } +} diff --git a/packages/rs-sdk/src/platform/documents/contest_fund.rs b/packages/rs-sdk/src/platform/documents/contest_fund.rs index c3e4a6ca644..cf96efdcc57 100644 --- a/packages/rs-sdk/src/platform/documents/contest_fund.rs +++ b/packages/rs-sdk/src/platform/documents/contest_fund.rs @@ -14,6 +14,7 @@ use dpp::document::DocumentV0Getters; use dpp::fee::Credits; use dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions; use dpp::voting::contender_structs::ContenderWithSerializedDocument; +use dpp::voting::vote_polls::contested_document_resource_vote_poll::ContestedDocumentResourceVotePoll; use drive::config::DEFAULT_QUERY_LIMIT; use drive::query::vote_poll_vote_state_query::{ ContestedDocumentVotePollDriveQuery, ContestedDocumentVotePollDriveQueryResultType, @@ -61,6 +62,17 @@ impl Sdk { return Ok(None); }; + let contest_fund = self.contest_fund_to_join_vote_poll(&vote_poll).await?; + Ok(Some((vote_poll.index_name, contest_fund))) + } + + /// The fund a create pays to join the contest `vote_poll` now: the contest's fund, doubled + /// once the contest holds 250 contenders and again for every 50 more. The contenders are + /// counted as [`Self::contest_fund_to_join`] says. + pub async fn contest_fund_to_join_vote_poll( + &self, + vote_poll: &ContestedDocumentResourceVotePoll, + ) -> Result { let mut contenders: u16 = 0; let mut start_at = None; loop { @@ -91,9 +103,7 @@ impl Sdk { } } - let contest_fund = - vote_poll.required_vote_resolution_fund_to_join(contenders, self.version()); - Ok(Some((vote_poll.index_name, contest_fund))) + Ok(vote_poll.required_vote_resolution_fund_to_join(contenders, self.version())) } } @@ -128,7 +138,6 @@ mod tests { use dpp::tests::fixtures::get_dpns_data_contract_fixture; use dpp::version::PlatformVersion; use dpp::voting::contender_structs::ContenderWithSerializedDocumentV0; - use dpp::voting::vote_polls::contested_document_resource_vote_poll::ContestedDocumentResourceVotePoll; use drive_proof_verifier::types::Contenders; use std::collections::BTreeMap; diff --git a/packages/rs-sdk/src/platform/documents/contest_vote_state.rs b/packages/rs-sdk/src/platform/documents/contest_vote_state.rs new file mode 100644 index 00000000000..5abbbb8c1cb --- /dev/null +++ b/packages/rs-sdk/src/platform/documents/contest_vote_state.rs @@ -0,0 +1,76 @@ +//! The whole state of a contest: every contender with its document and tally, read a page at a +//! time. + +use crate::platform::fetch_many::FetchMany; +use crate::{Error, Sdk}; +use dpp::voting::contender_structs::ContenderWithSerializedDocument; +use dpp::voting::vote_polls::contested_document_resource_vote_poll::ContestedDocumentResourceVotePoll; +use drive::config::DEFAULT_QUERY_LIMIT; +use drive::query::vote_poll_vote_state_query::{ + ContestedDocumentVotePollDriveQuery, ContestedDocumentVotePollDriveQueryResultType, +}; +use drive_proof_verifier::types::Contenders; + +impl Sdk { + /// The state of the contest `vote_poll`: its contenders with their documents and tallies, + /// the abstain and lock tallies, and the winner once the contest ended. + /// + /// Reads the contenders in the order of the ids the contest names them by, in pages of up + /// to 100 (the most Drive answers to one query) that each start after the last contender + /// read, until `limit` contenders are read or none are left. The abstain and lock tallies + /// and the winner come from the first page: Drive returns the tallies only to a query + /// without a start. + /// + /// `limit` is the most contenders returned; `None` returns every contender, and `Some(0)` + /// an empty state without a request. + pub async fn fetch_contested_resource_vote_state( + &self, + vote_poll: &ContestedDocumentResourceVotePoll, + limit: Option, + ) -> Result { + let mut state: Option = None; + let mut start_at = None; + loop { + let read = state.as_ref().map_or(0, |state| state.contenders.len()); + let page_limit = match limit { + Some(limit) => { + let left = (limit as usize).saturating_sub(read); + if left == 0 { + break; + } + left.min(DEFAULT_QUERY_LIMIT as usize) as u16 + } + None => DEFAULT_QUERY_LIMIT, + }; + let page = ContenderWithSerializedDocument::fetch_many( + self, + ContestedDocumentVotePollDriveQuery { + vote_poll: vote_poll.clone(), + result_type: + ContestedDocumentVotePollDriveQueryResultType::DocumentsAndVoteTally, + allow_include_locked_and_abstaining_vote_tally: true, + start_at, + limit: Some(page_limit), + offset: None, + }, + ) + .await?; + let page_len = page.contenders.len(); + let last = page.contenders.keys().last().copied(); + match state.as_mut() { + None => state = Some(page), + Some(state) => state.contenders.extend(page.contenders), + } + + // A short page is the last one + match last { + Some(last) if page_len >= page_limit as usize => { + start_at = Some((last.to_buffer(), false)); + } + _ => break, + } + } + + Ok(state.unwrap_or_default()) + } +} diff --git a/packages/rs-sdk/src/platform/documents/mod.rs b/packages/rs-sdk/src/platform/documents/mod.rs index 9f43abbaf99..c54aca3aeb5 100644 --- a/packages/rs-sdk/src/platform/documents/mod.rs +++ b/packages/rs-sdk/src/platform/documents/mod.rs @@ -13,6 +13,7 @@ pub use dash_platform_queries::documents::{ pub mod chained_document_query_sdk; pub mod contest_fund; +pub mod contest_vote_state; pub mod document_query_sdk; mod fetch_bindings; pub mod page; diff --git a/packages/rs-sdk/src/platform/dpns_usernames/contested_queries.rs b/packages/rs-sdk/src/platform/dpns_usernames/contested_queries.rs index 5de0a064e85..fa8d0427abb 100644 --- a/packages/rs-sdk/src/platform/dpns_usernames/contested_queries.rs +++ b/packages/rs-sdk/src/platform/dpns_usernames/contested_queries.rs @@ -151,50 +151,8 @@ impl Sdk { ], }; - let mut state: Option = None; - let mut start_at = None; - loop { - let read = state.as_ref().map_or(0, |state| state.contenders.len()); - let page_limit = match limit { - Some(limit) => { - let left = (limit as usize).saturating_sub(read); - if left == 0 { - break; - } - left.min(DEFAULT_QUERY_LIMIT as usize) as u16 - } - None => DEFAULT_QUERY_LIMIT, - }; - let page = ContenderWithSerializedDocument::fetch_many( - self, - ContestedDocumentVotePollDriveQuery { - vote_poll: vote_poll.clone(), - result_type: - ContestedDocumentVotePollDriveQueryResultType::DocumentsAndVoteTally, - allow_include_locked_and_abstaining_vote_tally: true, - start_at, - limit: Some(page_limit), - offset: None, - }, - ) - .await?; - let page_len = page.contenders.len(); - let last = page.contenders.keys().last().copied(); - match state.as_mut() { - None => state = Some(page), - Some(state) => state.contenders.extend(page.contenders), - } - - // A short page is the last one - match last { - Some(last) if page_len >= page_limit as usize => { - start_at = Some((last.to_buffer(), false)); - } - _ => break, - } - } - - Ok(state.unwrap_or_default()) + self.fetch_contested_resource_vote_state(&vote_poll, limit) + .await } /// Get voters who voted for a specific identity for a contested DPNS username diff --git a/packages/wasm-sdk/src/decision_proposals.rs b/packages/wasm-sdk/src/decision_proposals.rs index bb5395ba1c0..f48e358af13 100644 --- a/packages/wasm-sdk/src/decision_proposals.rs +++ b/packages/wasm-sdk/src/decision_proposals.rs @@ -2,6 +2,11 @@ //! masternodes. Thin bindings over `dash_sdk::platform::decision_proposals`: a proposal is a //! `proposal` document of the decision proposals system contract, created and edited like any //! document, and its poll is named by the proposal's id. +//! +//! A question with more than two answers is a multiple choice proposal: see +//! [`multiple_choice`]. + +pub mod multiple_choice; use crate::error::WasmSdkError; use crate::queries::utils::{documents_map, documents_page_of}; diff --git a/packages/wasm-sdk/src/decision_proposals/multiple_choice.rs b/packages/wasm-sdk/src/decision_proposals/multiple_choice.rs new file mode 100644 index 00000000000..5f0eb5edd77 --- /dev/null +++ b/packages/wasm-sdk/src/decision_proposals/multiple_choice.rs @@ -0,0 +1,639 @@ +//! Multiple choice proposals (protocol version 15): questions whose answers are the choices +//! entered for them. Thin bindings over +//! `dash_sdk::platform::decision_proposals::multiple_choice`: a proposal is a +//! `multipleChoiceProposal` document and an answer a `choice` document of the decision +//! proposals system contract, created like any document, and the choices contend in a +//! masternode vote named by the proposal's id. + +use super::{optional_string_option, page_of, string_option}; +use crate::error::WasmSdkError; +use crate::queries::utils::documents_map; +use crate::queries::voting::yes_no::{block_to_js, set}; +use crate::sdk::WasmSdk; +use crate::state_transitions::identity::MasternodeVoteSigning; +use dash_sdk::dpp::decision_proposal::multiple_choice::CHOICE_DOCUMENT_TYPE_NAME; +use dash_sdk::dpp::decision_proposal::{ + DECISION_PROPOSALS_CONTRACT_ID, MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME, +}; +use dash_sdk::dpp::document::Document; +use dash_sdk::dpp::voting::vote_polls::VotePoll; +use dash_sdk::platform::decision_proposals::multiple_choice::{ + build_multiple_choice_proposal_edit, multiple_choice_proposal_vote, + multiple_choice_proposal_vote_poll, ChoiceInput, DescriptionDocument, + MultipleChoiceProposalEdit, MultipleChoiceProposalInput, MultipleChoiceProposalVote, + MultipleChoiceVoteChoice, +}; +use dash_sdk::platform::Identifier; +use js_sys::{Map, Object, Reflect}; +use wasm_bindgen::prelude::wasm_bindgen; +use wasm_bindgen::JsValue; +use wasm_dpp2::data_contract::document::DocumentWasm; +use wasm_dpp2::error::WasmDppError; +use wasm_dpp2::identifier::{IdentifierLikeJs, IdentifierWasm}; +use wasm_dpp2::utils::{try_from_options_with, try_to_string}; +use wasm_dpp2::voting::vote::VoteWasm; +use wasm_dpp2::VotePollWasm; + +#[wasm_bindgen(typescript_custom_section)] +const MULTIPLE_CHOICE_PROPOSALS_TS: &'static str = r#" +/** + * The document a multiple choice proposal points at for what is being decided. Platform + * refuses one that is not of a moderated type the elected team of its contract may delete. + */ +export interface MultipleChoiceProposalDescriptionDocument { + /** The document. */ + id: IdentifierLike; + /** The contract it lives in, one whose moderators the masternodes elect. */ + contractId: IdentifierLike; + /** Its document type. */ + documentType: string; +} + +/** + * Options for `buildMultipleChoiceProposal`: a question put to the masternodes whose answers + * are the choices entered for it (protocol version 15). Its owner pays the multiple choice + * proposal processing fee (`getMultipleChoiceProposalProcessingFee`) on top of the fees. + * Platform refuses a proposal that gives neither a description document nor a url. + */ +export interface MultipleChoiceProposalOptions { + /** The proposer, the document's owner. */ + ownerId: IdentifierLike; + /** The question, in one line: 1 to 128 characters. */ + title: string; + /** The document saying what is being decided. */ + descriptionDocument?: MultipleChoiceProposalDescriptionDocument; + /** + * Where what is being decided is described, for a proposal that points at no description + * document, or where it is discussed, for one that does: a URI of at most 512 characters. + * Nothing on chain moderates it. + */ + url?: string; + /** + * Whether anyone may enter choices; only the proposal's owner may when it is false. It + * never changes. + */ + open: boolean; +} + +/** + * What a multiple choice proposal changes to (`buildMultipleChoiceProposalEdit`). A field left + * out keeps its value. Platform accepts the edit for two hours after the proposal is created; + * whether it is open never changes. + */ +export interface MultipleChoiceProposalEdit { + /** The new title. */ + title?: string; + /** The new description document; `null` leaves the proposal described at its url alone. */ + descriptionDocument?: MultipleChoiceProposalDescriptionDocument | null; + /** The new url; `null` removes it. */ + url?: string | null; +} + +/** + * Options for `buildMultipleChoiceProposalChoice`: an answer to a multiple choice proposal. + * Its owner pays the contest fund (`getMultipleChoiceProposalChoiceFund`) on top of the fees. + * Anyone enters choices for an open proposal, and only its owner for one that is not. + */ +export interface MultipleChoiceProposalChoiceOptions { + /** The identity entering the choice, the document's owner. */ + ownerId: IdentifierLike; + /** The proposal the choice answers. */ + proposalId: IdentifierLike; + /** The answer, in one line: 1 to 128 characters. */ + title: string; + /** What voting for the answer means: 1 to 4096 characters. */ + description?: string; +} + +/** + * A masternode's answer in the vote among a multiple choice proposal's choices: a choice, by + * its document id (not the id of the identity that entered it); `'abstain'`; or + * `'noneOfTheChoices'`, which keeps no choice when these votes outnumber the leading choice. + */ +export type MultipleChoiceVoteChoice = + | { choiceId: IdentifierLike } + | 'abstain' + | 'noneOfTheChoices'; + +/** The answer a masternode gave (`getMasternodeMultipleChoiceProposalVote`). */ +export type MasternodeMultipleChoiceVote = + | { choiceId: Identifier } + | 'abstain' + | 'noneOfTheChoices'; + +/** A choice in the vote among a multiple choice proposal's choices. */ +export interface MultipleChoiceProposalChoiceInVote { + /** + * The `choice` document, while the vote runs. Left out once it ended: the choices that were + * not kept are no longer in state, and `getMultipleChoiceProposalKeptChoice` reads the one + * that was. + */ + choice?: Document; + /** The votes towards the choice: so far while the vote runs, final once it ended. */ + voteTally?: number; +} + +/** The vote among a multiple choice proposal's choices (`getMultipleChoiceProposalVote`). */ +export interface MultipleChoiceProposalVote { + /** The choices by their base58 document ids. Empty for a proposal with no choice. */ + choices: Map; + /** The abstaining votes. */ + abstainVoteTally?: number; + /** The votes for none of the choices. */ + noneOfTheChoicesVoteTally?: number; + /** How the vote ended; left out while it runs. */ + result?: { + /** The document id of the choice that was kept; left out when none was. */ + keptChoiceId?: Identifier; + /** The block the vote ended at. */ + finalizationBlock: YesNoVotePollBlock; + }; +} + +/** Options for `multipleChoiceProposalVote`: a masternode's answer on a proposal. */ +export interface MultipleChoiceProposalVoteOptions { + /** + * The ProTxHash of the masternode: an Identifier, its 32 bytes, the hex Core's RPC shows, + * or base58. + */ + masternodeProTxHash: IdentifierLike; + /** The proposal. */ + proposalId: IdentifierLike; + /** The answer. */ + voteChoice: MultipleChoiceVoteChoice; + /** The masternode's voting public key. */ + votingKey: IdentityPublicKey; + /** Signer holding the private key of the voting key. */ + signer: IdentitySigner; + /** Optional settings for the broadcast. */ + settings?: PutSettings; +} +"#; + +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(typescript_type = "MultipleChoiceProposalOptions")] + pub type MultipleChoiceProposalOptionsJs; + + #[wasm_bindgen(typescript_type = "MultipleChoiceProposalEdit")] + pub type MultipleChoiceProposalEditJs; + + #[wasm_bindgen(typescript_type = "MultipleChoiceProposalChoiceOptions")] + pub type MultipleChoiceProposalChoiceOptionsJs; + + #[wasm_bindgen(typescript_type = "MultipleChoiceProposalVoteOptions")] + pub type MultipleChoiceProposalVoteOptionsJs; + + #[wasm_bindgen(typescript_type = "DecisionProposalsByOwnerQuery")] + pub type MultipleChoiceProposalsByOwnerQueryJs; + + #[wasm_bindgen(typescript_type = "DecisionProposalsPageQuery")] + pub type MultipleChoiceProposalsPageQueryJs; +} + +/// The description document `value` names. +fn description_document(value: &JsValue) -> Result { + Ok(DescriptionDocument { + id: IdentifierWasm::try_from_options(value, "id")?.into(), + contract_id: IdentifierWasm::try_from_options(value, "contractId")?.into(), + document_type: string_option(value, "documentType")?, + }) +} + +/// The property `property` of `options`: `None` when it is left out, `Some(None)` when it is +/// `null`, and what `read` makes of it otherwise. +fn nullable_option( + options: &JsValue, + property: &str, + read: impl FnOnce(&JsValue) -> Result, +) -> Result>, WasmSdkError> { + let value = Reflect::get(options, &JsValue::from_str(property)) + .map_err(|_| WasmSdkError::invalid_argument(format!("cannot read {property}")))?; + if value.is_undefined() { + Ok(None) + } else if value.is_null() { + Ok(Some(None)) + } else { + read(&value).map(|value| Some(Some(value))) + } +} + +/// The answer `property` of `options` gives: `{ choiceId }`, `'abstain'` or +/// `'noneOfTheChoices'`. +fn vote_choice_from_options( + options: &JsValue, + property: &str, +) -> Result { + let value = Reflect::get(options, &JsValue::from_str(property)) + .map_err(|_| WasmSdkError::invalid_argument(format!("cannot read {property}")))?; + match value.as_string().as_deref() { + Some("abstain") => Ok(MultipleChoiceVoteChoice::Abstain), + Some("noneOfTheChoices") => Ok(MultipleChoiceVoteChoice::NoneOfTheChoices), + Some(other) => Err(WasmSdkError::invalid_argument(format!( + "{property} on a multiple choice proposal is {{ choiceId }}, 'abstain' or \ + 'noneOfTheChoices', got '{other}'" + ))), + None if value.is_object() => Ok(MultipleChoiceVoteChoice::Choice( + IdentifierWasm::try_from_options(&value, "choiceId")?.into(), + )), + None => Err(WasmSdkError::invalid_argument(format!( + "{property} on a multiple choice proposal is {{ choiceId }}, 'abstain' or \ + 'noneOfTheChoices'" + ))), + } +} + +/// `vote_choice` as `getMasternodeMultipleChoiceProposalVote` returns it. +fn vote_choice_to_js(vote_choice: MultipleChoiceVoteChoice) -> Result { + Ok(match vote_choice { + MultipleChoiceVoteChoice::Choice(choice_id) => { + let object = Object::new(); + set(&object, "choiceId", IdentifierWasm::from(choice_id).into())?; + object.into() + } + MultipleChoiceVoteChoice::Abstain => JsValue::from_str("abstain"), + MultipleChoiceVoteChoice::NoneOfTheChoices => JsValue::from_str("noneOfTheChoices"), + }) +} + +fn document_wasm( + document: Document, + document_type_name: &str, + entropy: Option<[u8; 32]>, +) -> DocumentWasm { + DocumentWasm::new( + document, + DECISION_PROPOSALS_CONTRACT_ID, + document_type_name.to_string(), + entropy, + ) +} + +/// `vote` as `getMultipleChoiceProposalVote` returns it. +fn vote_to_js(vote: MultipleChoiceProposalVote) -> Result { + let kept_choice_id = vote.kept_choice_id(); + let choices = Map::new(); + for (choice_id, choice_in_vote) in vote.choices { + let entry = Object::new(); + if let Some(choice) = choice_in_vote.choice { + set( + &entry, + "choice", + document_wasm(choice.document, CHOICE_DOCUMENT_TYPE_NAME, None).into(), + )?; + } + if let Some(vote_tally) = choice_in_vote.vote_tally { + set(&entry, "voteTally", JsValue::from(vote_tally))?; + } + choices.set( + &IdentifierWasm::from(choice_id).to_base58().into(), + &entry.into(), + ); + } + let object = Object::new(); + set(&object, "choices", choices.into())?; + if let Some(abstain_vote_tally) = vote.abstain_vote_tally { + set( + &object, + "abstainVoteTally", + JsValue::from(abstain_vote_tally), + )?; + } + if let Some(none_of_the_choices_vote_tally) = vote.none_of_the_choices_vote_tally { + set( + &object, + "noneOfTheChoicesVoteTally", + JsValue::from(none_of_the_choices_vote_tally), + )?; + } + if let Some((_, finalization_block)) = &vote.winner { + let result = Object::new(); + if let Some(kept_choice_id) = kept_choice_id { + set( + &result, + "keptChoiceId", + IdentifierWasm::from(kept_choice_id).into(), + )?; + } + set( + &result, + "finalizationBlock", + block_to_js(finalization_block)?, + )?; + set(&object, "result", result.into())?; + } + Ok(object.into()) +} + +#[wasm_bindgen] +impl WasmSdk { + /// Builds a multiple choice proposal: a `multipleChoiceProposal` document of the decision + /// proposals contract with a fresh entropy, to create with `documentCreate`. Its owner + /// pays the multiple choice proposal processing fee on top of the fees; the create does + /// not state it. The id is final once `documentCreate` returns the stored document. + /// + /// @param options - The proposer, the question, where it is described and whether anyone + /// may enter choices. + /// @returns The proposal, ready for `documentCreate`. + #[wasm_bindgen(js_name = "buildMultipleChoiceProposal")] + pub async fn build_multiple_choice_proposal( + &self, + options: MultipleChoiceProposalOptionsJs, + ) -> Result { + let options: JsValue = options.into(); + let owner_id: Identifier = IdentifierWasm::try_from_options(&options, "ownerId")?.into(); + let input = MultipleChoiceProposalInput { + title: string_option(&options, "title")?, + description_document: nullable_option( + &options, + "descriptionDocument", + description_document, + )? + .flatten(), + url: optional_string_option(&options, "url")?, + open: try_from_options_with(&options, "open", |value| { + value + .as_bool() + .ok_or_else(|| WasmDppError::invalid_argument("'open' must be a boolean")) + })?, + }; + let built = self + .as_ref() + .build_multiple_choice_proposal(owner_id, &input) + .await?; + Ok(document_wasm( + built.document, + MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME, + Some(built.entropy.0), + )) + } + + /// A multiple choice proposal with what the edit changes and its next revision, to + /// replace with `documentReplace`. Platform accepts the edit for two hours after the + /// proposal is created. A document that is not a multiple choice proposal is refused. + /// + /// @param proposal - The proposal as stored, from `getMultipleChoiceProposal`. + /// @param edit - The new title, description document or url; `null` removes the + /// description document or the url. + /// @returns The edited proposal. + #[wasm_bindgen(js_name = "buildMultipleChoiceProposalEdit")] + pub fn build_multiple_choice_proposal_edit( + &self, + proposal: &DocumentWasm, + edit: MultipleChoiceProposalEditJs, + ) -> Result { + let edit: JsValue = edit.into(); + let edit = MultipleChoiceProposalEdit { + title: optional_string_option(&edit, "title")?, + description_document: nullable_option( + &edit, + "descriptionDocument", + description_document, + )?, + url: nullable_option(&edit, "url", |value| Ok(try_to_string(value, "url")?))?, + }; + let data_contract_id: Identifier = proposal.data_contract_id().into(); + let document: Document = proposal.clone().into(); + Ok(document_wasm( + build_multiple_choice_proposal_edit( + &data_contract_id, + &proposal.document_type_name(), + &document, + &edit, + )?, + MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME, + None, + )) + } + + /// Builds a choice: a `choice` document of the decision proposals contract with a fresh + /// entropy, to create with `documentCreate`, which states the contest fund. The first + /// choice opens the vote, and later ones join it while its join window is open. The id, + /// which a vote towards the choice carries, is final once `documentCreate` returns the + /// stored document. + /// + /// @param options - The identity entering the choice, the proposal and the answer. + /// @returns The choice, ready for `documentCreate`. + #[wasm_bindgen(js_name = "buildMultipleChoiceProposalChoice")] + pub async fn build_multiple_choice_proposal_choice( + &self, + options: MultipleChoiceProposalChoiceOptionsJs, + ) -> Result { + let options: JsValue = options.into(); + let owner_id: Identifier = IdentifierWasm::try_from_options(&options, "ownerId")?.into(); + let input = ChoiceInput { + proposal_id: IdentifierWasm::try_from_options(&options, "proposalId")?.into(), + title: string_option(&options, "title")?, + description: optional_string_option(&options, "description")?, + }; + let built = self.as_ref().build_choice(owner_id, &input).await?; + Ok(document_wasm( + built.document, + CHOICE_DOCUMENT_TYPE_NAME, + Some(built.entropy.0), + )) + } + + /// What creating one multiple choice proposal adds to the processing fee of its batch, in + /// credits. + #[wasm_bindgen(js_name = "getMultipleChoiceProposalProcessingFee")] + pub async fn get_multiple_choice_proposal_processing_fee(&self) -> Result { + Ok(self + .as_ref() + .multiple_choice_proposal_processing_fee() + .await?) + } + + /// The fund a choice entered now for a proposal pays, in credits: the contest's fund, + /// doubled once the vote holds 250 choices and again for every 50 more. + /// + /// @param proposalId - The proposal. + #[wasm_bindgen(js_name = "getMultipleChoiceProposalChoiceFund")] + pub async fn get_multiple_choice_proposal_choice_fund( + &self, + #[wasm_bindgen(js_name = "proposalId")] proposal_id: IdentifierLikeJs, + ) -> Result { + let proposal_id: Identifier = proposal_id.try_into()?; + Ok(self.as_ref().choice_fund_to_join(proposal_id).await?) + } + + /// A multiple choice proposal by id. + /// + /// @param proposalId - The proposal. + /// @returns The `multipleChoiceProposal` document, or undefined when there is none. + #[wasm_bindgen(js_name = "getMultipleChoiceProposal")] + pub async fn get_multiple_choice_proposal( + &self, + #[wasm_bindgen(js_name = "proposalId")] proposal_id: IdentifierLikeJs, + ) -> Result, WasmSdkError> { + let proposal_id: Identifier = proposal_id.try_into()?; + Ok(self + .as_ref() + .fetch_multiple_choice_proposal(proposal_id) + .await? + .map(|document| { + document_wasm(document, MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME, None) + })) + } + + /// One page of an identity's multiple choice proposals, by creation time. + /// + /// @returns The proposals by id; pass the last id as `startAfter` for the next page. + #[wasm_bindgen( + js_name = "getMultipleChoiceProposalsByOwner", + unchecked_return_type = "Map" + )] + pub async fn get_multiple_choice_proposals_by_owner( + &self, + query: MultipleChoiceProposalsByOwnerQueryJs, + ) -> Result { + let query: JsValue = query.into(); + if query.is_undefined() || query.is_null() { + return Err(WasmSdkError::invalid_argument("Query object is required")); + } + let owner_id: Identifier = IdentifierWasm::try_from_options(&query, "ownerId")?.into(); + let documents = self + .as_ref() + .fetch_multiple_choice_proposals_by_owner(owner_id, page_of(&query)?) + .await?; + Ok(documents_map( + documents, + DECISION_PROPOSALS_CONTRACT_ID, + MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME, + )) + } + + /// One page of every multiple choice proposal, newest first. + /// + /// @returns The proposals by id; pass the last id as `startAfter` for the next page. + #[wasm_bindgen( + js_name = "getMultipleChoiceProposalsByCreatedAt", + unchecked_return_type = "Map" + )] + pub async fn get_multiple_choice_proposals_by_created_at( + &self, + query: Option, + ) -> Result { + let query: JsValue = query.map(Into::into).unwrap_or(JsValue::UNDEFINED); + let documents = self + .as_ref() + .fetch_multiple_choice_proposals_by_created_at(page_of(&query)?) + .await?; + Ok(documents_map( + documents, + DECISION_PROPOSALS_CONTRACT_ID, + MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME, + )) + } + + /// The vote among a proposal's choices as a vote poll, which `masternodeVote`, + /// `getContestedResourceVoteState` and the other contested resource queries take. In it a + /// choice is named by its document id wherever they name a contender by an identity id. + /// + /// @param proposalId - The proposal. + #[wasm_bindgen(js_name = "getMultipleChoiceProposalVotePoll")] + pub fn get_multiple_choice_proposal_vote_poll( + &self, + #[wasm_bindgen(js_name = "proposalId")] proposal_id: IdentifierLikeJs, + ) -> Result { + let proposal_id: Identifier = proposal_id.try_into()?; + Ok( + VotePoll::ContestedDocumentResourceVotePoll(multiple_choice_proposal_vote_poll( + proposal_id, + )) + .into(), + ) + } + + /// The vote among a proposal's choices: every choice with its tally while the vote runs, + /// and its result with every choice's final tally once it ended. A proposal no choice was + /// entered for has no choices. + /// + /// # Example + /// ```javascript + /// const vote = await sdk.getMultipleChoiceProposalVote(proposalId); + /// for (const [choiceId, { choice, voteTally }] of vote.choices) { + /// console.log(choiceId, choice?.properties.title, voteTally); + /// } + /// ``` + #[wasm_bindgen( + js_name = "getMultipleChoiceProposalVote", + unchecked_return_type = "MultipleChoiceProposalVote" + )] + pub async fn get_multiple_choice_proposal_vote( + &self, + #[wasm_bindgen(js_name = "proposalId")] proposal_id: IdentifierLikeJs, + ) -> Result { + let proposal_id: Identifier = proposal_id.try_into()?; + let vote = self + .as_ref() + .fetch_multiple_choice_proposal_vote(proposal_id) + .await?; + vote_to_js(vote) + } + + /// The choice the finished vote of a proposal kept, an ordinary document of the identity + /// that entered it. Undefined while the vote runs, when it kept none of the choices, and + /// for a proposal no choice was entered for. + /// + /// @param proposalId - The proposal. + #[wasm_bindgen(js_name = "getMultipleChoiceProposalKeptChoice")] + pub async fn get_multiple_choice_proposal_kept_choice( + &self, + #[wasm_bindgen(js_name = "proposalId")] proposal_id: IdentifierLikeJs, + ) -> Result, WasmSdkError> { + let proposal_id: Identifier = proposal_id.try_into()?; + Ok(self + .as_ref() + .fetch_kept_choice(proposal_id) + .await? + .map(|document| document_wasm(document, CHOICE_DOCUMENT_TYPE_NAME, None))) + } + + /// The answer a masternode gave in the vote among a proposal's choices. Undefined when + /// the masternode has not voted in it, and once the vote ended. + #[wasm_bindgen( + js_name = "getMasternodeMultipleChoiceProposalVote", + unchecked_return_type = "MasternodeMultipleChoiceVote | undefined" + )] + pub async fn get_masternode_multiple_choice_proposal_vote( + &self, + #[wasm_bindgen(js_name = "proTxHash")] pro_tx_hash: IdentifierLikeJs, + #[wasm_bindgen(js_name = "proposalId")] proposal_id: IdentifierLikeJs, + ) -> Result { + let pro_tx_hash: Identifier = pro_tx_hash + .try_into() + .map_err(|err| WasmSdkError::invalid_argument(format!("Invalid proTxHash: {err}")))?; + let proposal_id: Identifier = proposal_id.try_into()?; + match self + .as_ref() + .fetch_masternode_multiple_choice_vote(pro_tx_hash, proposal_id) + .await? + { + Some(vote_choice) => vote_choice_to_js(vote_choice), + None => Ok(JsValue::UNDEFINED), + } + } + + /// Votes in the vote among a proposal's choices for a masternode: builds the vote, signs + /// it with the voting key, broadcasts it and waits for the block that records it. Every + /// option is read before anything reaches the network. + /// + /// @param options - The masternode, the proposal, the answer, the voting key and signer. + /// @returns The vote as Platform recorded it. + #[wasm_bindgen(js_name = "multipleChoiceProposalVote")] + pub async fn multiple_choice_proposal_vote( + &self, + options: MultipleChoiceProposalVoteOptionsJs, + ) -> Result { + let options: JsValue = options.into(); + let pro_tx_hash: Identifier = + IdentifierWasm::try_from_options(&options, "masternodeProTxHash")?.into(); + let proposal_id: Identifier = + IdentifierWasm::try_from_options(&options, "proposalId")?.into(); + let vote_choice = vote_choice_from_options(&options, "voteChoice")?; + let signing = MasternodeVoteSigning::from_options(&options)?; + let vote = multiple_choice_proposal_vote(proposal_id, vote_choice); + self.put_masternode_vote(pro_tx_hash, vote, signing).await + } +} diff --git a/packages/wasm-sdk/src/queries/voting/yes_no.rs b/packages/wasm-sdk/src/queries/voting/yes_no.rs index 76450594be1..3eee76d7e61 100644 --- a/packages/wasm-sdk/src/queries/voting/yes_no.rs +++ b/packages/wasm-sdk/src/queries/voting/yes_no.rs @@ -69,7 +69,7 @@ export interface MasternodeYesNoVote { "#; /// Sets `key` on `object`. -fn set(object: &Object, key: &str, value: JsValue) -> Result<(), WasmSdkError> { +pub(crate) fn set(object: &Object, key: &str, value: JsValue) -> Result<(), WasmSdkError> { Reflect::set(object, &key.into(), &value) .map(|_| ()) .map_err(|_| WasmSdkError::generic(format!("failed to set `{key}`"))) @@ -85,7 +85,7 @@ fn yes_no_vote_poll(vote_poll: &VotePollWasm) -> Result Result { +pub(crate) fn block_to_js(block: &BlockInfo) -> Result { let object = Object::new(); set(&object, "height", BigInt::from(block.height).into())?; set(&object, "coreHeight", JsValue::from(block.core_height))?; diff --git a/packages/wasm-sdk/tests/unit/multiple-choice-proposals.spec.ts b/packages/wasm-sdk/tests/unit/multiple-choice-proposals.spec.ts new file mode 100644 index 00000000000..983bf227ba3 --- /dev/null +++ b/packages/wasm-sdk/tests/unit/multiple-choice-proposals.spec.ts @@ -0,0 +1,174 @@ +/** + * Multiple choice proposals (protocol version 15). `buildMultipleChoiceProposalEdit` and + * `getMultipleChoiceProposalVotePoll` need no network. The other calls parse every option + * before anything is fetched, so a call whose only fault is one option fails on that option: + * the options before it were accepted, and nothing reached the network. + */ +import { expect } from './helpers/chai.ts'; +import init, * as sdk from '../../dist/sdk.compressed.js'; + +const DECISION_PROPOSALS_CONTRACT_ID = '3iNyoNwjCTkb7XS3RHyWUtLx7pgC6AFAEQNNDHzxqngF'; +const ownerId = '5mjGWa9mruHnLBht3ntBi8CZ6sNk3hZZsQMgTvgQobjS'; +const proposalId = '4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF'; +const descriptionId = 'GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec'; +const proTxHashHex = 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2'; + +async function rejectionOf(promise: Promise): Promise { + try { + await promise; + } catch (e) { + return e as Error; + } + throw new Error('expected the call to be refused'); +} + +function refusalOf(call: () => unknown): Error { + try { + call(); + } catch (e) { + return e as Error; + } + throw new Error('expected the call to be refused'); +} + +describe('multiple choice proposals', () => { + let client: sdk.WasmSdk; + + before(async () => { + await init(); + client = await sdk.WasmSdkBuilder.testnet().build(); + }); + + after(() => { + client?.free(); + }); + + function storedProposal(documentTypeName = 'multipleChoiceProposal'): sdk.Document { + return new sdk.Document({ + properties: { + title: 'Which block size?', + descriptionId: new Uint8Array(32).fill(5), + descriptionContractId: new Uint8Array(32).fill(6), + descriptionDocumentType: 'post', + url: 'https://forum.dash.org/t/block-size', + open: true, + }, + documentTypeName, + dataContractId: DECISION_PROPOSALS_CONTRACT_ID, + ownerId, + revision: BigInt(1), + entropy: new Uint8Array(32).fill(3), + }); + } + + describe('buildMultipleChoiceProposalEdit()', () => { + it('should give the proposal a new title and its next revision', () => { + const proposal = storedProposal(); + const edited = client.buildMultipleChoiceProposalEdit(proposal, { title: 'Which block size, then?' }); + expect(edited.id.toBase58()).to.equal(proposal.id.toBase58()); + expect(edited.revision).to.equal(BigInt(2)); + const properties = edited.properties as Record; + expect(properties.title).to.equal('Which block size, then?'); + expect(properties.url).to.equal('https://forum.dash.org/t/block-size'); + expect(properties.descriptionDocumentType).to.equal('post'); + expect(properties.open).to.equal(true); + expect(edited.documentTypeName).to.equal('multipleChoiceProposal'); + }); + + it('should remove all three description properties when the edit sets the document to null', () => { + const edited = client.buildMultipleChoiceProposalEdit(storedProposal(), { descriptionDocument: null }); + const properties = edited.properties as Record; + expect(properties).to.not.have.property('descriptionId'); + expect(properties).to.not.have.property('descriptionContractId'); + expect(properties).to.not.have.property('descriptionDocumentType'); + expect(properties.url).to.equal('https://forum.dash.org/t/block-size'); + }); + + it('should point the proposal at another description document and remove the url', () => { + const edited = client.buildMultipleChoiceProposalEdit(storedProposal(), { + descriptionDocument: { id: proposalId, contractId: descriptionId, documentType: 'note' }, + url: null, + }); + const properties = edited.properties as Record; + expect(properties.descriptionDocumentType).to.equal('note'); + expect(properties).to.not.have.property('url'); + }); + + it('should refuse an edit that changes nothing', () => { + const error = refusalOf(() => client.buildMultipleChoiceProposalEdit(storedProposal(), {})); + expect(error.message).to.match(/changes nothing/); + }); + + it('should refuse a document that is not a multiple choice proposal', () => { + const error = refusalOf(() => client.buildMultipleChoiceProposalEdit( + storedProposal('proposal'), + { title: 'Another question?' }, + )); + expect(error.message).to.match(/is not a multiple choice proposal/); + }); + }); + + describe('getMultipleChoiceProposalVotePoll()', () => { + it('should name the contest of the choice type at the proposal', () => { + const votePoll = client.getMultipleChoiceProposalVotePoll(proposalId); + const json = votePoll.toJSON() as Record; + expect(JSON.stringify(json)).to.contain('byProposal'); + expect(JSON.stringify(json)).to.contain(DECISION_PROPOSALS_CONTRACT_ID); + }); + }); + + describe('listings', () => { + it('should accept Identifier instances as the owner and the cursor', async () => { + const error = await rejectionOf(client.getMultipleChoiceProposalsByOwner({ + ownerId: new sdk.Identifier(ownerId), + startAfter: new sdk.Identifier(ownerId), + limit: 1.5, + })); + expect(error.message).to.match(/'limit' must be an integer/); + }); + }); + + describe('buildMultipleChoiceProposal()', () => { + it('should refuse a description document that names no contract', async () => { + const error = await rejectionOf(client.buildMultipleChoiceProposal({ + ownerId, + title: 'Which block size?', + descriptionDocument: { id: descriptionId, documentType: 'post' } as never, + open: true, + })); + expect(error.message).to.match(/contractId/); + }); + + it('should refuse an open that is not a boolean', async () => { + const error = await rejectionOf(client.buildMultipleChoiceProposal({ + ownerId, + title: 'Which block size?', + url: 'https://forum.dash.org/t/block-size', + open: 'yes' as never, + })); + expect(error.message).to.match(/'open' must be a boolean/); + }); + }); + + describe('multipleChoiceProposalVote()', () => { + it('should refuse an answer that is neither a choice, abstain nor none of the choices', async () => { + const error = await rejectionOf(client.multipleChoiceProposalVote({ + masternodeProTxHash: proTxHashHex, + proposalId, + voteChoice: 'lock' as never, + } as never)); + expect(error.message).to.match(/'abstain' or 'noneOfTheChoices', got 'lock'/); + }); + + [{ choiceId: descriptionId }, 'abstain', 'noneOfTheChoices'].forEach((voteChoice) => { + it(`should accept ${JSON.stringify(voteChoice)} and read the voting key before the network`, async () => { + const error = await rejectionOf(client.multipleChoiceProposalVote({ + masternodeProTxHash: proTxHashHex, + proposalId, + voteChoice, + } as never)); + expect(error.message).to.match(/'votingKey' is required/); + }); + }); + }); +}); From f0621c6cd5028bc8a6a05d9e6b722458f4d2466f Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Fri, 13 Nov 2026 11:28:57 +0700 Subject: [PATCH 2/3] fix(sdk): cut a finished contest's vote state to the limit asked for A contest that ended answers a vote state page with every contender of its record, whatever limit the page asked for, so fetch_contested_resource_vote_state (and get_contested_dpns_vote_state, which calls it) returned more contenders than `limit`. The contenders are now cut to the limit, the first in id order kept; the winner and the abstain and lock tallies are returned whole. The multiple choice vote reader moves each decoded choice document instead of cloning it, and no longer copies the document type. New wasm binding tests cover the JavaScript shape of the vote state (no choice, running, kept a choice, kept none) and the vote choice round trip. Co-Authored-By: Claude Fable 5.2 --- .../decision_proposals/multiple_choice.rs | 15 +- .../platform/documents/contest_vote_state.rs | 101 ++++++++- .../src/decision_proposals/multiple_choice.rs | 214 ++++++++++++++++++ 3 files changed, 322 insertions(+), 8 deletions(-) diff --git a/packages/rs-sdk/src/platform/decision_proposals/multiple_choice.rs b/packages/rs-sdk/src/platform/decision_proposals/multiple_choice.rs index 2dda70d0be1..9e6b69addbc 100644 --- a/packages/rs-sdk/src/platform/decision_proposals/multiple_choice.rs +++ b/packages/rs-sdk/src/platform/decision_proposals/multiple_choice.rs @@ -267,15 +267,18 @@ impl MultipleChoiceProposalVote { .document_type_for_name(CHOICE_DOCUMENT_TYPE_NAME) .map_err(|e| Error::Protocol(e.into()))?; let choices = contenders - .to_contenders(&document_type.to_owned_document_type(), platform_version)? - .into_iter() + .contenders + .iter() .map(|(choice_id, contender)| { - let (document, vote_tally) = (contender.document().clone(), contender.vote_tally()); + let mut contender = contender.try_to_contender(document_type, platform_version)?; Ok(( - choice_id, + *choice_id, ChoiceInVote { - choice: document.map(Choice::from_document).transpose()?, - vote_tally, + choice: contender + .take_document() + .map(Choice::from_document) + .transpose()?, + vote_tally: contender.vote_tally(), }, )) }) diff --git a/packages/rs-sdk/src/platform/documents/contest_vote_state.rs b/packages/rs-sdk/src/platform/documents/contest_vote_state.rs index 5abbbb8c1cb..655ee2d054f 100644 --- a/packages/rs-sdk/src/platform/documents/contest_vote_state.rs +++ b/packages/rs-sdk/src/platform/documents/contest_vote_state.rs @@ -22,7 +22,9 @@ impl Sdk { /// without a start. /// /// `limit` is the most contenders returned; `None` returns every contender, and `Some(0)` - /// an empty state without a request. + /// an empty state without a request. A contest that ended answers with every contender of + /// its record whatever a page asks for, so its contenders are cut to `limit` here, the + /// first in id order kept; its winner and its abstain and lock tallies are returned whole. pub async fn fetch_contested_resource_vote_state( &self, vote_poll: &ContestedDocumentResourceVotePoll, @@ -71,6 +73,101 @@ impl Sdk { } } - Ok(state.unwrap_or_default()) + let mut state = state.unwrap_or_default(); + if let Some(limit) = limit { + while state.contenders.len() > limit as usize { + state.contenders.pop_last(); + } + } + Ok(state) + } +} + +#[cfg(all(test, feature = "mocks"))] +mod tests { + use super::*; + use crate::SdkBuilder; + use dpp::block::block_info::BlockInfo; + use dpp::platform_value::{Identifier, Value}; + use dpp::version::PlatformVersion; + use dpp::voting::contender_structs::ContenderWithSerializedDocumentV0; + use dpp::voting::vote_info_storage::contested_document_vote_poll_winner_info::ContestedDocumentVotePollWinnerInfo; + use std::collections::BTreeMap; + + /// A contest that ended answers a page with every contender of its record, however few + /// the page asked for: the state holds `limit` of them, with the winner and the abstain + /// and lock tallies of the whole contest. + #[tokio::test] + async fn should_return_at_most_the_limit_of_contenders_of_a_contest_that_ended() { + let mut sdk = SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .build() + .expect("a mock sdk"); + let vote_poll = ContestedDocumentResourceVotePoll { + contract_id: Identifier::new([7; 32]), + document_type_name: "domain".to_string(), + index_name: "parentNameAndLabel".to_string(), + index_values: vec![ + Value::Text("dash".to_string()), + Value::Text("quantum".to_string()), + ], + }; + let contender = |n: u8, vote_tally: u32| { + let identity_id = Identifier::new([n; 32]); + ( + identity_id, + ContenderWithSerializedDocument::V0(ContenderWithSerializedDocumentV0 { + identity_id, + serialized_document: None, + vote_tally: Some(vote_tally), + }), + ) + }; + let winner = Some(( + ContestedDocumentVotePollWinnerInfo::WonByIdentity(Identifier::new([3; 32])), + BlockInfo::default(), + )); + for limit in [1u16, 2] { + sdk.mock() + .expect_fetch_many::<_, ContenderWithSerializedDocument, _, Contenders>( + ContestedDocumentVotePollDriveQuery { + vote_poll: vote_poll.clone(), + result_type: + ContestedDocumentVotePollDriveQueryResultType::DocumentsAndVoteTally, + allow_include_locked_and_abstaining_vote_tally: true, + start_at: None, + limit: Some(limit), + offset: None, + }, + Some(Contenders { + winner, + contenders: BTreeMap::from([ + contender(1, 4), + contender(2, 5), + contender(3, 12), + ]), + abstain_vote_tally: Some(6), + lock_vote_tally: Some(2), + }), + ) + .await + .expect("registers the page"); + } + for limit in [1u32, 2] { + let state = sdk + .fetch_contested_resource_vote_state(&vote_poll, Some(limit)) + .await + .expect("reads"); + assert_eq!( + state.contenders.keys().copied().collect::>(), + (1..=limit as u8) + .map(|n| Identifier::new([n; 32])) + .collect::>(), + "limit {limit}" + ); + assert_eq!(state.winner, winner); + assert_eq!(state.abstain_vote_tally, Some(6)); + assert_eq!(state.lock_vote_tally, Some(2)); + } } } diff --git a/packages/wasm-sdk/src/decision_proposals/multiple_choice.rs b/packages/wasm-sdk/src/decision_proposals/multiple_choice.rs index 5f0eb5edd77..59a9d654fe8 100644 --- a/packages/wasm-sdk/src/decision_proposals/multiple_choice.rs +++ b/packages/wasm-sdk/src/decision_proposals/multiple_choice.rs @@ -637,3 +637,217 @@ impl WasmSdk { self.put_masternode_vote(pro_tx_hash, vote, signing).await } } + +#[cfg(all(test, target_arch = "wasm32"))] +mod binding_tests { + use super::*; + use dash_sdk::dpp::block::block_info::BlockInfo; + use dash_sdk::dpp::decision_proposal::multiple_choice::choice_properties; + use dash_sdk::dpp::document::DocumentV0; + use dash_sdk::dpp::platform_value::Value; + use dash_sdk::dpp::voting::vote_info_storage::contested_document_vote_poll_winner_info::ContestedDocumentVotePollWinnerInfo; + use dash_sdk::platform::decision_proposals::multiple_choice::{Choice, ChoiceInVote}; + use std::collections::BTreeMap; + use wasm_bindgen::JsCast; + use wasm_bindgen_test::wasm_bindgen_test; + + fn get(value: &JsValue, key: &str) -> JsValue { + Reflect::get(value, &JsValue::from_str(key)).expect("a property") + } + + fn base58(id: Identifier) -> String { + IdentifierWasm::from(id).to_base58() + } + + /// The choice `title` of the proposal `[7; 32]`, with the document id `id`. + fn choice(id: Identifier, title: &str) -> Choice { + Choice::from_document( + DocumentV0 { + id, + owner_id: Identifier::new([4; 32]), + properties: BTreeMap::from([ + ( + choice_properties::PROPOSAL_ID.to_string(), + Value::Identifier([7; 32]), + ), + ( + choice_properties::TITLE.to_string(), + Value::Text(title.to_string()), + ), + ]), + ..Default::default() + } + .into(), + ) + .expect("a choice") + } + + fn choices_of(vote: &JsValue) -> Map { + let choices = get(vote, "choices"); + assert!(choices.is_instance_of::(), "a Map: {choices:?}"); + choices.unchecked_into() + } + + fn finalization_block() -> BlockInfo { + BlockInfo { + time_ms: 1_700_000_000_000, + height: 7, + core_height: 5, + ..Default::default() + } + } + + #[wasm_bindgen_test] + fn should_give_a_vote_with_no_choice_an_empty_map_and_nothing_else() { + let vote = vote_to_js(MultipleChoiceProposalVote::default()).expect("converts"); + assert_eq!(choices_of(&vote).size(), 0); + for property in ["abstainVoteTally", "noneOfTheChoicesVoteTally", "result"] { + assert!(get(&vote, property).is_undefined(), "{property}"); + } + } + + #[wasm_bindgen_test] + fn should_give_a_running_vote_its_choices_by_document_id_with_their_tallies() { + let double_id = Identifier::new([1; 32]); + let keep_id = Identifier::new([2; 32]); + let vote = vote_to_js(MultipleChoiceProposalVote { + choices: BTreeMap::from([ + ( + double_id, + ChoiceInVote { + choice: Some(choice(double_id, "Double it")), + vote_tally: Some(12), + }, + ), + ( + keep_id, + ChoiceInVote { + choice: Some(choice(keep_id, "Keep it")), + vote_tally: None, + }, + ), + ]), + abstain_vote_tally: Some(3), + none_of_the_choices_vote_tally: Some(1), + winner: None, + }) + .expect("converts"); + + let choices = choices_of(&vote); + assert_eq!(choices.size(), 2); + let double = choices.get(&base58(double_id).into()); + assert_eq!(get(&double, "voteTally").as_f64(), Some(12.0)); + let document = get(&double, "choice"); + assert_eq!( + get(&document, "documentTypeName").as_string().as_deref(), + Some(CHOICE_DOCUMENT_TYPE_NAME) + ); + assert_eq!( + IdentifierWasm::try_from_options(&document, "id") + .expect("an id") + .to_base58(), + base58(double_id) + ); + assert_eq!( + IdentifierWasm::try_from_options(&document, "dataContractId") + .expect("a contract id") + .to_base58(), + base58(DECISION_PROPOSALS_CONTRACT_ID) + ); + let keep = choices.get(&base58(keep_id).into()); + assert!(!get(&keep, "choice").is_undefined()); + assert!(get(&keep, "voteTally").is_undefined()); + + assert_eq!(get(&vote, "abstainVoteTally").as_f64(), Some(3.0)); + assert_eq!(get(&vote, "noneOfTheChoicesVoteTally").as_f64(), Some(1.0)); + assert!(get(&vote, "result").is_undefined()); + } + + #[wasm_bindgen_test] + fn should_give_a_vote_that_kept_a_choice_its_id_and_every_final_tally() { + let double_id = Identifier::new([1; 32]); + let keep_id = Identifier::new([2; 32]); + let tally = |vote_tally| ChoiceInVote { + choice: None, + vote_tally: Some(vote_tally), + }; + let vote = vote_to_js(MultipleChoiceProposalVote { + choices: BTreeMap::from([(double_id, tally(12)), (keep_id, tally(4))]), + abstain_vote_tally: Some(3), + none_of_the_choices_vote_tally: Some(1), + winner: Some(( + ContestedDocumentVotePollWinnerInfo::WonByIdentity(double_id), + finalization_block(), + )), + }) + .expect("converts"); + + let choices = choices_of(&vote); + for (choice_id, vote_tally) in [(double_id, 12.0), (keep_id, 4.0)] { + let entry = choices.get(&base58(choice_id).into()); + assert!(get(&entry, "choice").is_undefined()); + assert_eq!(get(&entry, "voteTally").as_f64(), Some(vote_tally)); + } + let result = get(&vote, "result"); + assert_eq!( + IdentifierWasm::try_from_options(&result, "keptChoiceId") + .expect("the kept choice") + .to_base58(), + base58(double_id) + ); + let block = get(&result, "finalizationBlock"); + assert_eq!(get(&block, "height"), JsValue::from(7u64)); + assert_eq!(get(&block, "coreHeight").as_f64(), Some(5.0)); + assert_eq!(get(&block, "timeMs"), JsValue::from(1_700_000_000_000u64)); + } + + #[wasm_bindgen_test] + fn should_give_a_vote_that_kept_no_choice_a_result_without_a_kept_choice() { + let vote = vote_to_js(MultipleChoiceProposalVote { + choices: BTreeMap::from([( + Identifier::new([1; 32]), + ChoiceInVote { + choice: None, + vote_tally: Some(2), + }, + )]), + abstain_vote_tally: Some(0), + none_of_the_choices_vote_tally: Some(9), + winner: Some(( + ContestedDocumentVotePollWinnerInfo::Locked, + finalization_block(), + )), + }) + .expect("converts"); + + let result = get(&vote, "result"); + assert!(result.is_object()); + assert!(get(&result, "keptChoiceId").is_undefined()); + assert!(get(&result, "finalizationBlock").is_object()); + assert_eq!(get(&vote, "abstainVoteTally").as_f64(), Some(0.0)); + assert_eq!(get(&vote, "noneOfTheChoicesVoteTally").as_f64(), Some(9.0)); + } + + #[wasm_bindgen_test] + fn should_read_a_masternode_answer_back_as_it_is_given() { + let choice_id = Identifier::new([1; 32]); + let options = |vote_choice: JsValue| { + let options = Object::new(); + set(&options, "voteChoice", vote_choice).expect("sets"); + JsValue::from(options) + }; + for vote_choice in [ + MultipleChoiceVoteChoice::Choice(choice_id), + MultipleChoiceVoteChoice::Abstain, + MultipleChoiceVoteChoice::NoneOfTheChoices, + ] { + let given = vote_choice_to_js(vote_choice).expect("converts"); + assert_eq!( + vote_choice_from_options(&options(given), "voteChoice").expect("reads"), + vote_choice + ); + } + assert!(vote_choice_from_options(&options("lock".into()), "voteChoice").is_err()); + assert!(vote_choice_from_options(&options(JsValue::from(1)), "voteChoice").is_err()); + } +} From 966c1a545a368256e087a1b6b1d56ed3c4079bb5 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Fri, 13 Nov 2026 16:34:11 +0700 Subject: [PATCH 3/3] fix(sdk): read a finished contest's vote state in one page A contest that ended answers its first vote state page with its whole record. The read loop took a full page as a sign of more and asked for the next one, which a finished contest answers empty: one proved query for nothing. The loop now stops at a page that names a winner. fetch_kept_choice stays one document query through the byProposal index, and its comment says why that is enough: the choices a vote holds are in the vote's own storage, so the index holds a choice only once a vote has kept it. The consensus tests now assert it: a document query of a proposal's choices finds none while the vote runs, none after a lock, and only the kept choice after an award. Co-Authored-By: Claude Fable 5.2 --- .../multiple_choice_proposal_tests.rs | 46 ++++++++++++++++++- .../decision_proposals/multiple_choice.rs | 4 ++ .../platform/documents/contest_vote_state.rs | 43 +++++++++++++++-- 3 files changed, 87 insertions(+), 6 deletions(-) diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/multiple_choice_proposal_tests.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/multiple_choice_proposal_tests.rs index f80fd37439d..b6e03193d59 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/multiple_choice_proposal_tests.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/multiple_choice_proposal_tests.rs @@ -811,6 +811,38 @@ fn stored_choice( stored_document(platform, contract, choice::NAME, choice_id) } +/// The ids of the choices of the proposal `proposal_id` a document query finds through the +/// `byProposal` index, as a client reads the choice a vote kept: the choices a vote still +/// holds are in the vote's own storage, not there. +fn choices_found_by_proposal( + platform: &TempPlatform, + contract: &DataContract, + proposal_id: Identifier, + platform_version: &PlatformVersion, +) -> Vec { + let document_type = contract + .document_type_for_name(choice::NAME) + .expect("expected the choice type"); + let query = DriveDocumentQuery::from_value( + platform_value!({ + "where": [[choice::properties::PROPOSAL_ID, "==", proposal_id]], + }), + contract, + document_type, + &platform.config.drive, + platform_version, + ) + .expect("expected a document query"); + platform + .drive + .query_documents(query, None, false, None, None) + .expect("expected to query the choices") + .documents() + .iter() + .map(|document| document.id()) + .collect() +} + /// A serialized edit of the multiple choice proposal `question` by `proposer` (its owner) /// setting `changes`, its revision bumped. async fn edit_transition( @@ -1007,8 +1039,12 @@ async fn should_keep_the_choice_the_masternodes_vote_for_most() { prefunded_balance(&platform, &poll, platform_version), 4 * fund ); - // A choice is held by the vote, not stored, until the vote ends + // A choice is held by the vote, not stored, until the vote ends: a document query of the + // proposal's choices finds none of the four assert!(stored_choice(&platform, &contract, bob_choice).is_none()); + assert!( + choices_found_by_proposal(&platform, &contract, proposal_id, platform_version).is_empty() + ); // A vote names a choice by its document id. Two masternodes for Bob's choice, one each for // Alice's and Carol's, one for none of them @@ -1044,6 +1080,11 @@ async fn should_keep_the_choice_the_masternodes_vote_for_most() { for other in [alice_choice, carol_choice, proposer_choice] { assert!(stored_choice(&platform, &contract, other).is_none()); } + // Which leaves the kept choice the only one a document query of the proposal's finds + assert_eq!( + choices_found_by_proposal(&platform, &contract, proposal_id, platform_version), + vec![bob_choice] + ); } #[tokio::test] @@ -1112,6 +1153,9 @@ async fn should_keep_no_choice_when_the_lock_votes_outnumber_every_choice() { for entered in [alice_choice, bob_choice] { assert!(stored_choice(&platform, &contract, entered).is_none()); } + assert!( + choices_found_by_proposal(&platform, &contract, proposal_id, platform_version).is_empty() + ); // The masternodes' answer stands: no choice can be entered for the proposal again let (again, _) = choice_transition( diff --git a/packages/rs-sdk/src/platform/decision_proposals/multiple_choice.rs b/packages/rs-sdk/src/platform/decision_proposals/multiple_choice.rs index 9e6b69addbc..bda7ad7bc60 100644 --- a/packages/rs-sdk/src/platform/decision_proposals/multiple_choice.rs +++ b/packages/rs-sdk/src/platform/decision_proposals/multiple_choice.rs @@ -614,6 +614,10 @@ impl Sdk { /// The choice the finished vote of the proposal `proposal_id` kept, stored as an ordinary /// document under the identity that entered it. `None` while the vote runs, for a vote /// that kept none of the choices, and for a proposal no choice was entered for. + /// + /// One proved document query through the `byProposal` index. The choices a vote holds are + /// in the vote's own storage, which a document query does not read: the index holds a + /// choice only once a vote has kept it, and being unique it holds at most that one. pub async fn fetch_kept_choice( &self, proposal_id: Identifier, diff --git a/packages/rs-sdk/src/platform/documents/contest_vote_state.rs b/packages/rs-sdk/src/platform/documents/contest_vote_state.rs index 655ee2d054f..80442d8c8fb 100644 --- a/packages/rs-sdk/src/platform/documents/contest_vote_state.rs +++ b/packages/rs-sdk/src/platform/documents/contest_vote_state.rs @@ -22,9 +22,10 @@ impl Sdk { /// without a start. /// /// `limit` is the most contenders returned; `None` returns every contender, and `Some(0)` - /// an empty state without a request. A contest that ended answers with every contender of - /// its record whatever a page asks for, so its contenders are cut to `limit` here, the - /// first in id order kept; its winner and its abstain and lock tallies are returned whole. + /// an empty state without a request. A contest that ended answers its first page with + /// every contender of its record, whatever the page asks for: no further page is read, and + /// its contenders are cut to `limit` here, the first in id order kept; its winner and its + /// abstain and lock tallies are returned whole. pub async fn fetch_contested_resource_vote_state( &self, vote_poll: &ContestedDocumentResourceVotePoll, @@ -59,6 +60,8 @@ impl Sdk { .await?; let page_len = page.contenders.len(); let last = page.contenders.keys().last().copied(); + // A page naming a winner is the record of a contest that ended, which is whole + let ended = page.winner.is_some(); match state.as_mut() { None => state = Some(page), Some(state) => state.contenders.extend(page.contenders), @@ -66,7 +69,7 @@ impl Sdk { // A short page is the last one match last { - Some(last) if page_len >= page_limit as usize => { + Some(last) if !ended && page_len >= page_limit as usize => { start_at = Some((last.to_buffer(), false)); } _ => break, @@ -98,7 +101,7 @@ mod tests { /// the page asked for: the state holds `limit` of them, with the winner and the abstain /// and lock tallies of the whole contest. #[tokio::test] - async fn should_return_at_most_the_limit_of_contenders_of_a_contest_that_ended() { + async fn should_read_a_contest_that_ended_in_one_page_and_cut_it_to_the_limit() { let mut sdk = SdkBuilder::new_mock() .with_version(PlatformVersion::latest()) .build() @@ -153,6 +156,36 @@ mod tests { .await .expect("registers the page"); } + // The whole record of a contest that ended comes with its first page, however many + // contenders it holds: no page after it is registered, so asking for one would fail + let record: BTreeMap<_, _> = (1..=150u8).map(|n| contender(n, 1)).collect(); + sdk.mock() + .expect_fetch_many::<_, ContenderWithSerializedDocument, _, Contenders>( + ContestedDocumentVotePollDriveQuery { + vote_poll: vote_poll.clone(), + result_type: + ContestedDocumentVotePollDriveQueryResultType::DocumentsAndVoteTally, + allow_include_locked_and_abstaining_vote_tally: true, + start_at: None, + limit: Some(DEFAULT_QUERY_LIMIT), + offset: None, + }, + Some(Contenders { + winner, + contenders: record, + abstain_vote_tally: Some(6), + lock_vote_tally: Some(2), + }), + ) + .await + .expect("registers the record"); + let whole = sdk + .fetch_contested_resource_vote_state(&vote_poll, None) + .await + .expect("reads the record in one page"); + assert_eq!(whole.contenders.len(), 150); + assert_eq!(whole.winner, winner); + for limit in [1u32, 2] { let state = sdk .fetch_contested_resource_vote_state(&vote_poll, Some(limit))