From c5c0dfbe1449c00eb709e90798eb0ab50573c357 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Sat, 31 Oct 2026 07:41:04 +0300 Subject: [PATCH 1/3] feat(sdk): decision proposal helpers in rs-sdk, wasm-sdk and js-evo-sdk Step 5a of #5679. The Rust and JavaScript SDKs build a decision proposal to create as a document, give one new text, list and read proposals, read a proposal's poll and vote on it as a masternode, all by the proposal's id. - rs-dpp: YesNoVotePollPurpose::unique_id (the poll's id from its purpose alone), decision_proposal_vote_poll_id, the text property names; a contest fund in the creation options no longer replaces a proposal create's fund. - rs-sdk: QueriedYesNoVotePoll::Purpose, Sdk::yes_no_vote_poll_id and Sdk::yes_no_vote, and the decision_proposals module; DocumentsPage and Sdk::require_protocol_version shared with the moderation charters. - wasm-sdk: the *DecisionProposal* methods; masternodeVote answers a yes/no poll with 'yes', 'no' or 'abstain'. - js-evo-sdk: sdk.decisionProposals. Co-Authored-By: Claude Opus 5.5 --- docs/protocol/decision-proposals.md | 18 +- packages/js-evo-sdk/README.md | 44 + .../src/decision-proposals/facade.ts | 100 +++ packages/js-evo-sdk/src/sdk.ts | 4 + .../unit/facades/decision-proposals.spec.ts | 139 ++++ packages/rs-dpp/src/decision_proposal/mod.rs | 63 +- .../document/batch_transition/methods/mod.rs | 47 +- .../voting/vote_polls/yes_no_vote_poll/mod.rs | 65 +- packages/rs-sdk/src/platform.rs | 1 + .../rs-sdk/src/platform/decision_proposals.rs | 765 ++++++++++++++++++ packages/rs-sdk/src/platform/documents/mod.rs | 2 + .../rs-sdk/src/platform/documents/page.rs | 72 ++ .../src/platform/moderation_charters/mod.rs | 15 +- .../platform/moderation_charters/readers.rs | 71 +- .../src/platform/system_data_contract.rs | 24 + .../rs-sdk/src/platform/yes_no_vote_polls.rs | 148 +++- packages/wasm-sdk/src/decision_proposals.rs | 484 +++++++++++ packages/wasm-sdk/src/lib.rs | 1 + packages/wasm-sdk/src/moderation_charters.rs | 28 +- packages/wasm-sdk/src/queries/utils.rs | 26 + packages/wasm-sdk/src/queries/voting/mod.rs | 2 +- .../wasm-sdk/src/queries/voting/yes_no.rs | 4 +- .../src/state_transitions/identity.rs | 81 +- .../tests/unit/decision-proposals.spec.ts | 125 +++ 24 files changed, 2145 insertions(+), 184 deletions(-) create mode 100644 packages/js-evo-sdk/src/decision-proposals/facade.ts create mode 100644 packages/js-evo-sdk/tests/unit/facades/decision-proposals.spec.ts create mode 100644 packages/rs-sdk/src/platform/decision_proposals.rs create mode 100644 packages/rs-sdk/src/platform/documents/page.rs create mode 100644 packages/wasm-sdk/src/decision_proposals.rs create mode 100644 packages/wasm-sdk/tests/unit/decision-proposals.spec.ts diff --git a/docs/protocol/decision-proposals.md b/docs/protocol/decision-proposals.md index a9e81102521..786ec1b610a 100644 --- a/docs/protocol/decision-proposals.md +++ b/docs/protocol/decision-proposals.md @@ -72,7 +72,8 @@ poll by id alone. The create states the fund it pays as its prefunded voting balance: the name `proposal` and exactly the decision proposal fund. The transition builders fill -it in for a proposal, as they do for a contested document. Any other fund is +it in for a proposal, as they do for a contested document, and a contest fund +given in the creation options leaves it as it is. Any other fund is refused (`DecisionProposalFundMismatchError`, 11100), as is a rule outside the limits below (`InvalidDecisionProposalRuleError`, 11101) and an end date outside them (`DecisionProposalEndDateOutOfRangeError`, 41300). The mempool judges the @@ -107,11 +108,22 @@ proposal before it closes. The poll closes in a block whose time has reached its end date. Its result, whether it passed with the yes, no and abstain voting power cast and the voting power it needed, stays in the poll's stored info. Read it with -`getYesNoVotePollState`, naming the poll by its id (`YesNoVotePoll::unique_id` -of the `DecisionProposal` purpose): the response carries the poll as it was +`getYesNoVotePollState`, naming the poll by its id (`YesNoVotePollPurpose::unique_id` +of the `DecisionProposal` purpose, `decision_proposal_vote_poll_id` in +`dpp::decision_proposal`): the response carries the poll as it was opened, its rule included, and once it has finished, the result and the blocks it opened and closed in. The result is signaling only. Nothing on Platform acts on a passed or failed proposal (`on_yes_no_vote_poll_finished` does nothing for this purpose); what it means is up to the people who read it. + +## From the SDKs + +The Rust SDK (`dash_sdk::platform::decision_proposals`) and the JavaScript SDKs +(`sdk.decisionProposals` in `@dashevo/evo-sdk`, the `*DecisionProposal*` +methods of `@dashevo/wasm-sdk`) build a proposal to create as a document, give +an existing one new text to replace it with, list proposals through the three +indexes a page at a time, and read and answer a proposal's poll by the +proposal's id. A masternode's vote names the poll by its id, which the SDKs +derive from the proposal's id with the protocol version they speak. diff --git a/packages/js-evo-sdk/README.md b/packages/js-evo-sdk/README.md index dd09e66ffd6..c899d271572 100644 --- a/packages/js-evo-sdk/README.md +++ b/packages/js-evo-sdk/README.md @@ -111,6 +111,7 @@ The SDK organises its API into domain-specific facades, each accessible as a pro | [`sdk.shielded`](src/shielded/facade.ts) | Query shielded pool state, encrypted notes, anchors, and nullifier status | | [`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 | 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. @@ -484,6 +485,49 @@ await sdk.documents.create({ document: resignation, identityKey, signer }); The leader reads either with `sdk.encryptedFor.decrypt`. +## Decision proposals + +From protocol version 15 any identity can put a yes/no question to the masternodes: a `proposal` document of the decision proposals system contract (`3iNyoNwjCTkb7XS3RHyWUtLx7pgC6AFAEQNNDHzxqngF`). Creating it opens the proposal's vote poll, and the owner pays the decision proposal fund, 0.5 Dash, on top of the fees. The result is signaling only. `sdk.decisionProposals` builds proposals for `sdk.documents`, reads them with proved queries, and reads and answers their polls by the proposal's id: + +```ts +// A question that passes with more than 60% yes, if at least 10% of the network answers +const draft = await sdk.decisionProposals.build({ + ownerId: identity.id, + title: 'Raise the block size?', + description: 'Yes doubles it; no keeps it.', + url: 'https://forum.dash.org/t/block-size', + passPercent: 60, // 50 to 80 + minimumTurnoutPercent: 10, // 0 to 50 + endDate: BigInt(Date.now() + 14 * 24 * 3600 * 1000), // 1 to 4 weeks after the creating block +}); +const proposal = await sdk.documents.create({ document: draft, identityKey, signer }); + +// The text can be edited for a day; the rule and the end date never change +const edited = await sdk.decisionProposals.buildEdit(proposal, { title: 'Raise the block size to 4 MB?' }); +await sdk.documents.replace({ document: edited, identityKey, signer }); + +// The open proposals, closing soonest first; an identity's; every proposal, newest first +const open = await sdk.decisionProposals.byEndDate({ endDateFrom: BigInt(Date.now()), limit: 20 }); +const mine = await sdk.decisionProposals.byOwner({ ownerId: identity.id }); +const latest = await sdk.decisionProposals.byCreatedAt({ limit: 10 }); + +// The poll: its tallies while it runs, its result once it closes +const state = await sdk.decisionProposals.pollState(proposal.id); +if (state?.status === 'finished') console.log(state.result.passed); + +// A masternode answers 'yes', 'no' or 'abstain' with its voting key +await sdk.decisionProposals.vote({ + masternodeProTxHash: proTxHash, + proposalId: proposal.id, + voteChoice: 'yes', + votingKey, + signer: votingSigner, +}); +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'`. + ## 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 new file mode 100644 index 00000000000..b614a51ce00 --- /dev/null +++ b/packages/js-evo-sdk/src/decision-proposals/facade.ts @@ -0,0 +1,100 @@ +import * as wasm from '../wasm.js'; +import type { EvoSDK } from '../sdk.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. + */ +export class DecisionProposalsFacade { + private sdk: EvoSDK; + + constructor(sdk: EvoSDK) { + this.sdk = sdk; + } + + /** + * Builds a proposal to create with `sdk.documents.create`, which states the fund itself and + * returns the stored proposal with its final id. + */ + async build(options: wasm.DecisionProposalOptions): Promise { + const w = await this.sdk.getWasmSdkConnected(); + return w.buildDecisionProposal(options); + } + + /** + * A proposal with new text and its next revision, to replace with `sdk.documents.replace`. + * Platform accepts the edit for a day after the proposal is created. + */ + async buildEdit(proposal: wasm.Document, edit: wasm.DecisionProposalEdit): Promise { + const w = await this.sdk.getWasmSdkConnected(); + return w.buildDecisionProposalEdit(proposal, edit); + } + + /** A proposal by id, or undefined when there is none. */ + async get(proposalId: wasm.IdentifierLike): Promise { + const w = await this.sdk.getWasmSdkConnected(); + return w.getDecisionProposal(proposalId); + } + + /** + * One page of the proposals by end date, then by creation time. `endDateFrom: Date.now()` + * lists the open ones. + */ + async byEndDate( + query?: wasm.DecisionProposalsByEndDateQuery, + ): Promise> { + const w = await this.sdk.getWasmSdkConnected(); + return w.getDecisionProposalsByEndDate(query); + } + + /** One page of an identity's proposals, by creation time. */ + async byOwner( + query: wasm.DecisionProposalsByOwnerQuery, + ): Promise> { + const w = await this.sdk.getWasmSdkConnected(); + return w.getDecisionProposalsByOwner(query); + } + + /** One page of every proposal, newest first. */ + async byCreatedAt( + query?: wasm.DecisionProposalsPageQuery, + ): Promise> { + const w = await this.sdk.getWasmSdkConnected(); + return w.getDecisionProposalsByCreatedAt(query); + } + + /** The id of a proposal's poll, as `sdk.voting.votePollsByEndDate` lists it. */ + async pollId(proposalId: wasm.IdentifierLike): Promise { + const w = await this.sdk.getWasmSdkConnected(); + return w.getDecisionProposalPollId(proposalId); + } + + /** + * The status and tallies of a proposal's poll: started, with the voting power cast so far, + * or finished, with its result. Undefined for a proposal never created. + */ + async pollState(proposalId: wasm.IdentifierLike): Promise { + const w = await this.sdk.getWasmSdkConnected(); + return w.getDecisionProposalPollState(proposalId); + } + + /** + * A masternode's answer on a proposal, or undefined when it has not voted on it or the poll + * finished. + */ + async masternodeVote( + proTxHash: wasm.IdentifierLike, + proposalId: wasm.IdentifierLike, + ): Promise { + const w = await this.sdk.getWasmSdkConnected(); + return w.getMasternodeDecisionProposalVote(proTxHash, proposalId); + } + + /** Votes on a proposal for a masternode, and returns the vote as Platform recorded it. */ + async vote(options: wasm.DecisionProposalVoteOptions): Promise { + const w = await this.sdk.getWasmSdkConnected(); + return w.decisionProposalVote(options); + } +} diff --git a/packages/js-evo-sdk/src/sdk.ts b/packages/js-evo-sdk/src/sdk.ts index 49268094f89..8389374cdb5 100644 --- a/packages/js-evo-sdk/src/sdk.ts +++ b/packages/js-evo-sdk/src/sdk.ts @@ -16,6 +16,7 @@ import { VotingFacade } from './voting/facade.js'; import { ShieldedFacade } from './shielded/facade.js'; import { EncryptedForFacade } from './encrypted-for/facade.js'; import { ModerationChartersFacade } from './moderation-charters/facade.js'; +import { DecisionProposalsFacade } from './decision-proposals/facade.js'; export interface ConnectionOptions { version?: number; @@ -77,6 +78,7 @@ export class EvoSDK { public shielded!: ShieldedFacade; public encryptedFor!: EncryptedForFacade; public moderationCharters!: ModerationChartersFacade; + public decisionProposals!: DecisionProposalsFacade; constructor(options: EvoSDKOptions = {}) { // Apply defaults while preserving any future connection options const { network = 'testnet', trusted = false, addresses, devnetName, quorumUrl, ...connection } = options; @@ -117,6 +119,7 @@ export class EvoSDK { this.shielded = new ShieldedFacade(this); this.encryptedFor = new EncryptedForFacade(this); this.moderationCharters = new ModerationChartersFacade(this); + this.decisionProposals = new DecisionProposalsFacade(this); } get wasm(): wasm.WasmSdk { @@ -343,5 +346,6 @@ export { VotingFacade } from './voting/facade.js'; 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 { wallet } from './wallet/functions.js'; export * from './wasm.js'; diff --git a/packages/js-evo-sdk/tests/unit/facades/decision-proposals.spec.ts b/packages/js-evo-sdk/tests/unit/facades/decision-proposals.spec.ts new file mode 100644 index 00000000000..81138895b40 --- /dev/null +++ b/packages/js-evo-sdk/tests/unit/facades/decision-proposals.spec.ts @@ -0,0 +1,139 @@ +import type { SinonStub } from 'sinon'; +import init, * as wasmSDKPackage from '@dashevo/wasm-sdk'; +import { EvoSDK } from '../../../dist/sdk.js'; + +describe('DecisionProposalsFacade', () => { + let wasmSdk: wasmSDKPackage.WasmSdk; + let client: EvoSDK; + + let buildDecisionProposalStub: SinonStub; + let buildDecisionProposalEditStub: SinonStub; + let getDecisionProposalStub: SinonStub; + let getDecisionProposalsByEndDateStub: SinonStub; + let getDecisionProposalsByOwnerStub: SinonStub; + let getDecisionProposalsByCreatedAtStub: SinonStub; + let getDecisionProposalPollIdStub: SinonStub; + let getDecisionProposalPollStateStub: SinonStub; + let getMasternodeDecisionProposalVoteStub: SinonStub; + let decisionProposalVoteStub: SinonStub; + + const ownerId = '5mjGWa9mruHnLBht3ntBi8CZ6sNk3hZZsQMgTvgQobjS'; + const proposalId = '4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF'; + const proTxHash = 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2'; + + beforeEach(async function setup() { + await init(); + const builder = wasmSDKPackage.WasmSdkBuilder.testnet(); + wasmSdk = await builder.build(); + client = EvoSDK.fromWasm(wasmSdk); + + buildDecisionProposalStub = this.sinon.stub(wasmSdk, 'buildDecisionProposal').resolves({}); + buildDecisionProposalEditStub = this.sinon.stub(wasmSdk, 'buildDecisionProposalEdit').returns({}); + getDecisionProposalStub = this.sinon.stub(wasmSdk, 'getDecisionProposal').resolves(undefined); + getDecisionProposalsByEndDateStub = this.sinon.stub(wasmSdk, 'getDecisionProposalsByEndDate').resolves(new Map()); + getDecisionProposalsByOwnerStub = this.sinon.stub(wasmSdk, 'getDecisionProposalsByOwner').resolves(new Map()); + getDecisionProposalsByCreatedAtStub = this.sinon.stub(wasmSdk, 'getDecisionProposalsByCreatedAt').resolves(new Map()); + getDecisionProposalPollIdStub = this.sinon.stub(wasmSdk, 'getDecisionProposalPollId').resolves({}); + getDecisionProposalPollStateStub = this.sinon.stub(wasmSdk, 'getDecisionProposalPollState').resolves(undefined); + getMasternodeDecisionProposalVoteStub = this.sinon.stub(wasmSdk, 'getMasternodeDecisionProposalVote').resolves(undefined); + decisionProposalVoteStub = this.sinon.stub(wasmSdk, 'decisionProposalVote').resolves({}); + }); + + describe('build()', () => { + it('should forward the options to buildDecisionProposal', async () => { + const options = { + ownerId, + title: 'Raise the block size?', + description: 'Yes doubles it; no keeps it.', + url: 'https://forum.dash.org/t/block-size', + passPercent: 60, + minimumTurnoutPercent: 10, + endDate: 1_700_000_000_000n, + }; + await client.decisionProposals.build(options); + expect(buildDecisionProposalStub).to.be.calledOnceWithExactly(options); + }); + }); + + describe('buildEdit()', () => { + it('should forward the proposal and the edit to buildDecisionProposalEdit', async () => { + const proposal = {} as wasmSDKPackage.Document; + const edit = { title: 'Raise the block size to 4 MB?', url: null }; + await client.decisionProposals.buildEdit(proposal, edit); + expect(buildDecisionProposalEditStub).to.be.calledOnceWithExactly(proposal, edit); + }); + }); + + describe('get()', () => { + it('should forward the proposal id to getDecisionProposal', async () => { + const result = await client.decisionProposals.get(proposalId); + expect(getDecisionProposalStub).to.be.calledOnceWithExactly(proposalId); + expect(result).to.equal(undefined); + }); + }); + + describe('byEndDate()', () => { + it('should forward the query to getDecisionProposalsByEndDate', async () => { + const query = { endDateFrom: 1_700_000_000_000n, limit: 20 }; + const result = await client.decisionProposals.byEndDate(query); + expect(getDecisionProposalsByEndDateStub).to.be.calledOnceWithExactly(query); + expect(result).to.be.instanceOf(Map); + }); + + it('should list from the start without a query', async () => { + await client.decisionProposals.byEndDate(); + expect(getDecisionProposalsByEndDateStub).to.be.calledOnceWithExactly(undefined); + }); + }); + + describe('byOwner()', () => { + it('should forward the query to getDecisionProposalsByOwner', async () => { + const query = { ownerId, startAfter: proposalId }; + await client.decisionProposals.byOwner(query); + expect(getDecisionProposalsByOwnerStub).to.be.calledOnceWithExactly(query); + }); + }); + + describe('byCreatedAt()', () => { + it('should forward the query to getDecisionProposalsByCreatedAt', async () => { + const query = { limit: 5 }; + await client.decisionProposals.byCreatedAt(query); + expect(getDecisionProposalsByCreatedAtStub).to.be.calledOnceWithExactly(query); + }); + }); + + describe('pollId()', () => { + it('should forward the proposal id to getDecisionProposalPollId', async () => { + await client.decisionProposals.pollId(proposalId); + expect(getDecisionProposalPollIdStub).to.be.calledOnceWithExactly(proposalId); + }); + }); + + describe('pollState()', () => { + it('should forward the proposal id to getDecisionProposalPollState', async () => { + await client.decisionProposals.pollState(proposalId); + expect(getDecisionProposalPollStateStub).to.be.calledOnceWithExactly(proposalId); + }); + }); + + describe('masternodeVote()', () => { + it('should forward the masternode and the proposal to getMasternodeDecisionProposalVote', async () => { + await client.decisionProposals.masternodeVote(proTxHash, proposalId); + expect(getMasternodeDecisionProposalVoteStub).to.be.calledOnceWithExactly(proTxHash, proposalId); + }); + }); + + describe('vote()', () => { + it('should forward the options to decisionProposalVote', async () => { + const options = { + masternodeProTxHash: proTxHash, + proposalId, + voteChoice: 'yes' as const, + votingKey: {} as wasmSDKPackage.IdentityPublicKey, + signer: {} as wasmSDKPackage.IdentitySigner, + }; + await client.decisionProposals.vote(options); + expect(decisionProposalVoteStub).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 335fb0ac957..933e7132bf3 100644 --- a/packages/rs-dpp/src/decision_proposal/mod.rs +++ b/packages/rs-dpp/src/decision_proposal/mod.rs @@ -39,13 +39,22 @@ pub const PROPOSAL_DOCUMENT_TYPE_NAME: &str = "proposal"; /// proposal's own type. A contested create names its contested index there instead. pub const DECISION_PROPOSAL_FUND_NAME: &str = PROPOSAL_DOCUMENT_TYPE_NAME; -/// The properties of a proposal the poll is read from. +/// The properties of a proposal. pub mod properties { + /// The question, in one line. Editable for a day after the proposal is created. + pub const TITLE: &str = "title"; + /// What a yes and a no mean. Editable for a day after the proposal is created. + pub const DESCRIPTION: &str = "description"; + /// Where the proposal is discussed; optional. Editable for a day after the proposal is + /// created. + pub const URL: &str = "url"; /// The proposal passes when yes is strictly more than this percent of yes plus no. pub const PASS_PERCENT: &str = "passPercent"; /// The least yes plus no voting power the proposal needs, as a percent of the masternode /// list's total voting power when the poll closes, rounded up. pub const MINIMUM_TURNOUT_PERCENT: &str = "minimumTurnoutPercent"; + /// When voting closes, in milliseconds since the Unix epoch: from a week to four weeks + /// after the block that creates the proposal. pub const END_DATE: &str = "endDate"; } @@ -67,6 +76,23 @@ pub fn decision_proposal_required_fund(platform_version: &PlatformVersion) -> Cr .decision_proposal_fund_required_amount } +/// The id of the yes/no poll the proposal `document_id` opens: the id of the purpose +/// [`YesNoVotePollPurpose::DecisionProposal`], which a vote on the proposal names and the poll +/// queries take. Known from the proposal's id alone, before or after the poll opens. +/// +/// # Parameters +/// - `document_id`: the proposal's id. +/// - `platform_version`: the platform version, which selects how the id is derived. +/// +/// # Returns +/// The poll's id, or an error before protocol version 15. +pub fn decision_proposal_vote_poll_id( + document_id: Identifier, + platform_version: &PlatformVersion, +) -> Result { + YesNoVotePollPurpose::DecisionProposal { document_id }.unique_id(platform_version) +} + /// The yes/no poll a decision proposal opens and when it closes. #[derive(Debug, Clone, PartialEq, Eq)] pub struct DecisionProposalVotePoll { @@ -295,6 +321,38 @@ mod tests { assert!(refusal(read(no_turnout)).contains("is required")); } + /// The poll id read from the proposal's id alone is the id of the poll the proposal opens. + #[test] + fn should_name_the_poll_of_a_proposal_by_its_id_alone() { + let platform_version = PlatformVersion::latest(); + let document_id = Identifier::new([7; 32]); + let opened = DecisionProposalVotePoll::from_proposal( + document_id, + &proposal(60, 10), + platform_version, + ) + .expect("active at 15") + .into_data() + .expect("a valid rule") + .vote_poll; + assert_eq!( + decision_proposal_vote_poll_id(document_id, platform_version).expect("active at 15"), + opened.unique_id(platform_version).expect("active at 15") + ); + assert_ne!( + decision_proposal_vote_poll_id(Identifier::new([8; 32]), platform_version) + .expect("active at 15"), + opened.unique_id(platform_version).expect("active at 15") + ); + assert!(matches!( + decision_proposal_vote_poll_id( + document_id, + PlatformVersion::get(14).expect("expected protocol version 14") + ), + Err(ProtocolError::UnknownVersionError(_)) + )); + } + #[test] fn should_not_be_active_before_protocol_version_15() { let platform_version = PlatformVersion::get(14).expect("expected protocol version 14"); @@ -335,6 +393,9 @@ mod tests { decision_proposals_contract::ID ); assert_eq!(PROPOSAL_DOCUMENT_TYPE_NAME, proposal::NAME); + assert_eq!(properties::TITLE, proposal::properties::TITLE); + assert_eq!(properties::DESCRIPTION, proposal::properties::DESCRIPTION); + assert_eq!(properties::URL, proposal::properties::URL); assert_eq!(properties::PASS_PERCENT, proposal::properties::PASS_PERCENT); assert_eq!( properties::MINIMUM_TURNOUT_PERCENT, diff --git a/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/methods/mod.rs b/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/methods/mod.rs index c3c93e48f6c..502e3c088ca 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/methods/mod.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/methods/mod.rs @@ -9,6 +9,7 @@ use crate::data_contract::document_type::action_fees::agreement::DocumentActionF use crate::data_contract::document_type::DocumentTypeRef; #[cfg(feature = "state-transition-signing")] use crate::data_contract::TokenContractPosition; +use crate::decision_proposal::is_decision_proposal; #[cfg(feature = "state-transition-signing")] use crate::document::Document; use crate::fee::Credits; @@ -69,7 +70,8 @@ pub struct StateTransitionCreationOptions { /// fees, but nothing into the contest. The identity must hold what it states, because the /// balance check made before the contest is counted is against it. `None` keeps the fund /// the create is built with, the contest's fund, what joining a contest holding fewer than - /// 250 contenders costs. A create that joins no contest ignores it. + /// 250 contenders costs. A create that joins no contest ignores it, a decision proposal's + /// included: its fund is fixed. pub contest_fund: Option, } @@ -121,11 +123,19 @@ impl StateTransitionCreationOptions { } /// `transition` stating the options' contest fund as the most it pays into its contest, if - /// they name one and it is a contested create. + /// they name one and it is a contested create. A decision proposal's create also states a + /// fund, the decision proposal fund, which consensus requires exactly: it keeps it. pub fn apply_contest_fund(&self, mut transition: DocumentTransition) -> DocumentTransition { - if let (Some(contest_fund), DocumentTransition::Create(create)) = - (self.contest_fund, &mut transition) - { + let Some(contest_fund) = self.contest_fund else { + return transition; + }; + if is_decision_proposal( + &transition.data_contract_id(), + transition.document_type_name(), + ) { + return transition; + } + if let DocumentTransition::Create(create) = &mut transition { if let Some((_, stated)) = create.prefunded_voting_balances_mut() { *stated = contest_fund; } @@ -1628,6 +1638,11 @@ mod action_fee_agreement_option_tests { #[cfg(test)] mod contest_fund_option_tests { use super::*; + use crate::decision_proposal::{ + DECISION_PROPOSALS_CONTRACT_ID, DECISION_PROPOSAL_FUND_NAME, PROPOSAL_DOCUMENT_TYPE_NAME, + }; + use crate::state_transition::batch_transition::document_base_transition::document_base_transition_trait::DocumentBaseTransitionAccessors; + use crate::state_transition::batch_transition::document_base_transition::v0::v0_methods::DocumentBaseTransitionV0Methods; use crate::state_transition::batch_transition::document_create_transition::DocumentCreateTransition; fn create(prefunded_voting_balance: Option<(String, Credits)>) -> DocumentTransition { @@ -1671,4 +1686,26 @@ mod contest_fund_option_tests { "a create that joins no contest ignores it" ); } + + /// A decision proposal's create states the decision proposal fund, which consensus + /// requires exactly: a contest fund in the options leaves it as it is. + #[test] + fn should_keep_the_fund_of_a_decision_proposal_create() { + let options = StateTransitionCreationOptions { + contest_fund: Some(7), + ..Default::default() + }; + let mut proposal = create(Some((DECISION_PROPOSAL_FUND_NAME.to_string(), 50))); + let DocumentTransition::Create(create_transition) = &mut proposal else { + unreachable!("built as a create"); + }; + create_transition + .base_mut() + .set_data_contract_id(DECISION_PROPOSALS_CONTRACT_ID); + create_transition + .base_mut() + .set_document_type_name(PROPOSAL_DOCUMENT_TYPE_NAME.to_string()); + + assert_eq!(stated(&options.apply_contest_fund(proposal)), Some(50)); + } } diff --git a/packages/rs-dpp/src/voting/vote_polls/yes_no_vote_poll/mod.rs b/packages/rs-dpp/src/voting/vote_polls/yes_no_vote_poll/mod.rs index 65b788f53d6..3752445499c 100644 --- a/packages/rs-dpp/src/voting/vote_polls/yes_no_vote_poll/mod.rs +++ b/packages/rs-dpp/src/voting/vote_polls/yes_no_vote_poll/mod.rs @@ -179,6 +179,43 @@ impl fmt::Display for YesNoVotePollPurpose { } } +impl YesNoVotePollPurpose { + /// The id of the poll with this purpose, derived as the platform version selects + /// (`dpp.voting_versions.yes_no_vote_poll_id`). Only the purpose names a poll, so the id is + /// known without the poll's rule: [`YesNoVotePoll::unique_id`] is this id. + /// + /// # Parameters + /// - `platform_version`: the platform version. + /// + /// # Returns + /// The id of the poll with this purpose. + pub fn unique_id( + &self, + platform_version: &PlatformVersion, + ) -> Result { + match platform_version.dpp.voting_versions.yes_no_vote_poll_id { + Some(0) => self.unique_id_v0(), + Some(version) => Err(ProtocolError::UnknownVersionMismatch { + method: "YesNoVotePollPurpose::unique_id".to_string(), + known_versions: vec![0], + received: version, + }), + None => Err(ProtocolError::UnknownVersionError( + "YesNoVotePollPurpose::unique_id is not active before protocol version 15" + .to_string(), + )), + } + } + + /// Version 0: the double SHA-256 of the yes/no poll id domain tag followed by the serialized + /// purpose. + fn unique_id_v0(&self) -> Result { + let mut preimage = YES_NO_VOTE_POLL_ID_DOMAIN.to_vec(); + preimage.extend(self.serialize_to_bytes()?); + Ok(Identifier::new(hash_double(preimage))) + } +} + /// A poll the masternodes answer with yes, no or abstain. /// /// The poll passes when the yes voting power is strictly more than @@ -491,8 +528,11 @@ impl YesNoVotePoll { } /// The id the poll is stored and voted on under, which also keys its end date index entry - /// and names its prefunded balance, derived as the platform version selects - /// (`dpp.voting_versions.yes_no_vote_poll_id`). + /// and names its prefunded balance: the id of its purpose + /// ([`YesNoVotePollPurpose::unique_id`]). Version 0 is the double SHA-256 of the domain tag + /// followed by the serialized purpose. The rule is left out, so a vote naming the id answers + /// whatever rule the poll opened with, and a purpose opens one poll whatever rule it is + /// asked with. /// /// # Parameters /// - `platform_version`: the platform version. @@ -503,17 +543,7 @@ impl YesNoVotePoll { &self, platform_version: &PlatformVersion, ) -> Result { - match platform_version.dpp.voting_versions.yes_no_vote_poll_id { - Some(0) => self.unique_id_v0(), - Some(version) => Err(ProtocolError::UnknownVersionMismatch { - method: "YesNoVotePoll::unique_id".to_string(), - known_versions: vec![0], - received: version, - }), - None => Err(ProtocolError::UnknownVersionError( - "YesNoVotePoll::unique_id is not active before protocol version 15".to_string(), - )), - } + self.purpose.unique_id(platform_version) } /// The prefunded balance the votes on this poll are paid from: the poll's unique id. @@ -529,15 +559,6 @@ impl YesNoVotePoll { ) -> Result { self.unique_id(platform_version) } - - /// Version 0: the double SHA-256 of the yes/no poll id domain tag followed by the serialized - /// purpose. The rule is left out, so a vote naming the id answers whatever rule the poll - /// opened with, and a purpose opens one poll whatever rule it is asked with. - fn unique_id_v0(&self) -> Result { - let mut preimage = YES_NO_VOTE_POLL_ID_DOMAIN.to_vec(); - preimage.extend(self.purpose.serialize_to_bytes()?); - Ok(Identifier::new(hash_double(preimage))) - } } #[cfg(test)] diff --git a/packages/rs-sdk/src/platform.rs b/packages/rs-sdk/src/platform.rs index d10da5b7ff4..bec4dae14c4 100644 --- a/packages/rs-sdk/src/platform.rs +++ b/packages/rs-sdk/src/platform.rs @@ -13,6 +13,7 @@ pub mod contract_moderation; pub mod dashpay; pub mod data_contracts_by_range; pub mod data_contracts_latest_versions; +pub mod decision_proposals; mod delegate; pub mod documents; pub mod dpns_usernames; diff --git a/packages/rs-sdk/src/platform/decision_proposals.rs b/packages/rs-sdk/src/platform/decision_proposals.rs new file mode 100644 index 00000000000..fa4255905cc --- /dev/null +++ b/packages/rs-sdk/src/platform/decision_proposals.rs @@ -0,0 +1,765 @@ +//! Decision proposals (protocol version 15): yes/no questions any identity puts to the +//! masternodes, as `proposal` documents of the decision proposals system contract. Creating a +//! proposal opens its yes/no vote poll, funded by the decision proposal fund (0.5 Dash) its +//! owner pays. Nothing acts on a result; it stays in the poll's stored info. +//! +//! * [`Sdk::build_decision_proposal`] builds a proposal, put like any document create with +//! [`PutDocument`](crate::platform::transition::put_document::PutDocument). The create states +//! the fund itself. Consensus refuses a rule outside the contract's limits and an end date +//! less than a week or more than four weeks after the block that creates the proposal. +//! * [`build_decision_proposal_edit`] gives a proposal new text, put as a replace. Only the +//! title, description and url change, and only for a day after the proposal is created. +//! * [`Sdk::fetch_decision_proposal`] reads a proposal by id, and three listings read them a +//! page at a time through the contract's indexes: +//! [`Sdk::fetch_decision_proposals_by_end_date`] closing soonest first, +//! [`Sdk::fetch_decision_proposals_by_owner`] in filing order, and +//! [`Sdk::fetch_decision_proposals_by_created_at`] newest first. +//! [`DecisionProposal::from_document`] reads a proposal's properties. +//! * [`Sdk::decision_proposal_vote`] builds a masternode's answer on a proposal, put with +//! [`PutVote`](crate::platform::transition::vote::PutVote). +//! +//! A proposal's poll is named by its purpose, [`YesNoVotePollPurpose::DecisionProposal`] with +//! the proposal's id ([`Sdk::decision_proposal_vote_poll_id`] gives its id): pass it to +//! [`YesNoVotePollStateQuery::new`](crate::platform::yes_no_vote_polls::YesNoVotePollStateQuery::new) +//! for the poll's status and tallies, and to +//! [`MasternodeYesNoVoteQuery::new`](crate::platform::yes_no_vote_polls::MasternodeYesNoVoteQuery::new) +//! for a masternode's answer. + +use crate::platform::documents::document_query::DocumentQuery; +use crate::platform::documents::page::DocumentsPage; +use crate::platform::{DataContract, Document, Fetch, FetchMany, Identifier}; +use crate::{Error, Sdk}; +use dapi_grpc::platform::v0::get_documents_request::get_documents_request_v0::Start; +use dpp::data_contract::accessors::v0::DataContractV0Getters; +use dpp::data_contract::document_type::methods::DocumentTypeBasicMethods; +use dpp::decision_proposal::{ + properties, DECISION_PROPOSALS_CONTRACT_ID, PROPOSAL_DOCUMENT_TYPE_NAME, +}; +use dpp::document::{DocumentV0, DocumentV0Getters, DocumentV0Setters, INITIAL_REVISION}; +use dpp::platform_value::btreemap_extensions::BTreeValueMapHelper; +use dpp::platform_value::string_encoding::Encoding; +use dpp::platform_value::{Bytes32, Value}; +use dpp::prelude::TimestampMillis; +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::voting::vote_choices::yes_no_abstain_vote_choice::YesNoAbstainVoteChoice; +use dpp::voting::vote_polls::yes_no_vote_poll::YesNoVotePollPurpose; +use dpp::voting::votes::Vote; +use drive::query::{OrderClause, WhereClause, WhereOperator}; +use drive_proof_verifier::types::Documents; +use std::collections::BTreeMap; +use std::sync::Arc; + +/// What a new proposal asks and the rule it is decided by. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DecisionProposalInput { + /// The question, in one line: 1 to 128 characters. + pub title: String, + /// What a yes and a no mean: 1 to 4096 characters. + pub description: String, + /// Where the proposal is discussed, a URI of at most 512 characters. + pub url: Option, + /// The proposal passes when the yes voting power is strictly more than this percent of the + /// yes plus no voting power: 50 to 80. + pub pass_percent: u8, + /// The least yes plus no voting power the proposal needs, as a percent of the masternode + /// list's total voting power when it closes, rounded up: 0 to 50. + pub minimum_turnout_percent: u8, + /// When voting closes, in milliseconds since the Unix epoch: from a week to four weeks + /// after the block that creates the proposal, which is a little later than now. + pub end_date: TimestampMillis, +} + +/// New text for a proposal. A field left `None` keeps its value. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct DecisionProposalEdit { + /// The new title. + pub title: Option, + /// The new description. + pub description: Option, + /// The new url: `Some(Some(url))` sets it, `Some(None)` removes it. + pub url: Option>, +} + +/// A 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. + pub document: Document, + /// The entropy the document id derives from. + pub entropy: Bytes32, +} + +/// A proposal: its document and the properties read out of it. +#[derive(Debug, Clone, PartialEq)] +pub struct DecisionProposal { + /// The `proposal` document. + pub document: Document, + /// The question, in one line. + pub title: String, + /// What a yes and a no mean. + pub description: String, + /// Where the proposal is discussed. + pub url: Option, + /// The proposal passes when yes is strictly more than this percent of yes plus no. + pub pass_percent: u8, + /// The least yes plus no voting power the proposal needs, as a percent of the network's. + pub minimum_turnout_percent: u8, + /// When voting closes, in milliseconds since the Unix epoch. + pub end_date: TimestampMillis, +} + +impl DecisionProposal { + /// Reads a proposal out of a `proposal` document. + pub fn from_document(document: Document) -> Result { + let malformed = |error: dpp::platform_value::Error| { + Error::Generic(format!("proposal {} is malformed: {error}", document.id())) + }; + let properties = document.properties(); + Ok(Self { + title: properties + .get_string(properties::TITLE) + .map_err(malformed)?, + description: properties + .get_string(properties::DESCRIPTION) + .map_err(malformed)?, + url: properties + .get_optional_string(properties::URL) + .map_err(malformed)?, + pass_percent: properties + .get_integer(properties::PASS_PERCENT) + .map_err(malformed)?, + minimum_turnout_percent: properties + .get_integer(properties::MINIMUM_TURNOUT_PERCENT) + .map_err(malformed)?, + end_date: properties + .get_integer(properties::END_DATE) + .map_err(malformed)?, + document, + }) + } + + /// The proposal's id. + pub fn id(&self) -> Identifier { + self.document.id() + } + + /// The proposer, who paid the fund. + pub fn owner_id(&self) -> Identifier { + self.document.owner_id() + } + + /// The purpose of the proposal's poll, which names it in the poll queries. + pub fn vote_poll_purpose(&self) -> YesNoVotePollPurpose { + YesNoVotePollPurpose::DecisionProposal { + document_id: self.id(), + } + } +} + +/// The end dates a listing by end date covers: from `from` (included) to `to` (left out). An +/// open bound is `None`. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct DecisionProposalEndDates { + /// The earliest end date listed, included. + pub from: Option, + /// The end date the listing stops before. + pub to: Option, +} + +/// Builds a proposal of `owner_id` asking what `input` says, in `contract`, the decision +/// proposals contract, with its id derived from `entropy`. +pub fn build_decision_proposal_document( + contract: &DataContract, + owner_id: Identifier, + 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(), + Value::Text(input.title.clone()), + ), + ( + properties::DESCRIPTION.to_string(), + Value::Text(input.description.clone()), + ), + ( + properties::PASS_PERCENT.to_string(), + Value::U8(input.pass_percent), + ), + ( + properties::MINIMUM_TURNOUT_PERCENT.to_string(), + Value::U8(input.minimum_turnout_percent), + ), + (properties::END_DATE.to_string(), Value::U64(input.end_date)), + ]); + if let Some(url) = &input.url { + properties.insert(properties::URL.to_string(), Value::Text(url.clone())); + } + let document = DocumentV0 { + id: Document::generate_document_id_v0( + &contract.id(), + &owner_id, + PROPOSAL_DOCUMENT_TYPE_NAME, + entropy.as_slice(), + ), + owner_id, + properties, + revision: document_type + .requires_revision() + .then_some(INITIAL_REVISION), + ..Default::default() + } + .into(); + Ok(DecisionProposalDocument { document, entropy }) +} + +/// `proposal` with the new text `edit` gives it and its next revision, ready to be put as a +/// replace. Consensus refuses the replace more than a day after the proposal was created (or a +/// fifth of the time it runs, if that is shorter), and refuses any change to its rule or end +/// date. +pub fn build_decision_proposal_edit( + proposal: &Document, + edit: &DecisionProposalEdit, +) -> Result { + if edit == &DecisionProposalEdit::default() { + return Err(Error::Generic(format!( + "the edit of proposal {} changes nothing", + proposal.id() + ))); + } + let revision = proposal + .revision() + .ok_or_else(|| Error::Generic(format!("proposal {} carries no revision", proposal.id())))?; + let mut document = proposal.clone(); + document.set_revision(Some(revision + 1)); + if let Some(title) = &edit.title { + document.set(properties::TITLE, Value::Text(title.clone())); + } + if let Some(description) = &edit.description { + document.set(properties::DESCRIPTION, Value::Text(description.clone())); + } + match &edit.url { + Some(Some(url)) => document.set(properties::URL, Value::Text(url.clone())), + Some(None) => { + document.remove(properties::URL); + } + None => {} + } + Ok(document) +} + +/// The query for the proposals whose end date is within `end_dates`, by end date, then by +/// creation time (`byEndDate`), one page of them. +fn proposals_by_end_date_query( + contract: Arc, + end_dates: DecisionProposalEndDates, + page: DocumentsPage, +) -> Result { + let end_date_clause = |operator, value| WhereClause { + field: properties::END_DATE.to_string(), + operator, + value, + }; + let range = match (end_dates.from, end_dates.to) { + (Some(from), Some(to)) => Some(end_date_clause( + WhereOperator::BetweenExcludeRight, + Value::Array(vec![Value::U64(from), Value::U64(to)]), + )), + (Some(from), None) => Some(end_date_clause( + WhereOperator::GreaterThanOrEquals, + Value::U64(from), + )), + (None, Some(to)) => Some(end_date_clause(WhereOperator::LessThan, Value::U64(to))), + (None, None) => None, + }; + let mut query = DocumentQuery::new(contract, PROPOSAL_DOCUMENT_TYPE_NAME)?; + if let Some(range) = range { + query = query.with_where(range); + } + paged( + query.with_order_by(OrderClause { + field: properties::END_DATE.to_string(), + ascending: true, + }), + page, + ) +} + +/// The query for the proposals of `owner_id`, by creation time (`byOwner`), one page of them. +fn proposals_by_owner_query( + contract: Arc, + owner_id: Identifier, + page: DocumentsPage, +) -> Result { + let query = DocumentQuery::new(contract, PROPOSAL_DOCUMENT_TYPE_NAME)? + .with_where(WhereClause { + field: "$ownerId".to_string(), + operator: WhereOperator::Equal, + value: Value::Identifier(owner_id.to_buffer()), + }) + // The order clause pins the index: a bare equality on the first property of a + // two-property index is proven absent instead of served. + .with_order_by(OrderClause { + field: "$createdAt".to_string(), + ascending: true, + }); + paged(query, page) +} + +/// The query for every proposal, newest first (`byCreatedAt`), one page of them. +fn proposals_by_created_at_query( + contract: Arc, + page: DocumentsPage, +) -> Result { + let query = + DocumentQuery::new(contract, PROPOSAL_DOCUMENT_TYPE_NAME)?.with_order_by(OrderClause { + field: "$createdAt".to_string(), + ascending: false, + }); + paged(query, page) +} + +/// `query` limited to `page`. +fn paged(query: DocumentQuery, page: DocumentsPage) -> Result { + let mut query = query.with_limit(page.page_size()); + query.start = page + .start_after + .map(|id| Start::StartAfter(id.to_buffer().to_vec())); + Ok(query) +} + +impl Sdk { + /// The decision proposals system contract: from the context provider when it holds it, + /// fetched otherwise. The contract exists from protocol version 15; below 15 the SDK + /// first learns the network's version, and a network still below 15 has no such contract, + /// which is an error. + pub async fn fetch_decision_proposals_contract(&self) -> Result, Error> { + self.require_protocol_version( + DECISION_PROPOSALS_CONTRACT_INITIAL_PROTOCOL_VERSION, + "the decision proposals contract", + ) + .await?; + self.fetch_system_data_contract(DECISION_PROPOSALS_CONTRACT_ID) + .await? + .ok_or_else(|| { + Error::MissingDependency( + "decision proposals contract".to_string(), + DECISION_PROPOSALS_CONTRACT_ID.to_string(Encoding::Base58), + ) + }) + } + + /// Builds a proposal of `owner_id` asking what `input` says (see + /// [`build_decision_proposal_document`]). The result is put like any document create; the + /// owner pays the decision proposal fund on top of the fees. + pub async fn build_decision_proposal( + &self, + owner_id: Identifier, + input: &DecisionProposalInput, + ) -> Result { + let contract = self.fetch_decision_proposals_contract().await?; + let entropy = Bytes32::new(StdRng::from_os_rng().random()); + build_decision_proposal_document(&contract, owner_id, input, entropy) + } + + /// The proposal with id `proposal_id`, `None` when there is none. + pub async fn fetch_decision_proposal( + &self, + proposal_id: Identifier, + ) -> Result, Error> { + let contract = self.fetch_decision_proposals_contract().await?; + let query = DocumentQuery::new(contract, PROPOSAL_DOCUMENT_TYPE_NAME)? + .with_document_id(&proposal_id); + Document::fetch(self, query).await + } + + /// One page of the proposals whose end date is within `end_dates`, by end date, then by + /// creation time. The open ones are those ending from now on. [`DocumentsPage::after`] + /// gives the next page. + pub async fn fetch_decision_proposals_by_end_date( + &self, + end_dates: DecisionProposalEndDates, + page: DocumentsPage, + ) -> Result { + let contract = self.fetch_decision_proposals_contract().await?; + Document::fetch_many( + self, + proposals_by_end_date_query(contract, end_dates, page)?, + ) + .await + } + + /// One page of the proposals of `owner_id`, by creation time. [`DocumentsPage::after`] + /// gives the next page. + pub async fn fetch_decision_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, owner_id, page)?).await + } + + /// One page of every proposal, newest first. [`DocumentsPage::after`] gives the next page. + pub async fn fetch_decision_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, page)?).await + } + + /// A masternode's answer `vote_choice` on the proposal `proposal_id`, to put with + /// [`PutVote`](crate::platform::transition::vote::PutVote). The vote names the proposal's + /// poll by its id. A masternode may vote 5 times on a poll, but not give the answer it + /// already gave; polls exist from protocol version 15. + pub async fn decision_proposal_vote( + &self, + proposal_id: Identifier, + vote_choice: YesNoAbstainVoteChoice, + ) -> Result { + self.yes_no_vote( + &YesNoVotePollPurpose::DecisionProposal { + document_id: proposal_id, + }, + vote_choice, + ) + .await + } + + /// The id of the yes/no poll the proposal `proposal_id` opens, which the vote polls by end + /// date listing and the poll queries name it by. + pub async fn decision_proposal_vote_poll_id( + &self, + proposal_id: Identifier, + ) -> Result { + self.yes_no_vote_poll_id(&YesNoVotePollPurpose::DecisionProposal { + document_id: proposal_id, + }) + .await + } +} + +#[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::{ + decision_proposal_vote_poll_id, DecisionProposalVotePoll, DECISION_PROPOSAL_FUND_NAME, + }; + use dpp::system_data_contracts::{load_system_data_contract, SystemDataContract}; + use dpp::version::PlatformVersion; + use dpp::voting::votes::yes_no_vote::v0::YesNoVoteV0; + use dpp::voting::votes::yes_no_vote::YesNoVote; + use drive::query::DriveDocumentQuery; + + const DAY_MS: u64 = 86_400_000; + + 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 input() -> DecisionProposalInput { + DecisionProposalInput { + title: "Raise the block size?".to_string(), + description: "Yes doubles it; no keeps it.".to_string(), + url: Some("https://forum.dash.org/t/block-size".to_string()), + pass_percent: 60, + minimum_turnout_percent: 10, + end_date: 1_700_000_000_000 + 14 * DAY_MS, + } + } + + /// The document `build_decision_proposal_document` builds, 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 + } + + /// 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_build_a_proposal_the_schema_accepts_and_the_poll_reads() { + let platform_version = PlatformVersion::latest(); + let contract = proposals_contract(); + let owner_id = Identifier::from([3; 32]); + let entropy = Bytes32::new([9; 32]); + let built = build_decision_proposal_document(&contract, owner_id, &input(), entropy) + .expect("builds"); + + assert_eq!(built.entropy, entropy); + assert_eq!(built.document.owner_id(), owner_id); + assert_eq!(built.document.revision(), Some(INITIAL_REVISION)); + assert_eq!( + built.document.id(), + Document::generate_document_id_v0( + &DECISION_PROPOSALS_CONTRACT_ID, + &owner_id, + PROPOSAL_DOCUMENT_TYPE_NAME, + entropy.as_slice(), + ) + ); + let document = stored(&built.document); + let validation = contract + .validate_document(PROPOSAL_DOCUMENT_TYPE_NAME, &document, platform_version) + .expect("validates"); + assert!(validation.is_valid(), "{:?}", validation.errors); + + // The poll consensus opens is the one the proposal's id names + let opened = DecisionProposalVotePoll::from_proposal( + document.id(), + document.properties(), + platform_version, + ) + .expect("active") + .into_data() + .expect("a valid rule"); + assert_eq!(opened.end_date, input().end_date); + assert_eq!(opened.vote_poll.supermajority_numerator, 60); + let proposal = DecisionProposal::from_document(document).expect("reads"); + assert_eq!(opened.vote_poll.purpose, proposal.vote_poll_purpose()); + + // A create built from it states the decision proposal fund + let document_type = contract + .document_type_for_name(PROPOSAL_DOCUMENT_TYPE_NAME) + .expect("the proposal type"); + assert_eq!( + document_type + .prefunded_voting_balance_for_document(&built.document, platform_version) + .expect("active"), + Some((DECISION_PROPOSAL_FUND_NAME.to_string(), 50_000_000_000)) + ); + } + + #[test] + fn should_leave_out_a_url_not_given() { + let platform_version = PlatformVersion::latest(); + let contract = proposals_contract(); + let built = build_decision_proposal_document( + &contract, + Identifier::from([3; 32]), + &DecisionProposalInput { + url: None, + ..input() + }, + Bytes32::new([9; 32]), + ) + .expect("builds"); + assert!(built.document.get(properties::URL).is_none()); + let document = stored(&built.document); + assert!(contract + .validate_document(PROPOSAL_DOCUMENT_TYPE_NAME, &document, platform_version) + .expect("validates") + .is_valid()); + assert_eq!( + DecisionProposal::from_document(document) + .expect("reads") + .url, + None + ); + } + + #[test] + fn should_read_every_property_of_a_proposal() { + let built = build_decision_proposal_document( + &proposals_contract(), + Identifier::from([3; 32]), + &input(), + Bytes32::new([9; 32]), + ) + .expect("builds"); + let proposal = DecisionProposal::from_document(built.document.clone()).expect("reads"); + assert_eq!( + proposal, + DecisionProposal { + document: built.document.clone(), + title: input().title, + description: input().description, + url: input().url, + pass_percent: 60, + minimum_turnout_percent: 10, + end_date: input().end_date, + } + ); + assert_eq!(proposal.id(), built.document.id()); + assert_eq!(proposal.owner_id(), Identifier::from([3; 32])); + + let mut no_title = built.document; + no_title.remove(properties::TITLE); + assert!(DecisionProposal::from_document(no_title).is_err()); + } + + #[test] + fn should_edit_only_the_text_and_move_to_the_next_revision() { + let contract = proposals_contract(); + let proposal = stored( + &build_decision_proposal_document( + &contract, + Identifier::from([3; 32]), + &input(), + Bytes32::new([9; 32]), + ) + .expect("builds") + .document, + ); + + let edited = build_decision_proposal_edit( + &proposal, + &DecisionProposalEdit { + title: Some("Raise the block size to 4 MB?".to_string()), + ..Default::default() + }, + ) + .expect("edits"); + assert_eq!(edited.id(), proposal.id()); + assert_eq!(edited.revision(), Some(INITIAL_REVISION + 1)); + let read = DecisionProposal::from_document(edited).expect("reads"); + assert_eq!(read.title, "Raise the block size to 4 MB?"); + assert_eq!(read.description, input().description); + assert_eq!(read.url, input().url); + assert_eq!( + ( + read.pass_percent, + read.minimum_turnout_percent, + read.end_date + ), + (60, 10, input().end_date) + ); + + let without_url = build_decision_proposal_edit( + &proposal, + &DecisionProposalEdit { + description: Some("Yes doubles it.".to_string()), + url: Some(None), + ..Default::default() + }, + ) + .expect("edits"); + let read = DecisionProposal::from_document(without_url).expect("reads"); + assert_eq!(read.description, "Yes doubles it."); + assert_eq!(read.url, None); + + assert!( + build_decision_proposal_edit(&proposal, &DecisionProposalEdit::default()).is_err(), + "an edit that changes nothing is refused before it is paid for" + ); + } + + #[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 end_dates = [ + DecisionProposalEndDates::default(), + DecisionProposalEndDates { + from: Some(1_700_000_000_000), + to: None, + }, + DecisionProposalEndDates { + from: None, + to: Some(1_800_000_000_000), + }, + DecisionProposalEndDates { + from: Some(1_700_000_000_000), + to: Some(1_800_000_000_000), + }, + ]; + for end_dates in end_dates { + let query = + proposals_by_end_date_query(contract.clone(), end_dates, page).expect("builds"); + assert_eq!(served_through(&query), "byEndDate", "{end_dates:?}"); + assert_eq!(query.limit, 20); + } + assert_eq!( + served_through( + &proposals_by_owner_query(contract.clone(), Identifier::from([3; 32]), page) + .expect("builds") + ), + "byOwner" + ); + let by_created_at = + proposals_by_created_at_query(contract, 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); + } + + #[test] + fn should_name_the_poll_a_vote_answers_by_the_proposal_id() { + let platform_version = PlatformVersion::latest(); + let proposal_id = Identifier::from([4; 32]); + let purpose = YesNoVotePollPurpose::DecisionProposal { + document_id: proposal_id, + }; + assert_eq!( + decision_proposal_vote_poll_id(proposal_id, platform_version).expect("active"), + purpose.unique_id(platform_version).expect("active") + ); + } + + #[tokio::test] + async fn should_build_a_vote_on_the_proposal_poll() { + let sdk = crate::SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .build() + .expect("a mock sdk"); + let proposal_id = Identifier::from([4; 32]); + let vote = sdk + .decision_proposal_vote(proposal_id, YesNoAbstainVoteChoice::No) + .await + .expect("builds"); + assert_eq!( + sdk.decision_proposal_vote_poll_id(proposal_id) + .await + .expect("derives"), + decision_proposal_vote_poll_id(proposal_id, PlatformVersion::latest()).expect("active") + ); + assert_eq!( + vote, + Vote::YesNoVote(YesNoVote::V0(YesNoVoteV0 { + vote_poll_id: decision_proposal_vote_poll_id( + proposal_id, + PlatformVersion::latest() + ) + .expect("active"), + vote_choice: YesNoAbstainVoteChoice::No, + })) + ); + } +} diff --git a/packages/rs-sdk/src/platform/documents/mod.rs b/packages/rs-sdk/src/platform/documents/mod.rs index 5bf12321fb8..4b8d63789c9 100644 --- a/packages/rs-sdk/src/platform/documents/mod.rs +++ b/packages/rs-sdk/src/platform/documents/mod.rs @@ -15,6 +15,8 @@ pub mod chained_document_query_sdk; pub mod contest_fund; pub mod document_query_sdk; mod fetch_bindings; +pub mod page; pub mod transitions; pub use document_query_sdk::DocumentQuerySdk; +pub use page::DocumentsPage; diff --git a/packages/rs-sdk/src/platform/documents/page.rs b/packages/rs-sdk/src/platform/documents/page.rs new file mode 100644 index 00000000000..6418ab6999a --- /dev/null +++ b/packages/rs-sdk/src/platform/documents/page.rs @@ -0,0 +1,72 @@ +//! One page of a document listing that continues after the last document of the page before. + +use crate::platform::Identifier; +use drive_proof_verifier::types::Documents; + +/// The most documents one query returns, the platform's cap. +pub const MAX_DOCUMENTS_PAGE_SIZE: u32 = 100; + +/// One page of a listing: at most `limit` documents (the platform's cap of 100 when `None` or +/// 0), after the document `start_after` in the index's order. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct DocumentsPage { + /// How many documents at most; `None` and 0 are 100. + pub limit: Option, + /// The id of the last document of the previous page; `None` for the first page. + pub start_after: Option, +} + +impl DocumentsPage { + /// The page after the one `page` holds, `None` when `page` was the last: it held fewer + /// documents than the limit. + pub fn after(&self, page: &Documents) -> Option { + let limit = self.page_size(); + if page.len() < limit as usize { + return None; + } + page.keys().last().map(|last| Self { + limit: self.limit, + start_after: Some(*last), + }) + } + + /// The number of documents a page holds when it is full. + pub fn page_size(&self) -> u32 { + match self.limit { + None | Some(0) => MAX_DOCUMENTS_PAGE_SIZE, + Some(limit) => limit, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn should_page_after_the_last_document_of_a_full_page_only() { + let page = DocumentsPage { + limit: Some(2), + start_after: None, + }; + let full: Documents = [Identifier::from([1; 32]), Identifier::from([2; 32])] + .into_iter() + .map(|id| (id, None)) + .collect(); + assert_eq!( + page.after(&full), + Some(DocumentsPage { + limit: Some(2), + start_after: Some(Identifier::from([2; 32])), + }) + ); + let short: Documents = [(Identifier::from([1; 32]), None)].into_iter().collect(); + assert_eq!(page.after(&short), None); + // A limit of 0 is the platform's default of 100, so two documents are a short page + let default_size = DocumentsPage { + limit: Some(0), + start_after: None, + }; + assert_eq!(default_size.after(&full), None); + } +} diff --git a/packages/rs-sdk/src/platform/moderation_charters/mod.rs b/packages/rs-sdk/src/platform/moderation_charters/mod.rs index d73e1283b6d..d9942c10fcf 100644 --- a/packages/rs-sdk/src/platform/moderation_charters/mod.rs +++ b/packages/rs-sdk/src/platform/moderation_charters/mod.rs @@ -53,16 +53,11 @@ impl Sdk { /// does not parse at 13, so below 14 the SDK first learns the network's version; a network /// still below 14 has no such contract, which is an error. pub async fn fetch_moderation_charters_contract(&self) -> Result, Error> { - if self.protocol_version_number() < MODERATION_CHARTERS_CONTRACT_INITIAL_PROTOCOL_VERSION { - let version = self.refresh_protocol_version().await?; - if version < MODERATION_CHARTERS_CONTRACT_INITIAL_PROTOCOL_VERSION { - return Err(Error::Generic(format!( - "the moderation charters contract exists from protocol version \ - {MODERATION_CHARTERS_CONTRACT_INITIAL_PROTOCOL_VERSION}; the SDK runs \ - protocol version {version}" - ))); - } - } + self.require_protocol_version( + MODERATION_CHARTERS_CONTRACT_INITIAL_PROTOCOL_VERSION, + "the moderation charters contract", + ) + .await?; self.fetch_system_data_contract(MODERATION_CHARTERS_CONTRACT_ID) .await? .ok_or_else(|| { diff --git a/packages/rs-sdk/src/platform/moderation_charters/readers.rs b/packages/rs-sdk/src/platform/moderation_charters/readers.rs index 89d253077c0..a60f5bef9c8 100644 --- a/packages/rs-sdk/src/platform/moderation_charters/readers.rs +++ b/packages/rs-sdk/src/platform/moderation_charters/readers.rs @@ -2,6 +2,7 @@ use super::ModerationTeam; use crate::platform::documents::document_query::DocumentQuery; +use crate::platform::documents::page::{DocumentsPage, MAX_DOCUMENTS_PAGE_SIZE}; use crate::platform::{DataContract, Document, Fetch, FetchMany}; use crate::{Error, Sdk}; use dapi_grpc::platform::v0::get_documents_request::get_documents_request_v0::Start; @@ -19,47 +20,14 @@ use std::collections::BTreeSet; use std::future::Future; use std::sync::Arc; -/// The most documents one query returns, the platform's cap. -const MAX_PAGE_SIZE: u32 = 100; - /// How many full pages a reader that must see every document (the team's additions and /// removals, a charter's resignation requests) fetches before it gives up rather than answer /// from part of the set. Nothing caps additions per charter until seating lands (it will /// allow at most 15), so the budget only bounds a loop over a set a leader could grow at will. const MAX_PAGES_PER_READ: u32 = 50; -/// One page of a listing: at most `limit` documents (the platform's cap of 100 when `None` or -/// 0), after the document `start_after` in the index's order. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct CharterDocumentsPage { - /// How many documents at most; `None` and 0 are 100. - pub limit: Option, - /// The id of the last document of the previous page; `None` for the first page. - pub start_after: Option, -} - -impl CharterDocumentsPage { - /// The page after the one `page` holds, `None` when `page` was the last: it held fewer - /// documents than the limit. - pub fn after(&self, page: &Documents) -> Option { - let limit = self.page_size(); - if page.len() < limit as usize { - return None; - } - page.keys().last().map(|last| Self { - limit: self.limit, - start_after: Some(*last), - }) - } - - /// The number of documents a page holds when it is full. - fn page_size(&self) -> u32 { - match self.limit { - None | Some(0) => MAX_PAGE_SIZE, - Some(limit) => limit, - } - } -} +/// One page of a listing of the moderation charters contract's documents. +pub type CharterDocumentsPage = DocumentsPage; /// A contract's seated charter: its `electedCharter` document and the properties read out of /// it. Its owner is the leader. @@ -459,7 +427,7 @@ where } Err(Error::Generic(format!( "more than {} moderation charter documents match; refusing to answer from part of them", - MAX_PAGES_PER_READ * MAX_PAGE_SIZE + MAX_PAGES_PER_READ * MAX_DOCUMENTS_PAGE_SIZE ))) } @@ -562,33 +530,6 @@ mod tests { .is_some()); } - #[test] - fn should_page_after_the_last_document_of_a_full_page_only() { - let page = CharterDocumentsPage { - limit: Some(2), - start_after: None, - }; - let full: Documents = [Identifier::from([1; 32]), Identifier::from([2; 32])] - .into_iter() - .map(|id| (id, None)) - .collect(); - assert_eq!( - page.after(&full), - Some(CharterDocumentsPage { - limit: Some(2), - start_after: Some(Identifier::from([2; 32])), - }) - ); - let short: Documents = [(Identifier::from([1; 32]), None)].into_iter().collect(); - assert_eq!(page.after(&short), None); - // A limit of 0 is the platform's default of 100, so two documents are a short page - let default_size = CharterDocumentsPage { - limit: Some(0), - start_after: None, - }; - assert_eq!(default_size.after(&full), None); - } - fn document(id: u32, owner: u8) -> Document { let mut bytes = [0u8; 32]; bytes[..4].copy_from_slice(&id.to_be_bytes()); @@ -624,7 +565,7 @@ mod tests { #[tokio::test] async fn should_read_a_set_of_exactly_the_page_budget_in_full() { - let budget = MAX_PAGES_PER_READ * MAX_PAGE_SIZE; + let budget = MAX_PAGES_PER_READ * MAX_DOCUMENTS_PAGE_SIZE; let documents = collect_every_page(serve_pages(budget)) .await .expect("a set of exactly the budget is complete"); @@ -636,7 +577,7 @@ mod tests { #[tokio::test] async fn should_refuse_a_set_larger_than_the_page_budget() { - let budget = MAX_PAGES_PER_READ * MAX_PAGE_SIZE; + let budget = MAX_PAGES_PER_READ * MAX_DOCUMENTS_PAGE_SIZE; assert!(collect_every_page(serve_pages(budget + 1)).await.is_err()); } diff --git a/packages/rs-sdk/src/platform/system_data_contract.rs b/packages/rs-sdk/src/platform/system_data_contract.rs index 66953140548..f0da9d1b36e 100644 --- a/packages/rs-sdk/src/platform/system_data_contract.rs +++ b/packages/rs-sdk/src/platform/system_data_contract.rs @@ -4,9 +4,33 @@ use crate::platform::{DataContract, Fetch, Identifier}; use crate::{Error, Sdk}; use dash_context_provider::ContextProvider; +use dpp::version::ProtocolVersion; use std::sync::Arc; impl Sdk { + /// Fails unless the network runs `initial_protocol_version` or later, the version + /// `feature` exists from. + /// + /// An unpinned SDK starts mainnet and testnet at 13 and only learns a newer version from a + /// verified response, so below `initial_protocol_version` the SDK first learns the + /// network's version; a network still below it does not have the feature. + pub(crate) async fn require_protocol_version( + &self, + initial_protocol_version: ProtocolVersion, + feature: &str, + ) -> Result<(), Error> { + if self.protocol_version_number() < initial_protocol_version { + let version = self.refresh_protocol_version().await?; + if version < initial_protocol_version { + return Err(Error::Generic(format!( + "{feature} exists from protocol version {initial_protocol_version}; the SDK \ + runs protocol version {version}" + ))); + } + } + Ok(()) + } + /// The system data contract `contract_id`, from the context provider when it holds it at /// the SDK's protocol version, fetched and proved otherwise. `None` when the network has no /// such contract. diff --git a/packages/rs-sdk/src/platform/yes_no_vote_polls.rs b/packages/rs-sdk/src/platform/yes_no_vote_polls.rs index f4557a5d39d..42a593cbcb3 100644 --- a/packages/rs-sdk/src/platform/yes_no_vote_polls.rs +++ b/packages/rs-sdk/src/platform/yes_no_vote_polls.rs @@ -2,10 +2,10 @@ //! answer on a poll (`getMasternodeYesNoVote`), both read by the poll's id. Nodes serve them //! from protocol version 15, and the SDK sends neither before the network has proven 15. //! -//! A query names the poll by its id, or by the whole [`YesNoVotePoll`] (see +//! A query names the poll by its id, by its purpose or by the whole [`YesNoVotePoll`] (see //! [`QueriedYesNoVotePoll`]): the polls the end date listing (`getVotePollsByEndDate`) -//! returns and the poll a [`YesNoVote`](dpp::voting::votes::yes_no_vote::YesNoVote) carries -//! can be passed as they are. +//! returns can be passed as they are, and a decision proposal's poll is named by +//! [`YesNoVotePollPurpose::DecisionProposal`] with the proposal's id. //! //! [`YesNoVotePollState::fetch`] answers `None` for a poll never opened. While the poll is open //! its stored info is started and the tallies are the voting power cast so far; once it @@ -16,54 +16,63 @@ //! Both types also implement [`FetchUnproved`] for the unverified fast path. use crate::platform::{Fetch, FetchUnproved, Identifier, Query, QuerySettings}; -use crate::Error; +use crate::{Error, Sdk}; use dapi_grpc::platform::v0::get_masternode_yes_no_vote_request::GetMasternodeYesNoVoteRequestV0; use dapi_grpc::platform::v0::get_yes_no_vote_poll_state_request::GetYesNoVotePollStateRequestV0; use dapi_grpc::platform::v0::{ get_masternode_yes_no_vote_request, get_yes_no_vote_poll_state_request, GetMasternodeYesNoVoteRequest, GetYesNoVotePollStateRequest, }; +use dpp::version::feature_initial_protocol_versions::YES_NO_VOTE_POLL_INITIAL_PROTOCOL_VERSION; use dpp::version::PlatformVersion; -use dpp::voting::vote_polls::yes_no_vote_poll::YesNoVotePoll; +use dpp::voting::vote_choices::yes_no_abstain_vote_choice::YesNoAbstainVoteChoice; +use dpp::voting::vote_polls::yes_no_vote_poll::{YesNoVotePoll, YesNoVotePollPurpose}; +use dpp::voting::votes::yes_no_vote::v0::YesNoVoteV0; +use dpp::voting::votes::yes_no_vote::YesNoVote; +use dpp::voting::votes::Vote; pub use drive_proof_verifier::types::yes_no_vote_polls::{MasternodeYesNoVote, YesNoVotePollState}; -/// The yes/no vote poll a query names: its id, or the poll itself. +/// The yes/no vote poll a query names: its id, its purpose, or the poll itself. /// -/// A poll's id is derived with the protocol version ([`YesNoVotePoll::unique_id`]), and no -/// version before 15 derives one. For a poll, the SDK derives the id each time it builds the -/// request, with the version it speaks then. An SDK at 14 or earlier first builds the request -/// only to learn the version it needs, so it can ask the network whether it runs 15; that -/// request carries the id the newest version this build knows derives. A network SDK sends a +/// A poll's id is derived from its purpose with the protocol version +/// ([`YesNoVotePollPurpose::unique_id`]), and no version before 15 derives one. For a purpose +/// or a poll, the SDK derives the id each time it builds the request, with the version it +/// speaks then. An SDK at 14 or earlier first builds the request only to learn the version it +/// needs, so it can ask the network whether it runs 15; that request carries the id the +/// newest version this build knows derives. A network SDK sends a /// request needing 15 only once the network has proven 15, and builds it again first, with /// the version it then speaks. #[derive(Debug, Clone, PartialEq, Eq)] pub enum QueriedYesNoVotePoll { - /// The poll's id, as [`YesNoVotePoll::unique_id`] derives it. + /// The poll's id, as [`YesNoVotePollPurpose::unique_id`] derives it. Id(Identifier), - /// The poll, whose id the SDK derives when it builds the request. + /// The poll's purpose, such as a decision proposal, whose id the SDK derives when it + /// builds the request. + Purpose(YesNoVotePollPurpose), + /// The poll, whose id the SDK derives from its purpose when it builds the request. Poll(YesNoVotePoll), } impl QueriedYesNoVotePoll { /// The id the request names the poll by, under `settings`. fn vote_poll_id(&self, settings: &QuerySettings<'_>) -> Result { - match self { - QueriedYesNoVotePoll::Id(vote_poll_id) => Ok(*vote_poll_id), - QueriedYesNoVotePoll::Poll(vote_poll) => { - let derives_poll_ids = settings - .protocol_version - .dpp - .voting_versions - .yes_no_vote_poll_id - .is_some(); - let platform_version = if derives_poll_ids { - settings.protocol_version - } else { - PlatformVersion::latest() - }; - Ok(vote_poll.unique_id(platform_version)?) - } - } + let purpose = match self { + QueriedYesNoVotePoll::Id(vote_poll_id) => return Ok(*vote_poll_id), + QueriedYesNoVotePoll::Purpose(purpose) => purpose, + QueriedYesNoVotePoll::Poll(vote_poll) => &vote_poll.purpose, + }; + let derives_poll_ids = settings + .protocol_version + .dpp + .voting_versions + .yes_no_vote_poll_id + .is_some(); + let platform_version = if derives_poll_ids { + settings.protocol_version + } else { + PlatformVersion::latest() + }; + Ok(purpose.unique_id(platform_version)?) } } @@ -73,6 +82,12 @@ impl From for QueriedYesNoVotePoll { } } +impl From for QueriedYesNoVotePoll { + fn from(purpose: YesNoVotePollPurpose) -> Self { + QueriedYesNoVotePoll::Purpose(purpose) + } +} + impl From for QueriedYesNoVotePoll { fn from(vote_poll: YesNoVotePoll) -> Self { QueriedYesNoVotePoll::Poll(vote_poll) @@ -87,7 +102,7 @@ pub struct YesNoVotePollStateQuery { } impl YesNoVotePollStateQuery { - /// The query for the state of `vote_poll`, named by its id or given whole. + /// The query for the state of `vote_poll`, named by its id or purpose, or given whole. pub fn new(vote_poll: impl Into) -> Self { YesNoVotePollStateQuery { vote_poll: vote_poll.into(), @@ -139,7 +154,8 @@ pub struct MasternodeYesNoVoteQuery { } impl MasternodeYesNoVoteQuery { - /// The query for the masternode's answer on `vote_poll`, named by its id or given whole. + /// The query for the masternode's answer on `vote_poll`, named by its id or purpose, or + /// given whole. pub fn new(pro_tx_hash: Identifier, vote_poll: impl Into) -> Self { MasternodeYesNoVoteQuery { pro_tx_hash, @@ -171,16 +187,44 @@ impl FetchUnproved for MasternodeYesNoVote { type Request = GetMasternodeYesNoVoteRequest; } +impl Sdk { + /// The id of the yes/no poll with `purpose`, derived with the protocol version the SDK + /// speaks. Below 15, which no poll exists before, the SDK first learns the network's + /// version; a network still below 15 has no polls, which is an error. + pub async fn yes_no_vote_poll_id( + &self, + purpose: &YesNoVotePollPurpose, + ) -> Result { + self.require_protocol_version( + YES_NO_VOTE_POLL_INITIAL_PROTOCOL_VERSION, + "yes/no vote polls", + ) + .await?; + Ok(purpose.unique_id(self.version())?) + } + + /// A masternode's answer `vote_choice` on the yes/no poll with `purpose`, to put with + /// [`PutVote`](crate::platform::transition::vote::PutVote). The vote names the poll by + /// its id ([`Sdk::yes_no_vote_poll_id`]). + pub async fn yes_no_vote( + &self, + purpose: &YesNoVotePollPurpose, + vote_choice: YesNoAbstainVoteChoice, + ) -> Result { + Ok(Vote::YesNoVote(YesNoVote::V0(YesNoVoteV0 { + vote_poll_id: self.yes_no_vote_poll_id(purpose).await?, + vote_choice, + }))) + } +} + #[cfg(all(test, feature = "mocks"))] mod tests { use super::*; use crate::{Sdk, SdkBuilder}; use dpp::block::block_info::BlockInfo; - use dpp::voting::vote_choices::yes_no_abstain_vote_choice::YesNoAbstainVoteChoice; use dpp::voting::vote_info_storage::yes_no_vote_poll_stored_info::v0::YesNoVotePollStoredInfoV0; - use dpp::voting::vote_polls::yes_no_vote_poll::{ - YesNoMinimumVotingPower, YesNoVotePollPurpose, - }; + use dpp::voting::vote_polls::yes_no_vote_poll::YesNoMinimumVotingPower; fn mock_sdk() -> Sdk { SdkBuilder::new_mock() @@ -217,6 +261,38 @@ mod tests { assert_eq!(v0.prove, settings.prove); } + /// A decision proposal's poll is named by its purpose alone, the proposal's id: the + /// request names the id the whole poll would. + #[test] + fn should_name_a_poll_by_its_purpose_as_by_the_whole_poll() { + let sdk = mock_sdk(); + let pro_tx_hash = Identifier::new([1; 32]); + for settings in [ + sdk.query_settings(), + QuerySettings { + protocol_version: PlatformVersion::get(14).expect("protocol 14"), + ..sdk.query_settings() + }, + ] { + let by_purpose: GetYesNoVotePollStateRequest = + YesNoVotePollStateQuery::new(poll().purpose) + .query(&settings) + .expect("request"); + let by_poll: GetYesNoVotePollStateRequest = poll().query(&settings).expect("request"); + assert_eq!(by_purpose, by_poll); + + let by_purpose: GetMasternodeYesNoVoteRequest = + MasternodeYesNoVoteQuery::new(pro_tx_hash, poll().purpose) + .query(&settings) + .expect("request"); + let by_poll: GetMasternodeYesNoVoteRequest = + MasternodeYesNoVoteQuery::new(pro_tx_hash, poll()) + .query(&settings) + .expect("request"); + assert_eq!(by_purpose, by_poll); + } + } + /// No version before 15 derives a poll id, so an SDK at 14 builds the request (which only /// tells it the version to ask the network for) with the id the newest version derives. #[test] diff --git a/packages/wasm-sdk/src/decision_proposals.rs b/packages/wasm-sdk/src/decision_proposals.rs new file mode 100644 index 00000000000..819e3c20baf --- /dev/null +++ b/packages/wasm-sdk/src/decision_proposals.rs @@ -0,0 +1,484 @@ +//! Decision proposals (protocol version 15): yes/no questions any identity puts to the +//! 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. + +use crate::error::WasmSdkError; +use crate::queries::utils::documents_map; +use crate::queries::voting::yes_no::{state_to_js, vote_to_js}; +use crate::sdk::WasmSdk; +use crate::state_transitions::identity::yes_no_vote_choice_from_options; +use dash_sdk::dpp::decision_proposal::{ + is_decision_proposal, DECISION_PROPOSALS_CONTRACT_ID, PROPOSAL_DOCUMENT_TYPE_NAME, +}; +use dash_sdk::dpp::document::Document; +use dash_sdk::dpp::voting::vote_polls::yes_no_vote_poll::YesNoVotePollPurpose; +use dash_sdk::platform::decision_proposals::{ + build_decision_proposal_edit, DecisionProposalEdit, DecisionProposalEndDates, + DecisionProposalInput, +}; +use dash_sdk::platform::documents::DocumentsPage; +use dash_sdk::platform::yes_no_vote_polls::{ + MasternodeYesNoVote, MasternodeYesNoVoteQuery, YesNoVotePollState, YesNoVotePollStateQuery, +}; +use dash_sdk::platform::{Fetch, Identifier}; +use drive_proof_verifier::types::Documents; +use js_sys::{Map, Reflect}; +use wasm_bindgen::prelude::wasm_bindgen; +use wasm_bindgen::JsValue; +use wasm_dpp2::data_contract::document::DocumentWasm; +use wasm_dpp2::identifier::{IdentifierLikeJs, IdentifierWasm}; +use wasm_dpp2::utils::{ + try_from_options_optional_with, try_from_options_with, try_to_string, try_to_u32, try_to_u64, + try_to_u8, +}; +use wasm_dpp2::voting::vote::VoteWasm; + +#[wasm_bindgen(typescript_custom_section)] +const DECISION_PROPOSALS_TS: &'static str = r#" +/** + * Options for `buildDecisionProposal`: a yes/no question put to the masternodes (protocol + * version 15). Creating the proposal opens its vote poll; the owner pays the decision + * proposal fund, 0.5 Dash, on top of the fees. + */ +export interface DecisionProposalOptions { + /** The proposer, the document's owner. */ + ownerId: IdentifierLike; + /** The question, in one line: 1 to 128 characters. */ + title: string; + /** What a yes and a no mean: 1 to 4096 characters. */ + description: string; + /** Where the proposal is discussed, a URI of at most 512 characters. */ + url?: string; + /** + * The proposal passes when the yes voting power is strictly more than this percent of the + * yes plus no voting power: 50 to 80. + */ + passPercent: number; + /** + * The least yes plus no voting power the proposal needs, as a percent of the masternode + * list's total voting power when it closes, rounded up: 0 to 50. + */ + minimumTurnoutPercent: number; + /** + * When voting closes, in milliseconds since the Unix epoch: from a week to four weeks after + * the block that creates the proposal, which is a little later than now. + */ + endDate: bigint | number; +} + +/** + * New text for a proposal (`buildDecisionProposalEdit`). A field left out keeps its value. + * Platform accepts the edit for a day after the proposal is created; the rule and the end + * date never change. + */ +export interface DecisionProposalEdit { + /** The new title. */ + title?: string; + /** The new description. */ + description?: string; + /** The new url; `null` removes it. */ + url?: string | null; +} + +/** One page of the proposals by end date (`getDecisionProposalsByEndDate`). */ +export interface DecisionProposalsByEndDateQuery { + /** + * The earliest end date listed, included. The current time lists the open proposals. + * Omit it for no lower bound. + */ + endDateFrom?: bigint | number; + /** The end date the listing stops before. Omit it for no upper bound. */ + endDateTo?: bigint | number; + /** Continue after this proposal; omit for the first page. */ + startAfter?: IdentifierLike; + /** + * Maximum number of proposals to return, 1 to 100. + * @default 100 + */ + limit?: number; +} + +/** One page of an identity's proposals (`getDecisionProposalsByOwner`). */ +export interface DecisionProposalsByOwnerQuery { + /** The proposer. */ + ownerId: IdentifierLike; + /** Continue after this proposal; omit for the first page. */ + startAfter?: IdentifierLike; + /** + * Maximum number of proposals to return, 1 to 100. + * @default 100 + */ + limit?: number; +} + +/** One page of every proposal, newest first (`getDecisionProposalsByCreatedAt`). */ +export interface DecisionProposalsPageQuery { + /** Continue after this proposal; omit for the first page. */ + startAfter?: IdentifierLike; + /** + * Maximum number of proposals to return, 1 to 100. + * @default 100 + */ + limit?: number; +} + +/** Options for `decisionProposalVote`: a masternode's answer on a proposal. */ +export interface DecisionProposalVoteOptions { + /** + * 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. A masternode may vote 5 times on a proposal, but not give the answer it + * already gave. + */ + voteChoice: YesNoAbstainVoteChoiceName; + /** 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 = "DecisionProposalOptions")] + pub type DecisionProposalOptionsJs; + + #[wasm_bindgen(typescript_type = "DecisionProposalEdit")] + pub type DecisionProposalEditJs; + + #[wasm_bindgen(typescript_type = "DecisionProposalsByEndDateQuery")] + pub type DecisionProposalsByEndDateQueryJs; + + #[wasm_bindgen(typescript_type = "DecisionProposalsByOwnerQuery")] + pub type DecisionProposalsByOwnerQueryJs; + + #[wasm_bindgen(typescript_type = "DecisionProposalsPageQuery")] + pub type DecisionProposalsPageQueryJs; + + #[wasm_bindgen(typescript_type = "DecisionProposalVoteOptions")] + pub type DecisionProposalVoteOptionsJs; +} + +/// A required string option. +fn string_option(options: &JsValue, property: &str) -> Result { + Ok(try_from_options_with(options, property, |value| { + try_to_string(value, property) + })?) +} + +/// An optional string option. +fn optional_string_option( + options: &JsValue, + property: &str, +) -> Result, WasmSdkError> { + Ok(try_from_options_optional_with( + options, + property, + |value| try_to_string(value, property), + )?) +} + +/// An optional end date option. +fn optional_end_date_option( + options: &JsValue, + property: &str, +) -> Result, WasmSdkError> { + Ok(try_from_options_optional_with( + options, + property, + |value| try_to_u64(value, property), + )?) +} + +/// The page a listing query asks for: `startAfter` and `limit`, each optional. An absent query +/// is the first page of 100. +fn page_of(query: &JsValue) -> Result { + if query.is_undefined() || query.is_null() { + return Ok(DocumentsPage::default()); + } + let start_after = + IdentifierWasm::try_from_optional_options(query, "startAfter")?.map(Identifier::from); + let limit = try_from_options_optional_with(query, "limit", |value| try_to_u32(value, "limit"))?; + Ok(DocumentsPage { limit, start_after }) +} + +fn proposal_wasm(document: Document, entropy: Option<[u8; 32]>) -> DocumentWasm { + DocumentWasm::new( + document, + DECISION_PROPOSALS_CONTRACT_ID, + PROPOSAL_DOCUMENT_TYPE_NAME.to_string(), + entropy, + ) +} + +fn proposals_map(documents: Documents) -> Map { + documents_map( + documents, + DECISION_PROPOSALS_CONTRACT_ID, + PROPOSAL_DOCUMENT_TYPE_NAME, + ) +} + +fn proposal_purpose(proposal_id: IdentifierLikeJs) -> Result { + let document_id: Identifier = proposal_id.try_into()?; + Ok(YesNoVotePollPurpose::DecisionProposal { document_id }) +} + +#[wasm_bindgen] +impl WasmSdk { + /// Builds a proposal: a `proposal` document of the decision proposals contract with a + /// fresh entropy, to create with `documentCreate`. The create states the decision proposal + /// fund itself. Platform refuses a rule outside the contract's limits and an end date less + /// than a week or more than four weeks after the block that creates the proposal. The id + /// is final once `documentCreate` returns the stored document. + /// + /// @param options - The proposer, the question and its rule. + /// @returns The proposal, ready for `documentCreate`. + #[wasm_bindgen(js_name = "buildDecisionProposal")] + pub async fn build_decision_proposal( + &self, + options: DecisionProposalOptionsJs, + ) -> Result { + let options: JsValue = options.into(); + let owner_id: Identifier = IdentifierWasm::try_from_options(&options, "ownerId")?.into(); + let input = DecisionProposalInput { + title: string_option(&options, "title")?, + description: string_option(&options, "description")?, + url: optional_string_option(&options, "url")?, + pass_percent: try_from_options_with(&options, "passPercent", |value| { + try_to_u8(value, "passPercent") + })?, + minimum_turnout_percent: try_from_options_with( + &options, + "minimumTurnoutPercent", + |value| try_to_u8(value, "minimumTurnoutPercent"), + )?, + end_date: try_from_options_with(&options, "endDate", |value| { + try_to_u64(value, "endDate") + })?, + }; + let built = self + .as_ref() + .build_decision_proposal(owner_id, &input) + .await?; + Ok(proposal_wasm(built.document, Some(built.entropy.0))) + } + + /// A proposal with new text and its next revision, to replace with `documentReplace`. + /// Platform accepts the edit for a day after the proposal is created; the rule and the + /// end date never change. A document that is not a proposal is refused. + /// + /// @param proposal - The proposal as stored, from `getDecisionProposal`. + /// @param edit - The new title, description or url; `url: null` removes the url. + /// @returns The edited proposal. + #[wasm_bindgen(js_name = "buildDecisionProposalEdit")] + pub fn build_decision_proposal_edit( + &self, + proposal: &DocumentWasm, + edit: DecisionProposalEditJs, + ) -> Result { + let edit: JsValue = edit.into(); + let url = Reflect::get(&edit, &JsValue::from_str("url")) + .map_err(|_| WasmSdkError::invalid_argument("cannot read url"))?; + let url = if url.is_undefined() { + None + } else if url.is_null() { + Some(None) + } else { + Some(Some(try_to_string(&url, "url")?)) + }; + let edit = DecisionProposalEdit { + title: optional_string_option(&edit, "title")?, + description: optional_string_option(&edit, "description")?, + url, + }; + let contract_id: Identifier = proposal.data_contract_id().into(); + if !is_decision_proposal(&contract_id, &proposal.document_type_name()) { + return Err(WasmSdkError::invalid_argument(format!( + "a {} document of contract {contract_id} is not a decision proposal", + proposal.document_type_name() + ))); + } + let document: Document = proposal.clone().into(); + Ok(proposal_wasm( + build_decision_proposal_edit(&document, &edit)?, + None, + )) + } + + /// A proposal by id. + /// + /// @param proposalId - The proposal. + /// @returns The `proposal` document, or undefined when there is none. + #[wasm_bindgen(js_name = "getDecisionProposal")] + pub async fn get_decision_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_decision_proposal(proposal_id) + .await? + .map(|document| proposal_wasm(document, None))) + } + + /// One page of the proposals whose end date is within the query's bounds, by end date, + /// then by creation time. `endDateFrom: Date.now()` lists the open proposals. + /// + /// @returns The proposals by id; pass the last id as `startAfter` for the next page. + #[wasm_bindgen( + js_name = "getDecisionProposalsByEndDate", + unchecked_return_type = "Map" + )] + pub async fn get_decision_proposals_by_end_date( + &self, + query: Option, + ) -> Result { + let query: JsValue = query.map(Into::into).unwrap_or(JsValue::UNDEFINED); + let end_dates = if query.is_undefined() || query.is_null() { + DecisionProposalEndDates::default() + } else { + DecisionProposalEndDates { + from: optional_end_date_option(&query, "endDateFrom")?, + to: optional_end_date_option(&query, "endDateTo")?, + } + }; + let documents = self + .as_ref() + .fetch_decision_proposals_by_end_date(end_dates, page_of(&query)?) + .await?; + Ok(proposals_map(documents)) + } + + /// One page of an identity's proposals, by creation time. + /// + /// @returns The proposals by id; pass the last id as `startAfter` for the next page. + #[wasm_bindgen( + js_name = "getDecisionProposalsByOwner", + unchecked_return_type = "Map" + )] + pub async fn get_decision_proposals_by_owner( + &self, + query: DecisionProposalsByOwnerQueryJs, + ) -> 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_decision_proposals_by_owner(owner_id, page_of(&query)?) + .await?; + Ok(proposals_map(documents)) + } + + /// One page of every proposal, newest first. + /// + /// @returns The proposals by id; pass the last id as `startAfter` for the next page. + #[wasm_bindgen( + js_name = "getDecisionProposalsByCreatedAt", + unchecked_return_type = "Map" + )] + pub async fn get_decision_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_decision_proposals_by_created_at(page_of(&query)?) + .await?; + Ok(proposals_map(documents)) + } + + /// The id of a proposal's yes/no poll, the id `getVotePollsByEndDate` lists it under and + /// votes name it by. + /// + /// @param proposalId - The proposal. + /// @returns The poll's id. + #[wasm_bindgen(js_name = "getDecisionProposalPollId")] + pub async fn get_decision_proposal_poll_id( + &self, + #[wasm_bindgen(js_name = "proposalId")] proposal_id: IdentifierLikeJs, + ) -> Result { + let proposal_id: Identifier = proposal_id.try_into()?; + Ok(self + .as_ref() + .decision_proposal_vote_poll_id(proposal_id) + .await? + .into()) + } + + /// The status and tallies of a proposal's poll: started, with the voting power cast so + /// far, or finished, with the result it records. `undefined` for a proposal never created. + /// + /// # Example + /// ```javascript + /// const state = await sdk.getDecisionProposalPollState(proposalId); + /// if (state?.status === 'finished') console.log(state.result.passed); + /// ``` + #[wasm_bindgen( + js_name = "getDecisionProposalPollState", + unchecked_return_type = "YesNoVotePollState | undefined" + )] + pub async fn get_decision_proposal_poll_state( + &self, + #[wasm_bindgen(js_name = "proposalId")] proposal_id: IdentifierLikeJs, + ) -> Result { + let query = YesNoVotePollStateQuery::new(proposal_purpose(proposal_id)?); + let state = YesNoVotePollState::fetch(self.as_ref(), query).await?; + state_to_js(state) + } + + /// A masternode's answer on a proposal and how many times it has voted on it. `undefined` + /// when the masternode has not voted on it, and once the poll finished. + #[wasm_bindgen( + js_name = "getMasternodeDecisionProposalVote", + unchecked_return_type = "MasternodeYesNoVote | undefined" + )] + pub async fn get_masternode_decision_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 query = MasternodeYesNoVoteQuery::new(pro_tx_hash, proposal_purpose(proposal_id)?); + let vote = MasternodeYesNoVote::fetch(self.as_ref(), query).await?; + vote_to_js(vote) + } + + /// Votes on a proposal for a masternode: builds the vote, signs it with the voting key, + /// broadcasts it and waits for the block that records it. + /// + /// @param options - The masternode, the proposal, the answer, the voting key and signer. + /// @returns The vote as Platform recorded it. + #[wasm_bindgen(js_name = "decisionProposalVote")] + pub async fn decision_proposal_vote( + &self, + options: DecisionProposalVoteOptionsJs, + ) -> 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 = yes_no_vote_choice_from_options(&options, "voteChoice")?; + let vote = self + .as_ref() + .decision_proposal_vote(proposal_id, vote_choice) + .await?; + self.put_masternode_vote(pro_tx_hash, vote, &options).await + } +} diff --git a/packages/wasm-sdk/src/lib.rs b/packages/wasm-sdk/src/lib.rs index e08467ae81a..550abe47bcb 100644 --- a/packages/wasm-sdk/src/lib.rs +++ b/packages/wasm-sdk/src/lib.rs @@ -3,6 +3,7 @@ use wasm_bindgen::prelude::wasm_bindgen; mod browser_storage; pub mod context_provider; mod contract_store; +pub mod decision_proposals; pub mod document_create_cost; pub mod document_type_layout; pub mod dpns; diff --git a/packages/wasm-sdk/src/moderation_charters.rs b/packages/wasm-sdk/src/moderation_charters.rs index 2036a99373a..2f4fe1cd395 100644 --- a/packages/wasm-sdk/src/moderation_charters.rs +++ b/packages/wasm-sdk/src/moderation_charters.rs @@ -5,6 +5,7 @@ use crate::encrypted_for::{message_from_options, secret_key_from_options}; use crate::error::WasmSdkError; +use crate::queries::utils::documents_map; use crate::sdk::WasmSdk; use dash_sdk::dpp::moderation_charter::{ ELECTED_CHARTER_DOCUMENT_TYPE_NAME, JOIN_REQUEST_DOCUMENT_TYPE_NAME, @@ -16,7 +17,6 @@ use dash_sdk::platform::moderation_charters::{ ResignationRequestInput, }; use dash_sdk::platform::{Document, Fetch, Identifier, Identity}; -use drive_proof_verifier::types::Documents; use js_sys::{Array, Map}; use wasm_bindgen::prelude::wasm_bindgen; use wasm_bindgen::JsValue; @@ -210,25 +210,6 @@ fn document_wasm(document: Document, document_type_name: &str) -> DocumentWasm { ) } -fn documents_map(documents: Documents, document_type_name: &str) -> Map { - let map = Map::new(); - for (id, document) in documents { - let key: JsValue = IdentifierWasm::from(id).to_base58().into(); - match document { - Some(document) => { - map.set( - &key, - &JsValue::from(document_wasm(document, document_type_name)), - ); - } - None => { - map.set(&key, &JsValue::NULL); - } - } - } - map -} - fn request_wasm(request: ModerationCharterRequest) -> DocumentWasm { DocumentWasm::new( request.document, @@ -334,6 +315,7 @@ impl WasmSdk { .await?; Ok(documents_map( documents, + MODERATION_CHARTERS_CONTRACT_ID, SUBMITTED_CHARTER_DOCUMENT_TYPE_NAME, )) } @@ -355,7 +337,11 @@ impl WasmSdk { .as_ref() .fetch_join_requests(submitted_charter_id, page) .await?; - Ok(documents_map(documents, JOIN_REQUEST_DOCUMENT_TYPE_NAME)) + Ok(documents_map( + documents, + MODERATION_CHARTERS_CONTRACT_ID, + JOIN_REQUEST_DOCUMENT_TYPE_NAME, + )) } /// The resignation requests for a seated charter the leader has not acted on: those whose diff --git a/packages/wasm-sdk/src/queries/utils.rs b/packages/wasm-sdk/src/queries/utils.rs index 21290a21bce..f03e8fdbd09 100644 --- a/packages/wasm-sdk/src/queries/utils.rs +++ b/packages/wasm-sdk/src/queries/utils.rs @@ -10,9 +10,35 @@ use wasm_dpp2::serialization::conversions::{ use crate::WasmSdkError; use dash_sdk::platform::Identifier; +use drive_proof_verifier::types::Documents; +use js_sys::Map; +use wasm_dpp2::data_contract::document::DocumentWasm; use wasm_dpp2::identifier::{IdentifierLikeJs, IdentifierWasm}; use wasm_dpp2::utils::IntoWasm; +/// `documents` of the type `document_type_name` of the contract `contract_id`, keyed by their +/// base58 ids in the order the query returned them, a missing document as `null`. +pub(crate) fn documents_map( + documents: Documents, + contract_id: Identifier, + document_type_name: &str, +) -> Map { + let map = Map::new(); + for (id, document) in documents { + let key: JsValue = IdentifierWasm::from(id).to_base58().into(); + let value = document.map_or(JsValue::NULL, |document| { + JsValue::from(DocumentWasm::new( + document, + contract_id, + document_type_name.to_string(), + None, + )) + }); + map.set(&key, &value); + } + map +} + /// The contract a query names, from any `IdentifierLike`. pub(crate) fn parse_contract_id(id: IdentifierLikeJs) -> Result { id.try_into() diff --git a/packages/wasm-sdk/src/queries/voting/mod.rs b/packages/wasm-sdk/src/queries/voting/mod.rs index db77fb7854c..d287a4f504e 100644 --- a/packages/wasm-sdk/src/queries/voting/mod.rs +++ b/packages/wasm-sdk/src/queries/voting/mod.rs @@ -3,4 +3,4 @@ mod resources; mod state; mod voters; mod votes; -mod yes_no; +pub(crate) mod yes_no; diff --git a/packages/wasm-sdk/src/queries/voting/yes_no.rs b/packages/wasm-sdk/src/queries/voting/yes_no.rs index d945d4eb13e..76450594be1 100644 --- a/packages/wasm-sdk/src/queries/voting/yes_no.rs +++ b/packages/wasm-sdk/src/queries/voting/yes_no.rs @@ -95,7 +95,7 @@ fn block_to_js(block: &BlockInfo) -> Result { } /// The state of an opened poll; `undefined` for a poll never opened. -fn state_to_js(state: Option) -> Result { +pub(crate) fn state_to_js(state: Option) -> Result { let Some(state) = state else { return Ok(JsValue::UNDEFINED); }; @@ -165,7 +165,7 @@ fn state_to_js(state: Option) -> Result) -> Result { +pub(crate) fn vote_to_js(vote: Option) -> Result { let Some(vote) = vote else { return Ok(JsValue::UNDEFINED); }; diff --git a/packages/wasm-sdk/src/state_transitions/identity.rs b/packages/wasm-sdk/src/state_transitions/identity.rs index 6aacefde7e8..9503d9f8020 100644 --- a/packages/wasm-sdk/src/state_transitions/identity.rs +++ b/packages/wasm-sdk/src/state_transitions/identity.rs @@ -13,6 +13,7 @@ use dash_sdk::dpp::identity::signer::Signer; use dash_sdk::dpp::identity::{Identity, IdentityPublicKey, KeyType, Purpose, SecurityLevel}; use dash_sdk::dpp::platform_value::Identifier; use dash_sdk::dpp::voting::vote_choices::resource_vote_choice::ResourceVoteChoice; +use dash_sdk::dpp::voting::vote_choices::yes_no_abstain_vote_choice::YesNoAbstainVoteChoice; use dash_sdk::dpp::voting::vote_polls::VotePoll; use dash_sdk::dpp::voting::votes::resource_vote::v0::ResourceVoteV0; use dash_sdk::dpp::voting::votes::resource_vote::ResourceVote; @@ -32,7 +33,7 @@ use wasm_dpp2::identifier::IdentifierWasm; use wasm_dpp2::identity::IdentityPublicKeyWasm; use wasm_dpp2::utils::{ try_from_options_optional, try_from_options_optional_with, try_from_options_with, try_to_array, - try_to_u64, IntoWasm, + try_to_string, try_to_u64, IntoWasm, }; use wasm_dpp2::voting::resource_vote_choice::ResourceVoteChoiceWasm; use wasm_dpp2::voting::vote::VoteWasm; @@ -719,7 +720,8 @@ impl WasmSdk { #[wasm_bindgen(typescript_custom_section)] const MASTERNODE_VOTE_OPTIONS_TS: &'static str = r#" /** - * Options for submitting a masternode vote for a contested resource. + * Options for submitting a masternode vote: on a contested resource, or on a yes/no poll such + * as a decision proposal's (protocol version 15). */ export interface MasternodeVoteOptions { /** @@ -729,16 +731,18 @@ export interface MasternodeVoteOptions { masternodeProTxHash: IdentifierLike; /** - * The vote poll to vote on. - * Use VotePoll.createContestedDocumentResourceVotePoll() to create. + * The vote poll to vote on: a contested resource poll + * (VotePoll.createContestedDocumentResourceVotePoll() creates one), or a yes/no poll as + * getVotePollsByEndDate returns it. */ votePoll: VotePoll; /** - * The vote choice. - * Use ResourceVoteChoice.towardsIdentity(), ResourceVoteChoice.abstain(), or ResourceVoteChoice.lock(). + * The vote choice. On a contested resource, a ResourceVoteChoice: + * ResourceVoteChoice.towardsIdentity(), ResourceVoteChoice.abstain(), or + * ResourceVoteChoice.lock(). On a yes/no poll, 'yes', 'no' or 'abstain'. */ - voteChoice: ResourceVoteChoice; + voteChoice: ResourceVoteChoice | YesNoAbstainVoteChoiceName; /** * The masternode's voting public key. @@ -768,7 +772,9 @@ extern "C" { #[wasm_bindgen] impl WasmSdk { - /// Submit a masternode vote for a contested resource. + /// Submit a masternode vote on a contested resource, or on a yes/no poll such as a + /// decision proposal's. A yes/no vote names the poll by its id, which the SDK derives from + /// the poll's purpose. /// /// This method handles the complete voting flow: /// 1. Builds and signs the vote transition with the voting key @@ -785,18 +791,41 @@ impl WasmSdk { let pro_tx_hash: Identifier = IdentifierWasm::try_from_options(&options, "masternodeProTxHash")?.into(); let vote_poll: VotePoll = VotePollWasm::try_from_options(&options, "votePoll")?.into(); - let resource_vote_choice: ResourceVoteChoice = - ResourceVoteChoiceWasm::try_from_options(&options, "voteChoice")?.into(); + let vote = match vote_poll { + VotePoll::ContestedDocumentResourceVotePoll(_) => { + let resource_vote_choice: ResourceVoteChoice = + ResourceVoteChoiceWasm::try_from_options(&options, "voteChoice")?.into(); + Vote::ResourceVote(ResourceVote::V0(ResourceVoteV0::try_new( + vote_poll, + resource_vote_choice, + )?)) + } + VotePoll::YesNoVotePoll(vote_poll) => { + let vote_choice = yes_no_vote_choice_from_options(&options, "voteChoice")?; + self.inner_sdk() + .yes_no_vote(&vote_poll.purpose, vote_choice) + .await? + } + }; + self.put_masternode_vote(pro_tx_hash, vote, &options).await + } +} + +impl WasmSdk { + /// Signs `vote` for the masternode `pro_tx_hash` with the voting key `options.votingKey` + /// the signer `options.signer` holds, broadcasts it with `options.settings`, and returns + /// the vote as Platform recorded it. + pub(crate) async fn put_masternode_vote( + &self, + pro_tx_hash: Identifier, + vote: Vote, + options: &JsValue, + ) -> Result { let voting_public_key: IdentityPublicKey = - IdentityPublicKeyWasm::try_from_options(&options, "votingKey")?.into(); - let signer = IdentitySignerWasm::try_from_options(&options, "signer")?; + IdentityPublicKeyWasm::try_from_options(options, "votingKey")?.into(); + let signer = IdentitySignerWasm::try_from_options(options, "signer")?; let settings = - try_from_options_optional::(&options, "settings")?.map(Into::into); - - let vote = Vote::ResourceVote(ResourceVote::V0(ResourceVoteV0::try_new( - vote_poll, - resource_vote_choice, - )?)); + try_from_options_optional::(options, "settings")?.map(Into::into); let recorded_vote = vote .put_to_platform_and_wait_for_response( @@ -812,6 +841,22 @@ impl WasmSdk { } } +/// The answer `property` of `options` gives on a yes/no poll: `'yes'`, `'no'` or `'abstain'`. +pub(crate) fn yes_no_vote_choice_from_options( + options: &JsValue, + property: &str, +) -> Result { + let choice = try_from_options_with(options, property, |value| try_to_string(value, property))?; + match choice.as_str() { + "yes" => Ok(YesNoAbstainVoteChoice::Yes), + "no" => Ok(YesNoAbstainVoteChoice::No), + "abstain" => Ok(YesNoAbstainVoteChoice::Abstain), + other => Err(WasmSdkError::invalid_argument(format!( + "{property} on a yes/no poll is 'yes', 'no' or 'abstain', got '{other}'" + ))), + } +} + // ============================================================================ // Identity Key Limits Update // ============================================================================ diff --git a/packages/wasm-sdk/tests/unit/decision-proposals.spec.ts b/packages/wasm-sdk/tests/unit/decision-proposals.spec.ts new file mode 100644 index 00000000000..4e04d87898d --- /dev/null +++ b/packages/wasm-sdk/tests/unit/decision-proposals.spec.ts @@ -0,0 +1,125 @@ +/** + * Decision proposals (protocol version 15). `buildDecisionProposalEdit` needs no network: it + * gives a stored proposal new text and its next revision. The listings and the vote 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 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('decision proposals', () => { + let client: sdk.WasmSdk; + + before(async () => { + await init(); + client = await sdk.WasmSdkBuilder.testnet().build(); + }); + + after(() => { + client?.free(); + }); + + function storedProposal(dataContractId = DECISION_PROPOSALS_CONTRACT_ID): sdk.Document { + return new sdk.Document({ + properties: { + title: 'Raise the block size?', + description: 'Yes doubles it; no keeps it.', + url: 'https://forum.dash.org/t/block-size', + passPercent: 60, + minimumTurnoutPercent: 10, + endDate: BigInt(1_700_000_000_000), + }, + documentTypeName: 'proposal', + dataContractId, + ownerId, + revision: BigInt(1), + entropy: new Uint8Array(32).fill(3), + }); + } + + describe('buildDecisionProposalEdit()', () => { + it('should give the proposal new text and its next revision', () => { + const proposal = storedProposal(); + const edited = client.buildDecisionProposalEdit(proposal, { title: 'Raise the block size to 4 MB?' }); + 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('Raise the block size to 4 MB?'); + expect(properties.description).to.equal('Yes doubles it; no keeps it.'); + expect(properties.url).to.equal('https://forum.dash.org/t/block-size'); + expect(edited.documentTypeName).to.equal('proposal'); + expect(edited.dataContractId.toBase58()).to.equal(DECISION_PROPOSALS_CONTRACT_ID); + }); + + it('should remove the url when the edit sets it to null', () => { + const edited = client.buildDecisionProposalEdit(storedProposal(), { description: 'Yes doubles it.', url: null }); + const properties = edited.properties as Record; + expect(properties.description).to.equal('Yes doubles it.'); + expect(properties).to.not.have.property('url'); + }); + + it('should refuse an edit that changes nothing', () => { + const error = refusalOf(() => client.buildDecisionProposalEdit(storedProposal(), {})); + expect(error.message).to.match(/changes nothing/); + }); + + it('should refuse a document that is not a decision proposal', () => { + const error = refusalOf(() => client.buildDecisionProposalEdit( + storedProposal('GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec'), + { title: 'Another question?' }, + )); + expect(error.message).to.match(/is not a decision proposal/); + }); + }); + + describe('listings', () => { + it('should accept Identifier instances as the owner and the cursor', async () => { + const error = await rejectionOf(client.getDecisionProposalsByOwner({ + ownerId: new sdk.Identifier(ownerId), + startAfter: new sdk.Identifier(ownerId), + limit: 1.5, + })); + expect(error.message).to.match(/'limit' must be an integer/); + }); + + it('should refuse an end date bound that is not a number', async () => { + const error = await rejectionOf(client.getDecisionProposalsByEndDate({ + endDateFrom: 'soon' as never, + })); + expect(error.message).to.match(/endDateFrom/); + }); + }); + + describe('decisionProposalVote()', () => { + it('should refuse an answer other than yes, no or abstain', async () => { + const error = await rejectionOf(client.decisionProposalVote({ + masternodeProTxHash: proTxHashHex, + proposalId: ownerId, + voteChoice: 'maybe' as never, + } as never)); + expect(error.message).to.match(/'yes', 'no' or 'abstain', got 'maybe'/); + }); + }); +}); From 56ac1a8c113841b310c542e64a3a2c6e7d87f8b1 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Sat, 31 Oct 2026 08:41:58 +0300 Subject: [PATCH 2/3] fix(sdk): judge a proposal edit in rs-sdk, and keep a proposal's fund in the raw create Review fixes: - build_decision_proposal_edit takes the document's contract and type, refuses anything but a decision proposal, refuses an edit that leaves the text as it is (an unchanged value, removing an absent url), and moves the revision with increment_revision (checked). The wasm binding passes the document's metadata and no longer decides. - The wasm-dpp2 DocumentCreateTransition constructor states contestFund through StateTransitionCreationOptions::apply_contest_fund, so a decision proposal keeps its fund there too. - The startAfter/limit parsing of the proposal and moderation charter listings is one helper (queries::utils::documents_page_of). Co-Authored-By: Claude Opus 5.5 --- .../rs-sdk/src/platform/decision_proposals.rs | 148 +++++++++++++++--- .../batch/document_transitions/create.rs | 26 ++- .../tests/unit/DocumentsTransitions.spec.ts | 19 +++ packages/wasm-sdk/src/decision_proposals.rs | 31 ++-- packages/wasm-sdk/src/moderation_charters.rs | 8 +- packages/wasm-sdk/src/queries/utils.rs | 14 +- 6 files changed, 187 insertions(+), 59 deletions(-) diff --git a/packages/rs-sdk/src/platform/decision_proposals.rs b/packages/rs-sdk/src/platform/decision_proposals.rs index fa4255905cc..f029b639a1a 100644 --- a/packages/rs-sdk/src/platform/decision_proposals.rs +++ b/packages/rs-sdk/src/platform/decision_proposals.rs @@ -33,8 +33,9 @@ use dapi_grpc::platform::v0::get_documents_request::get_documents_request_v0::St use dpp::data_contract::accessors::v0::DataContractV0Getters; use dpp::data_contract::document_type::methods::DocumentTypeBasicMethods; use dpp::decision_proposal::{ - properties, DECISION_PROPOSALS_CONTRACT_ID, PROPOSAL_DOCUMENT_TYPE_NAME, + is_decision_proposal, properties, DECISION_PROPOSALS_CONTRACT_ID, PROPOSAL_DOCUMENT_TYPE_NAME, }; +use dpp::document::document_methods::DocumentMethodsV0; use dpp::document::{DocumentV0, DocumentV0Getters, DocumentV0Setters, INITIAL_REVISION}; use dpp::platform_value::btreemap_extensions::BTreeValueMapHelper; use dpp::platform_value::string_encoding::Encoding; @@ -223,25 +224,25 @@ pub fn build_decision_proposal_document( Ok(DecisionProposalDocument { document, entropy }) } -/// `proposal` with the new text `edit` gives it and its next revision, ready to be put as a -/// replace. Consensus refuses the replace more than a day after the proposal was created (or a -/// fifth of the time it runs, if that is shorter), and refuses any change to its rule or end -/// date. +/// `proposal`, a `document_type_name` document of the contract `data_contract_id`, with the +/// new text `edit` gives it and its next revision, ready to be put as a replace. Anything but a +/// decision proposal is refused, as is an edit that leaves the text as it is: a replace that +/// changes nothing still pays its fees. Consensus refuses the replace more than a day after the +/// proposal was created (or a fifth of the time it runs, if that is shorter), and refuses any +/// change to its rule or end date. pub fn build_decision_proposal_edit( + data_contract_id: &Identifier, + document_type_name: &str, proposal: &Document, edit: &DecisionProposalEdit, ) -> Result { - if edit == &DecisionProposalEdit::default() { + if !is_decision_proposal(data_contract_id, document_type_name) { return Err(Error::Generic(format!( - "the edit of proposal {} changes nothing", - proposal.id() + "a {document_type_name} document of contract {data_contract_id} is not a decision \ + proposal" ))); } - let revision = proposal - .revision() - .ok_or_else(|| Error::Generic(format!("proposal {} carries no revision", proposal.id())))?; let mut document = proposal.clone(); - document.set_revision(Some(revision + 1)); if let Some(title) = &edit.title { document.set(properties::TITLE, Value::Text(title.clone())); } @@ -255,6 +256,13 @@ pub fn build_decision_proposal_edit( } None => {} } + if document.properties() == proposal.properties() { + return Err(Error::Generic(format!( + "the edit of proposal {} changes nothing", + proposal.id() + ))); + } + document.increment_revision()?; Ok(document) } @@ -622,23 +630,36 @@ mod tests { assert!(DecisionProposal::from_document(no_title).is_err()); } - #[test] - fn should_edit_only_the_text_and_move_to_the_next_revision() { - let contract = proposals_contract(); - let proposal = stored( + /// `edit` applied to `proposal` as a decision proposal. + fn edit_proposal(proposal: &Document, edit: DecisionProposalEdit) -> Result { + build_decision_proposal_edit( + &DECISION_PROPOSALS_CONTRACT_ID, + PROPOSAL_DOCUMENT_TYPE_NAME, + proposal, + &edit, + ) + } + + fn stored_proposal() -> Document { + stored( &build_decision_proposal_document( - &contract, + &proposals_contract(), Identifier::from([3; 32]), &input(), Bytes32::new([9; 32]), ) .expect("builds") .document, - ); + ) + } - let edited = build_decision_proposal_edit( + #[test] + fn should_edit_only_the_text_and_move_to_the_next_revision() { + let proposal = stored_proposal(); + + let edited = edit_proposal( &proposal, - &DecisionProposalEdit { + DecisionProposalEdit { title: Some("Raise the block size to 4 MB?".to_string()), ..Default::default() }, @@ -659,9 +680,9 @@ mod tests { (60, 10, input().end_date) ); - let without_url = build_decision_proposal_edit( + let without_url = edit_proposal( &proposal, - &DecisionProposalEdit { + DecisionProposalEdit { description: Some("Yes doubles it.".to_string()), url: Some(None), ..Default::default() @@ -671,11 +692,86 @@ mod tests { let read = DecisionProposal::from_document(without_url).expect("reads"); assert_eq!(read.description, "Yes doubles it."); assert_eq!(read.url, None); + } - assert!( - build_decision_proposal_edit(&proposal, &DecisionProposalEdit::default()).is_err(), - "an edit that changes nothing is refused before it is paid for" - ); + /// A replace that changes nothing still pays its fees, so an edit that leaves the text as it + /// is, whatever it names, is refused before it is signed. + #[test] + fn should_refuse_an_edit_that_changes_nothing() { + let proposal = stored_proposal(); + let unchanged = [ + DecisionProposalEdit::default(), + DecisionProposalEdit { + title: Some(input().title), + description: Some(input().description), + 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 mut without_url = proposal; + without_url.remove(properties::URL); + let error = edit_proposal( + &without_url, + DecisionProposalEdit { + url: Some(None), + ..Default::default() + }, + ) + .expect_err("removing an absent url changes nothing"); + assert!(error.to_string().contains("changes nothing")); + } + + #[test] + fn should_refuse_to_edit_a_document_that_is_not_a_decision_proposal() { + let proposal = stored_proposal(); + let edit = DecisionProposalEdit { + title: Some("Another question?".to_string()), + ..Default::default() + }; + for (data_contract_id, document_type_name) in [ + (Identifier::from([1; 32]), PROPOSAL_DOCUMENT_TYPE_NAME), + (DECISION_PROPOSALS_CONTRACT_ID, "note"), + ] { + let error = build_decision_proposal_edit( + &data_contract_id, + document_type_name, + &proposal, + &edit, + ) + .expect_err("not a decision proposal"); + assert!( + error.to_string().contains("is not a decision proposal"), + "{document_type_name} of {data_contract_id}: {error}" + ); + } + } + + #[test] + fn should_refuse_an_edit_past_the_last_revision() { + let mut proposal = stored_proposal(); + proposal.set_revision(Some(u64::MAX)); + assert!(edit_proposal( + &proposal, + DecisionProposalEdit { + title: Some("Raise the block size to 4 MB?".to_string()), + ..Default::default() + }, + ) + .is_err()); + + proposal.set_revision(None); + assert!(edit_proposal( + &proposal, + DecisionProposalEdit { + title: Some("Raise the block size to 4 MB?".to_string()), + ..Default::default() + }, + ) + .is_err()); } #[test] diff --git a/packages/wasm-dpp2/src/state_transitions/batch/document_transitions/create.rs b/packages/wasm-dpp2/src/state_transitions/batch/document_transitions/create.rs index d4a4c2c228a..52bb43db020 100644 --- a/packages/wasm-dpp2/src/state_transitions/batch/document_transitions/create.rs +++ b/packages/wasm-dpp2/src/state_transitions/batch/document_transitions/create.rs @@ -23,6 +23,7 @@ use dpp::prelude::{Identifier, IdentityNonce}; use dpp::state_transition::batch_transition::batched_transition::document_transition::DocumentTransition; use dpp::state_transition::batch_transition::document_base_transition::document_base_transition_trait::DocumentBaseTransitionAccessors; use dpp::state_transition::batch_transition::document_create_transition::v0::v0_methods::DocumentCreateTransitionV0Methods; +use dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions; use dpp::state_transition::batch_transition::DocumentCreateTransition; use dpp::version::PlatformVersion; use wasm_bindgen::prelude::wasm_bindgen; @@ -61,7 +62,8 @@ export interface DocumentCreateTransitionOptions { * The most, in credits, a contested create pays into its contest (protocol * version 14), stated in place of the amount of its prefunded voting * balance. Needs `dataContract` or `prefundedVotingBalance` to name the - * contested index. A document that joins no contest ignores it. + * contested index. A document that joins no contest ignores it, and a + * decision proposal keeps its fund. */ contestFund?: bigint; tokenPaymentInfo?: TokenPaymentInfo; @@ -155,12 +157,6 @@ impl DocumentCreateTransitionWasm { } (None, None) => None, }; - // Like `StateTransitionCreationOptions::apply_contest_fund` in dpp - let prefunded_voting_balance = match (prefunded_voting_balance, contest_fund) { - (Some((index_name, _)), Some(contest_fund)) => Some((index_name, contest_fund)), - (prefunded_voting_balance, _) => prefunded_voting_balance, - }; - document.set_id_for_creation(identity_contract_nonce, &platform_version)?; let rs_create_transition = generate_create_transition( @@ -172,7 +168,21 @@ impl DocumentCreateTransitionWasm { action_fee_agreement, ); - Ok(DocumentCreateTransitionWasm(rs_create_transition)) + // The contest fund stated in place of the one the create was built with, as the Rust + // builders state it: a decision proposal keeps its fund. + let creation_options = StateTransitionCreationOptions { + contest_fund, + ..Default::default() + }; + match creation_options.apply_contest_fund(DocumentTransition::Create(rs_create_transition)) + { + DocumentTransition::Create(rs_create_transition) => { + Ok(DocumentCreateTransitionWasm(rs_create_transition)) + } + _ => Err(WasmDppError::generic( + "applying the contest fund to a create returned another transition", + )), + } } #[wasm_bindgen(getter = "data")] diff --git a/packages/wasm-dpp2/tests/unit/DocumentsTransitions.spec.ts b/packages/wasm-dpp2/tests/unit/DocumentsTransitions.spec.ts index a99eeb1d150..7e8ea72875f 100644 --- a/packages/wasm-dpp2/tests/unit/DocumentsTransitions.spec.ts +++ b/packages/wasm-dpp2/tests/unit/DocumentsTransitions.spec.ts @@ -410,6 +410,25 @@ describe('DocumentsTransitions', () => { expect(createTransition.prefundedVotingBalance).to.equal(undefined); }); + it('should keep the fund of a decision proposal whatever contestFund says', () => { + // The fund a proposal create states, 0.5 Dash, which consensus requires exactly + const proposalFund = BigInt(50000000000); + const createTransition = new wasm.DocumentCreateTransition({ + document: new wasm.Document({ + properties: { title: 'Raise the block size?' }, + documentTypeName: 'proposal', + dataContractId: '3iNyoNwjCTkb7XS3RHyWUtLx7pgC6AFAEQNNDHzxqngF', + ownerId, + }), + identityContractNonce: BigInt(1), + prefundedVotingBalance: new wasm.PrefundedVotingBalance({ indexName: 'proposal', credits: proposalFund }), + contestFund: BigInt(7), + }); + + expect(createTransition.prefundedVotingBalance.indexName).to.equal('proposal'); + expect(createTransition.prefundedVotingBalance.credits).to.equal(proposalFund); + }); + it('should refuse contestFund without dataContract or prefundedVotingBalance', () => { expect(() => new wasm.DocumentCreateTransition({ document: name(contract(), 'quantum'), diff --git a/packages/wasm-sdk/src/decision_proposals.rs b/packages/wasm-sdk/src/decision_proposals.rs index 819e3c20baf..ddb1c8d9f95 100644 --- a/packages/wasm-sdk/src/decision_proposals.rs +++ b/packages/wasm-sdk/src/decision_proposals.rs @@ -4,12 +4,12 @@ //! document, and its poll is named by the proposal's id. use crate::error::WasmSdkError; -use crate::queries::utils::documents_map; +use crate::queries::utils::{documents_map, documents_page_of}; use crate::queries::voting::yes_no::{state_to_js, vote_to_js}; use crate::sdk::WasmSdk; use crate::state_transitions::identity::yes_no_vote_choice_from_options; use dash_sdk::dpp::decision_proposal::{ - is_decision_proposal, DECISION_PROPOSALS_CONTRACT_ID, PROPOSAL_DOCUMENT_TYPE_NAME, + DECISION_PROPOSALS_CONTRACT_ID, PROPOSAL_DOCUMENT_TYPE_NAME, }; use dash_sdk::dpp::document::Document; use dash_sdk::dpp::voting::vote_polls::yes_no_vote_poll::YesNoVotePollPurpose; @@ -29,8 +29,7 @@ use wasm_bindgen::JsValue; use wasm_dpp2::data_contract::document::DocumentWasm; use wasm_dpp2::identifier::{IdentifierLikeJs, IdentifierWasm}; use wasm_dpp2::utils::{ - try_from_options_optional_with, try_from_options_with, try_to_string, try_to_u32, try_to_u64, - try_to_u8, + try_from_options_optional_with, try_from_options_with, try_to_string, try_to_u64, try_to_u8, }; use wasm_dpp2::voting::vote::VoteWasm; @@ -198,16 +197,13 @@ fn optional_end_date_option( )?) } -/// The page a listing query asks for: `startAfter` and `limit`, each optional. An absent query -/// is the first page of 100. +/// The page a listing query asks for (see `documents_page_of`). An absent query is the first +/// page of 100. fn page_of(query: &JsValue) -> Result { if query.is_undefined() || query.is_null() { return Ok(DocumentsPage::default()); } - let start_after = - IdentifierWasm::try_from_optional_options(query, "startAfter")?.map(Identifier::from); - let limit = try_from_options_optional_with(query, "limit", |value| try_to_u32(value, "limit"))?; - Ok(DocumentsPage { limit, start_after }) + documents_page_of(query) } fn proposal_wasm(document: Document, entropy: Option<[u8; 32]>) -> DocumentWasm { @@ -300,16 +296,15 @@ impl WasmSdk { description: optional_string_option(&edit, "description")?, url, }; - let contract_id: Identifier = proposal.data_contract_id().into(); - if !is_decision_proposal(&contract_id, &proposal.document_type_name()) { - return Err(WasmSdkError::invalid_argument(format!( - "a {} document of contract {contract_id} is not a decision proposal", - proposal.document_type_name() - ))); - } + let data_contract_id: Identifier = proposal.data_contract_id().into(); let document: Document = proposal.clone().into(); Ok(proposal_wasm( - build_decision_proposal_edit(&document, &edit)?, + build_decision_proposal_edit( + &data_contract_id, + &proposal.document_type_name(), + &document, + &edit, + )?, None, )) } diff --git a/packages/wasm-sdk/src/moderation_charters.rs b/packages/wasm-sdk/src/moderation_charters.rs index 2f4fe1cd395..8f2874c41ee 100644 --- a/packages/wasm-sdk/src/moderation_charters.rs +++ b/packages/wasm-sdk/src/moderation_charters.rs @@ -5,7 +5,7 @@ use crate::encrypted_for::{message_from_options, secret_key_from_options}; use crate::error::WasmSdkError; -use crate::queries::utils::documents_map; +use crate::queries::utils::{documents_map, documents_page_of}; use crate::sdk::WasmSdk; use dash_sdk::dpp::moderation_charter::{ ELECTED_CHARTER_DOCUMENT_TYPE_NAME, JOIN_REQUEST_DOCUMENT_TYPE_NAME, @@ -23,7 +23,6 @@ use wasm_bindgen::JsValue; use wasm_dpp2::data_contract::document::DocumentWasm; use wasm_dpp2::identifier::{IdentifierLikeJs, IdentifierWasm}; use wasm_dpp2::identity::IdentityWasm; -use wasm_dpp2::utils::{try_from_options_optional_with, try_to_u32}; #[wasm_bindgen(typescript_custom_section)] const MODERATION_CHARTERS_TS: &'static str = r#" @@ -195,10 +194,7 @@ fn page_query( return Err(WasmSdkError::invalid_argument("Query object is required")); } let id = IdentifierWasm::try_from_options(query, id_field)?.into(); - let start_after = - IdentifierWasm::try_from_optional_options(query, "startAfter")?.map(Identifier::from); - let limit = try_from_options_optional_with(query, "limit", |value| try_to_u32(value, "limit"))?; - Ok((id, CharterDocumentsPage { limit, start_after })) + Ok((id, documents_page_of(query)?)) } fn document_wasm(document: Document, document_type_name: &str) -> DocumentWasm { diff --git a/packages/wasm-sdk/src/queries/utils.rs b/packages/wasm-sdk/src/queries/utils.rs index f03e8fdbd09..e81cb4b474f 100644 --- a/packages/wasm-sdk/src/queries/utils.rs +++ b/packages/wasm-sdk/src/queries/utils.rs @@ -9,12 +9,24 @@ use wasm_dpp2::serialization::conversions::{ }; use crate::WasmSdkError; +use dash_sdk::platform::documents::DocumentsPage; use dash_sdk::platform::Identifier; use drive_proof_verifier::types::Documents; use js_sys::Map; use wasm_dpp2::data_contract::document::DocumentWasm; use wasm_dpp2::identifier::{IdentifierLikeJs, IdentifierWasm}; -use wasm_dpp2::utils::IntoWasm; +use wasm_dpp2::utils::{try_from_options_optional_with, try_to_u32, IntoWasm}; + +/// The page a listing query asks for: `startAfter` and `limit`, each optional. Each field is +/// read on its own as an `IdentifierLike` or a number: an `Identifier` instance does not +/// survive the serde conversion a whole-object deserialization goes through. `limit` is read +/// last, so the fields before it are parsed first. +pub(crate) fn documents_page_of(query: &JsValue) -> Result { + let start_after = + IdentifierWasm::try_from_optional_options(query, "startAfter")?.map(Identifier::from); + let limit = try_from_options_optional_with(query, "limit", |value| try_to_u32(value, "limit"))?; + Ok(DocumentsPage { limit, start_after }) +} /// `documents` of the type `document_type_name` of the contract `contract_id`, keyed by their /// base58 ids in the order the query returned them, a missing document as `null`. From 07eb49225bdcdfc5a13b0ff38174757fa8109acd Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Sat, 31 Oct 2026 09:00:56 +0300 Subject: [PATCH 3/3] test(sdk): cover valid answers of decisionProposalVote before the network masternodeVote and decisionProposalVote now read the voting key, signer and settings (MasternodeVoteSigning) before the vote is built, which for a yes/no poll may ask the network for its protocol version. A spec checks that 'yes', 'no' and 'abstain' are accepted and the call stops at the missing voting key without reaching the network. Co-Authored-By: Claude Opus 5.5 --- packages/wasm-sdk/src/decision_proposals.rs | 8 ++- .../src/state_transitions/identity.rs | 59 ++++++++++++------- .../tests/unit/decision-proposals.spec.ts | 11 ++++ 3 files changed, 55 insertions(+), 23 deletions(-) diff --git a/packages/wasm-sdk/src/decision_proposals.rs b/packages/wasm-sdk/src/decision_proposals.rs index ddb1c8d9f95..bb5395ba1c0 100644 --- a/packages/wasm-sdk/src/decision_proposals.rs +++ b/packages/wasm-sdk/src/decision_proposals.rs @@ -7,7 +7,7 @@ use crate::error::WasmSdkError; use crate::queries::utils::{documents_map, documents_page_of}; use crate::queries::voting::yes_no::{state_to_js, vote_to_js}; use crate::sdk::WasmSdk; -use crate::state_transitions::identity::yes_no_vote_choice_from_options; +use crate::state_transitions::identity::{yes_no_vote_choice_from_options, MasternodeVoteSigning}; use dash_sdk::dpp::decision_proposal::{ DECISION_PROPOSALS_CONTRACT_ID, PROPOSAL_DOCUMENT_TYPE_NAME, }; @@ -455,7 +455,8 @@ impl WasmSdk { } /// Votes on a proposal for a masternode: builds the vote, signs it with the voting key, - /// broadcasts it and waits for the block that records it. + /// 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. @@ -470,10 +471,11 @@ impl WasmSdk { let proposal_id: Identifier = IdentifierWasm::try_from_options(&options, "proposalId")?.into(); let vote_choice = yes_no_vote_choice_from_options(&options, "voteChoice")?; + let signing = MasternodeVoteSigning::from_options(&options)?; let vote = self .as_ref() .decision_proposal_vote(proposal_id, vote_choice) .await?; - self.put_masternode_vote(pro_tx_hash, vote, &options).await + self.put_masternode_vote(pro_tx_hash, vote, signing).await } } diff --git a/packages/wasm-sdk/src/state_transitions/identity.rs b/packages/wasm-sdk/src/state_transitions/identity.rs index 9503d9f8020..6de154adf65 100644 --- a/packages/wasm-sdk/src/state_transitions/identity.rs +++ b/packages/wasm-sdk/src/state_transitions/identity.rs @@ -20,6 +20,7 @@ use dash_sdk::dpp::voting::votes::resource_vote::ResourceVote; use dash_sdk::dpp::voting::votes::Vote; use dash_sdk::platform::transition::broadcast::BroadcastStateTransition; use dash_sdk::platform::transition::put_identity::PutIdentity; +use dash_sdk::platform::transition::put_settings::PutSettings; use dash_sdk::platform::transition::top_up_identity::TopUpIdentity; use dash_sdk::platform::transition::update_identity_key_limits::{ raised_key_limits, UpdateIdentityKeyLimits, @@ -791,49 +792,67 @@ impl WasmSdk { let pro_tx_hash: Identifier = IdentifierWasm::try_from_options(&options, "masternodeProTxHash")?.into(); let vote_poll: VotePoll = VotePollWasm::try_from_options(&options, "votePoll")?.into(); - let vote = match vote_poll { + match vote_poll { VotePoll::ContestedDocumentResourceVotePoll(_) => { let resource_vote_choice: ResourceVoteChoice = ResourceVoteChoiceWasm::try_from_options(&options, "voteChoice")?.into(); - Vote::ResourceVote(ResourceVote::V0(ResourceVoteV0::try_new( + let signing = MasternodeVoteSigning::from_options(&options)?; + let vote = Vote::ResourceVote(ResourceVote::V0(ResourceVoteV0::try_new( vote_poll, resource_vote_choice, - )?)) + )?)); + self.put_masternode_vote(pro_tx_hash, vote, signing).await } VotePoll::YesNoVotePoll(vote_poll) => { let vote_choice = yes_no_vote_choice_from_options(&options, "voteChoice")?; - self.inner_sdk() + let signing = MasternodeVoteSigning::from_options(&options)?; + let vote = self + .inner_sdk() .yes_no_vote(&vote_poll.purpose, vote_choice) - .await? + .await?; + self.put_masternode_vote(pro_tx_hash, vote, signing).await } - }; - self.put_masternode_vote(pro_tx_hash, vote, &options).await + } + } +} + +/// How a masternode vote is signed and broadcast: the `votingKey`, `signer` and `settings` of +/// a vote's options, read before anything reaches the network. +pub(crate) struct MasternodeVoteSigning { + voting_public_key: IdentityPublicKey, + signer: IdentitySignerWasm, + settings: Option, +} + +impl MasternodeVoteSigning { + /// Reads `votingKey`, `signer` and `settings` from `options`. + pub(crate) fn from_options(options: &JsValue) -> Result { + Ok(Self { + voting_public_key: IdentityPublicKeyWasm::try_from_options(options, "votingKey")? + .into(), + signer: IdentitySignerWasm::try_from_options(options, "signer")?, + settings: try_from_options_optional::(options, "settings")? + .map(Into::into), + }) } } impl WasmSdk { - /// Signs `vote` for the masternode `pro_tx_hash` with the voting key `options.votingKey` - /// the signer `options.signer` holds, broadcasts it with `options.settings`, and returns - /// the vote as Platform recorded it. + /// Signs `vote` for the masternode `pro_tx_hash` as `signing` says, broadcasts it, and + /// returns the vote as Platform recorded it. pub(crate) async fn put_masternode_vote( &self, pro_tx_hash: Identifier, vote: Vote, - options: &JsValue, + signing: MasternodeVoteSigning, ) -> Result { - let voting_public_key: IdentityPublicKey = - IdentityPublicKeyWasm::try_from_options(options, "votingKey")?.into(); - let signer = IdentitySignerWasm::try_from_options(options, "signer")?; - let settings = - try_from_options_optional::(options, "settings")?.map(Into::into); - let recorded_vote = vote .put_to_platform_and_wait_for_response( pro_tx_hash, - &voting_public_key, + &signing.voting_public_key, self.inner_sdk(), - &signer, - settings, + &signing.signer, + signing.settings, ) .await?; diff --git a/packages/wasm-sdk/tests/unit/decision-proposals.spec.ts b/packages/wasm-sdk/tests/unit/decision-proposals.spec.ts index 4e04d87898d..1b0a60e8e7a 100644 --- a/packages/wasm-sdk/tests/unit/decision-proposals.spec.ts +++ b/packages/wasm-sdk/tests/unit/decision-proposals.spec.ts @@ -121,5 +121,16 @@ describe('decision proposals', () => { } as never)); expect(error.message).to.match(/'yes', 'no' or 'abstain', got 'maybe'/); }); + + ['yes', 'no', 'abstain'].forEach((voteChoice) => { + it(`should accept '${voteChoice}' and read the voting key before the network`, async () => { + const error = await rejectionOf(client.decisionProposalVote({ + masternodeProTxHash: proTxHashHex, + proposalId: ownerId, + voteChoice, + } as never)); + expect(error.message).to.match(/'votingKey' is required/); + }); + }); }); });