From f9a5f04eeb2fb93bdef18720d449dd247662e1f7 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Sat, 5 Oct 2024 23:45:52 +0700 Subject: [PATCH 01/50] feat(wasm-dpp): add transfer transition to documents batch wip --- .../src/document/document_factory/v0/mod.rs | 87 +++++ packages/wasm-dpp/src/document/factory.rs | 8 + .../document_transfer_transition.rs | 300 ++++++++++++++++++ .../document_transition/mod.rs | 1 + 4 files changed, 396 insertions(+) create mode 100644 packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_transfer_transition.rs diff --git a/packages/rs-dpp/src/document/document_factory/v0/mod.rs b/packages/rs-dpp/src/document/document_factory/v0/mod.rs index 58fc96de91a..5aa64b775a3 100644 --- a/packages/rs-dpp/src/document/document_factory/v0/mod.rs +++ b/packages/rs-dpp/src/document/document_factory/v0/mod.rs @@ -507,6 +507,93 @@ impl DocumentFactoryV0 { // Ok(raw_transitions) } + #[cfg(feature = "state-transitions")] + fn document_transfer_transitions( + documents: Vec<(Document, DocumentTypeRef)>, + nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce + platform_version: &PlatformVersion, + ) -> Result, ProtocolError> { + documents + .into_iter() + .map(|(mut document, document_type)| { + if !document_type.documents_mutable() { + return Err(DocumentError::TryingToReplaceImmutableDocument { + document: Box::new(document), + } + .into()); + } + if document.revision().is_none() { + return Err(DocumentError::RevisionAbsentError { + document: Box::new(document), + } + .into()); + }; + + document.increment_revision()?; + document.set_updated_at(Some(Utc::now().timestamp_millis() as TimestampMillis)); + + let recipient_owner_id = document.owner_id(); + + let nonce = nonce_counter + .entry((document.owner_id(), document_type.data_contract_id())) + .or_default(); + + let transition = DocumentTransferTransition::from_document( + document, + document_type, + *nonce, + recipient_owner_id, + platform_version, + None, + None, + )?; + + *nonce += 1; + + Ok(transition.into()) + }) + .collect() + // let mut raw_transitions = vec![]; + // for (document, document_type) in documents { + // if !document_type.documents_mutable() { + // return Err(DocumentError::TryingToReplaceImmutableDocument { + // document: Box::new(document), + // } + // .into()); + // } + // let Some(document_revision) = document.revision() else { + // return Err(DocumentError::RevisionAbsentError { + // document: Box::new(document), + // }.into()); + // }; + // let mut map = document.to_map_value()?; + // + // map.retain(|key, _| { + // !key.starts_with('$') || DOCUMENT_REPLACE_KEYS_TO_STAY.contains(&key.as_str()) + // }); + // map.insert( + // PROPERTY_ACTION.to_string(), + // Value::U8(DocumentTransitionActionType::Replace as u8), + // ); + // let new_revision = document_revision + 1; + // map.insert(PROPERTY_REVISION.to_string(), Value::U64(new_revision)); + // + // // If document have an originally set `updatedAt` + // // we should update it then + // let contains_updated_at = document_type + // .required_fields() + // .contains(PROPERTY_UPDATED_AT); + // + // if contains_updated_at { + // let now = Utc::now().timestamp_millis() as TimestampMillis; + // map.insert(PROPERTY_UPDATED_AT.to_string(), Value::U64(now)); + // } + // + // raw_transitions.push(map.into()); + // } + // Ok(raw_transitions) + } + #[cfg(feature = "state-transitions")] fn document_delete_transitions( documents: Vec<(Document, DocumentTypeRef)>, diff --git a/packages/wasm-dpp/src/document/factory.rs b/packages/wasm-dpp/src/document/factory.rs index a62dbc3aeca..09ca8e37c9b 100644 --- a/packages/wasm-dpp/src/document/factory.rs +++ b/packages/wasm-dpp/src/document/factory.rs @@ -32,6 +32,7 @@ pub struct DocumentTransitions { create: Vec, replace: Vec, delete: Vec, + transfer: Vec, } #[wasm_bindgen(js_class=DocumentTransitions)] @@ -55,6 +56,11 @@ impl DocumentTransitions { pub fn add_transition_delete(&mut self, transition: ExtendedDocumentWasm) { self.delete.push(transition) } + + #[wasm_bindgen(js_name = "addTransitionTransfer")] + pub fn add_transition_transfer(&mut self, transition: ExtendedDocumentWasm) { + self.transfer.push(transition) + } } #[wasm_bindgen(js_name = DocumentFactory)] @@ -283,10 +289,12 @@ fn extract_documents_by_action( let documents_create = extract_documents_of_action(documents, "create").with_js_error()?; let documents_replace = extract_documents_of_action(documents, "replace").with_js_error()?; let documents_delete = extract_documents_of_action(documents, "delete").with_js_error()?; + let documents_transfer = extract_documents_of_action(documents, "transfer").with_js_error()?; documents_by_action.insert(DocumentTransitionActionType::Create, documents_create); documents_by_action.insert(DocumentTransitionActionType::Replace, documents_replace); documents_by_action.insert(DocumentTransitionActionType::Delete, documents_delete); + documents_by_action.insert(DocumentTransitionActionType::Transfer, documents_transfer); Ok(documents_by_action) } diff --git a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_transfer_transition.rs b/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_transfer_transition.rs new file mode 100644 index 00000000000..b6e9cdfba7e --- /dev/null +++ b/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_transfer_transition.rs @@ -0,0 +1,300 @@ +use std::convert; + +use serde_json::Value as JsonValue; + +use dpp::platform_value::btreemap_extensions::{ + BTreeValueMapHelper, BTreeValueMapReplacementPathHelper, +}; +use dpp::platform_value::ReplacementType; +use dpp::prelude::Revision; +use dpp::{ + prelude::{Identifier}, + ProtocolError, +}; +use wasm_bindgen::prelude::*; +use dpp::data_contract::accessors::v0::DataContractV0Getters; +use dpp::state_transition::documents_batch_transition::document_base_transition::v0::v0_methods::DocumentBaseTransitionV0Methods; + +use crate::{ + buffer::Buffer, + document::state_transition::document_batch_transition::document_transition::to_object, + identifier::IdentifierWrapper, + lodash::lodash_set, + utils::{ToSerdeJSONExt, WithJsError}, + BinaryType, DataContractWasm, +}; +use dpp::state_transition::documents_batch_transition::document_transition::action_type::DocumentTransitionActionType; +use dpp::state_transition::documents_batch_transition::document_transition::document_transfer_transition::v0::v0_methods::DocumentTransferTransitionV0Methods; +use dpp::state_transition::documents_batch_transition::document_transition::DocumentTransferTransition; + +#[wasm_bindgen(js_name=DocumentTransferTransition)] +#[derive(Debug, Clone)] +pub struct DocumentTransferTransitionWasm { + inner: DocumentTransferTransition, +} + +impl From for DocumentTransferTransitionWasm { + fn from(v: DocumentTransferTransition) -> Self { + Self { inner: v } + } +} + +impl From for DocumentTransferTransition { + fn from(v: DocumentTransferTransitionWasm) -> Self { + v.inner + } +} + +#[wasm_bindgen(js_class=DocumentTransferTransition)] +impl DocumentTransferTransitionWasm { + // #[wasm_bindgen(constructor)] + // pub fn from_object( + // raw_object: JsValue, + // data_contract: &DataContractWasm, + // ) -> Result { + // let mut value = raw_object.with_serde_to_platform_value_map()?; + // let document_type_name = value + // .get_string(dpp::document::extended_document::property_names::DOCUMENT_TYPE_NAME) + // .map_err(ProtocolError::ValueError) + // .with_js_error()?; + // + // let document_type = data_contract + // .inner() + // .document_type_for_name(&document_type_name) + // .with_js_error()?; + // let identifier_paths = document_type.identifier_paths(); + // let binary_paths = document_type.binary_paths(); + // + // value + // .replace_at_paths(identifier_paths, ReplacementType::Identifier) + // .map_err(ProtocolError::ValueError) + // .with_js_error()?; + // + // value + // .replace_at_paths(binary_paths, ReplacementType::BinaryBytes) + // .map_err(ProtocolError::ValueError) + // .with_js_error()?; + // let transition = + // DocumentTransferTransition::from_value_map(value, data_contract).with_js_error()?; + // + // Ok(transition.into()) + // } + // + // #[wasm_bindgen(js_name=getAction)] + // pub fn action(&self) -> u8 { + // DocumentTransitionActionType::Transfer as u8; + // } + // + // #[wasm_bindgen(js_name=getRevision)] + // pub fn revision(&self) -> Revision { + // self.inner.revision() + // } + // + // #[wasm_bindgen(js_name=getUpdatedAt)] + // pub fn updated_at(&self) -> Option { + // self.inner + // .updated_at() + // .map(|timestamp| js_sys::Date::new(&JsValue::from_f64(timestamp as f64))) + // } + // + // #[wasm_bindgen(js_name=toObject)] + // pub fn to_object( + // &self, + // options: &JsValue, + // data_contract: DataContractWasm, + // ) -> Result { + // let document_type = data_contract + // .inner() + // .document_type_for_name(self.inner.base().document_type_name()) + // .with_js_error()?; + // let identifier_paths = document_type.identifier_paths(); + // let binary_paths = document_type.binary_paths(); + // + // to_object( + // self.inner.to_object().with_js_error()?, + // options, + // identifier_paths + // .into_iter() + // .chain(document_transfer_transition::v0::IDENTIFIER_FIELDS), + // binary_paths, + // ) + // } + // + // #[wasm_bindgen(js_name=toJSON)] + // pub fn to_json(&self) -> Result { + // let value = self.inner.to_json().with_js_error()?; + // let serializer = serde_wasm_bindgen::Serializer::json_compatible(); + // let js_value = value.serialize(&serializer)?; + // Ok(js_value) + // } + // + // // AbstractDataDocumentTransition + // #[wasm_bindgen(js_name=getData)] + // pub fn get_data(&self, data_contract: DataContractWasm) -> Result { + // let data = if let Some(ref data) = self.inner.data() { + // data + // } else { + // return Ok(JsValue::undefined()); + // }; + // + // let js_value = data.serialize(&serde_wasm_bindgen::Serializer::json_compatible())?; + // let document_type = data_contract + // .inner() + // .document_type_for_name(self.inner.base().document_type_name()) + // .with_js_error()?; + // let identifier_paths = document_type.identifier_paths(); + // let binary_paths = document_type.binary_paths(); + // + // for path in identifier_paths { + // let bytes = data + // .get_identifier_bytes_at_path(path) + // .map_err(ProtocolError::ValueError) + // .with_js_error()?; + // let id = >::from( + // Identifier::from_bytes(&bytes).unwrap(), + // ); + // lodash_set(&js_value, path, id.into()); + // } + // for path in binary_paths { + // let bytes = data + // .get_binary_bytes_at_path(path) + // .map_err(ProtocolError::ValueError) + // .with_js_error()?; + // let buffer = Buffer::from_bytes(&bytes); + // lodash_set(&js_value, path, buffer.into()); + // } + // + // Ok(js_value) + // } + // + // // AbstractDocumentTransition + // #[wasm_bindgen(js_name=getId)] + // pub fn id(&self) -> IdentifierWrapper { + // self.inner.base().id().into() + // } + // + // #[wasm_bindgen(js_name=getType)] + // pub fn document_type(&self) -> String { + // self.inner.base().document_type_name().clone() + // } + // + // #[wasm_bindgen(js_name=getDataContractId)] + // pub fn data_contract_id(&self) -> IdentifierWrapper { + // self.inner.base().data_contract_id().into() + // } + // + // #[wasm_bindgen(js_name=get)] + // pub fn get(&self, path: String) -> Result { + // let document_data = if let Some(ref data) = self.inner.data() { + // data + // } else { + // return Ok(JsValue::undefined()); + // }; + // + // let value = if let Ok(value) = document_data.get_at_path(&path) { + // value.to_owned() + // } else { + // return Ok(JsValue::undefined()); + // }; + // + // match self.get_binary_type_of_path(&path) { + // BinaryType::Buffer => { + // let bytes: Vec = serde_json::from_value( + // value + // .try_into() + // .map_err(ProtocolError::ValueError) + // .with_js_error()?, + // ) + // .unwrap(); + // let buffer = Buffer::from_bytes(&bytes); + // return Ok(buffer.into()); + // } + // BinaryType::Identifier => { + // let bytes: Vec = serde_json::from_value( + // value + // .try_into() + // .map_err(ProtocolError::ValueError) + // .with_js_error()?, + // ) + // .unwrap(); + // let id = >::from( + // Identifier::from_bytes(&bytes).unwrap(), + // ); + // return Ok(id.into()); + // } + // BinaryType::None => { + // // Do nothing. If is 'None' it means that binary may contain binary data + // // or may not captain it at all + // } + // } + // + // let json_value: JsonValue = value + // .clone() + // .try_into() + // .map_err(ProtocolError::ValueError) + // .with_js_error()?; + // let map = value + // .to_btree_ref_string_map() + // .map_err(ProtocolError::ValueError) + // .with_js_error()?; + // let js_value = json_value.serialize(&serde_wasm_bindgen::Serializer::json_compatible())?; + // let (identifier_paths, binary_paths) = self + // .inner + // .base() + // .data_contract() + // .get_identifiers_and_binary_paths(&self.inner.base().document_type_name()) + // .with_js_error()?; + // + // for property_path in identifier_paths { + // if property_path.starts_with(&path) { + // let (_, suffix) = property_path.split_at(path.len() + 1); + // + // if let Some(bytes) = map + // .get_optional_bytes_at_path(suffix) + // .map_err(ProtocolError::ValueError) + // .with_js_error()? + // { + // let id = >::from( + // Identifier::from_bytes(&bytes).unwrap(), + // ); + // lodash_set(&js_value, suffix, id.into()); + // } + // } + // } + // + // for property_path in binary_paths { + // if property_path.starts_with(&path) { + // let (_, suffix) = property_path.split_at(path.len() + 1); + // + // if let Some(bytes) = map + // .get_optional_bytes_at_path(suffix) + // .map_err(ProtocolError::ValueError) + // .with_js_error()? + // { + // let buffer = Buffer::from_bytes(&bytes); + // lodash_set(&js_value, suffix, buffer.into()); + // } + // } + // } + // + // Ok(js_value) + // } +} + +impl DocumentTransferTransitionWasm { + // fn get_binary_type_of_path(&self, path: &String) -> BinaryType { + // let maybe_binary_properties = self + // .inner + // .get_binary_properties(&self.inner.base().document_type_name()); + // + // if let Ok(binary_properties) = maybe_binary_properties { + // if let Some(data) = binary_properties.get(path) { + // if data.is_type_of_identifier() { + // return BinaryType::Identifier; + // } + // return BinaryType::Buffer; + // } + // } + // BinaryType::None + // } +} diff --git a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs b/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs index d4ad4e89f5f..300ed732ee5 100644 --- a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs +++ b/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs @@ -1,4 +1,5 @@ mod document_create_transition; +mod document_transfer_transition; // mod document_delete_transition; // mod document_replace_transition; From 1d7159adaca1f5229b9806c4f7c413f4fa91d46e Mon Sep 17 00:00:00 2001 From: pshenmic Date: Sat, 5 Oct 2024 23:46:30 +0700 Subject: [PATCH 02/50] feat(js-dash-sk): add transfer to document broadcast --- .../src/SDK/Client/Platform/methods/documents/broadcast.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts index 4a6a7a06026..876cc8e0106 100644 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts @@ -18,7 +18,8 @@ export default async function broadcast( documents: { create?: ExtendedDocument[], replace?: ExtendedDocument[], - delete?: ExtendedDocument[] + delete?: ExtendedDocument[], + transfer?: ExtendedDocument[] }, identity: any, ): Promise { @@ -26,6 +27,7 @@ export default async function broadcast( create: documents.create?.length || 0, replace: documents.replace?.length || 0, delete: documents.delete?.length || 0, + transfer: documents.transfer?.length || 0, }); await this.initialize(); @@ -36,6 +38,7 @@ export default async function broadcast( ...(documents.create || []), ...(documents.replace || []), ...(documents.delete || []), + ...(documents.transfer || []), ][0]?.getDataContractId(); if (!dataContractId) { @@ -79,6 +82,7 @@ export default async function broadcast( create: documents.create?.length || 0, replace: documents.replace?.length || 0, delete: documents.delete?.length || 0, + transfer: documents.transfer?.length || 0, }); return documentsBatchTransition; From 1d1a505f329504159d3a3b137930563f5320f01c Mon Sep 17 00:00:00 2001 From: pshenmic Date: Sat, 5 Oct 2024 23:59:01 +0700 Subject: [PATCH 03/50] fix(dpp): add missing import --- packages/rs-dpp/src/document/document_factory/v0/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/rs-dpp/src/document/document_factory/v0/mod.rs b/packages/rs-dpp/src/document/document_factory/v0/mod.rs index 5aa64b775a3..68be2142af8 100644 --- a/packages/rs-dpp/src/document/document_factory/v0/mod.rs +++ b/packages/rs-dpp/src/document/document_factory/v0/mod.rs @@ -32,6 +32,7 @@ use crate::state_transition::documents_batch_transition::{ DocumentsBatchTransition, DocumentsBatchTransitionV0, }; use itertools::Itertools; +use crate::state_transition::documents_batch_transition::document_transition::DocumentTransferTransition; const PROPERTY_FEATURE_VERSION: &str = "$version"; const PROPERTY_ENTROPY: &str = "$entropy"; From ad94fa6c32dd995bf267764e30a2e1d6ae53ac8f Mon Sep 17 00:00:00 2001 From: pshenmic Date: Sun, 6 Oct 2024 00:01:16 +0700 Subject: [PATCH 04/50] feat(js-dash-sdk): add transfer function wip --- .../src/SDK/Client/Platform/Platform.ts | 3 ++ .../Platform/methods/documents/transfer.ts | 40 +++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/Platform.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/Platform.ts index 873fe62c53d..cd105ed87b7 100644 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/Platform.ts +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/Platform.ts @@ -9,6 +9,7 @@ import createAssetLockTransaction from './createAssetLockTransaction'; import broadcastDocument from './methods/documents/broadcast'; import createDocument from './methods/documents/create'; +import transferDocument from './methods/documents/transfer'; import getDocument from './methods/documents/get'; import publishContract from './methods/contracts/publish'; @@ -58,6 +59,7 @@ export interface PlatformOpts { interface Records { broadcast: Function, create: Function, + transfer: Function, get: Function, } @@ -165,6 +167,7 @@ export class Platform { this.documents = { broadcast: broadcastDocument.bind(this), create: createDocument.bind(this), + transfer: transferDocument.bind(this), get: getDocument.bind(this), }; this.contracts = { diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts new file mode 100644 index 00000000000..0e27ce2bb6e --- /dev/null +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts @@ -0,0 +1,40 @@ +import { Platform } from '../../Platform'; +import broadcastStateTransition from '../../broadcastStateTransition'; + +/** + * Transfer document in the platform + * + * @param {Platform} this - bound instance class + * @param {string} typeLocator - type locator + * @param identity - identity + * @param {Object} [data] - options + */ +export async function transfer( + this: Platform, + documentId: string, + identity: any, +): Promise { + this.logger.debug(`[Document#transfer] Transfer document`); + await this.initialize(); + + const { dpp } = this; + + const document = await this.documents.get(documentId); + + this.logger.silly(`[Document#create] Obtained document ${document.getId()}`); + + if (document === null) { + throw new Error(`Document ${documentId} not found. Ensure contractId ${documentId} is correct.`); + } + + document.setOwnerId(identity); + + const transition = dpp.document.createStateTransition( + { transfer: [document] }, + identity.getId(), + ); + + await broadcastStateTransition(this, transition); +} + +export default transfer; From f3b04f2a20ee609eddcb28f085ba9367cf87148a Mon Sep 17 00:00:00 2001 From: pshenmic Date: Wed, 25 Dec 2024 00:21:50 +0700 Subject: [PATCH 05/50] feat(js-sdk): implement working document transfers --- .../Platform/methods/documents/broadcast.ts | 9 ++--- .../Platform/methods/documents/transfer.ts | 32 +++++++---------- .../src/document/document_factory/v0/mod.rs | 20 +++++++++-- .../specialized_document_factory/v0/mod.rs | 17 +++++++-- .../documents_batch/transformer/v0/mod.rs | 2 +- .../src/document/extended_document.rs | 36 ++++++++++++++++--- .../document_transfer_transition.rs | 28 +-------------- 7 files changed, 83 insertions(+), 61 deletions(-) diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts index 876cc8e0106..cc6bc90f63f 100644 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts @@ -6,12 +6,12 @@ import { signStateTransition } from '../../signStateTransition'; /** * Broadcast document onto the platform * - * @param {Platform} this - bound instance class * @param {Object} documents * @param {ExtendedDocument[]} [documents.create] * @param {ExtendedDocument[]} [documents.replace] * @param {ExtendedDocument[]} [documents.delete] * @param identity - identity + * @param keyIndex - identity key index */ export default async function broadcast( this: Platform, @@ -19,15 +19,14 @@ export default async function broadcast( create?: ExtendedDocument[], replace?: ExtendedDocument[], delete?: ExtendedDocument[], - transfer?: ExtendedDocument[] }, identity: any, + keyIndex : number, ): Promise { this.logger.debug('[Document#broadcast] Broadcast documents', { create: documents.create?.length || 0, replace: documents.replace?.length || 0, delete: documents.delete?.length || 0, - transfer: documents.transfer?.length || 0, }); await this.initialize(); @@ -38,7 +37,6 @@ export default async function broadcast( ...(documents.create || []), ...(documents.replace || []), ...(documents.delete || []), - ...(documents.transfer || []), ][0]?.getDataContractId(); if (!dataContractId) { @@ -56,7 +54,7 @@ export default async function broadcast( this.logger.silly('[Document#broadcast] Created documents batch transition'); - await signStateTransition(this, documentsBatchTransition, identity, 1); + await signStateTransition(this, documentsBatchTransition, identity, keyIndex ?? 1); // Broadcast state transition also wait for the result to be obtained await broadcastStateTransition(this, documentsBatchTransition); @@ -82,7 +80,6 @@ export default async function broadcast( create: documents.create?.length || 0, replace: documents.replace?.length || 0, delete: documents.delete?.length || 0, - transfer: documents.transfer?.length || 0, }); return documentsBatchTransition; diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts index 0e27ce2bb6e..43ccb1b39a7 100644 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts @@ -1,6 +1,7 @@ +import { Identity, ExtendedDocument } from '@dashevo/wasm-dpp'; import { Platform } from '../../Platform'; import broadcastStateTransition from '../../broadcastStateTransition'; - +import { signStateTransition } from '../../signStateTransition'; /** * Transfer document in the platform * @@ -8,33 +9,26 @@ import broadcastStateTransition from '../../broadcastStateTransition'; * @param {string} typeLocator - type locator * @param identity - identity * @param {Object} [data] - options + * @returns {StateTransition} */ export async function transfer( this: Platform, - documentId: string, - identity: any, + document: ExtendedDocument, + receiver: Identity, + sender: Identity, ): Promise { - this.logger.debug(`[Document#transfer] Transfer document`); + this.logger.debug('[Document#transfer] Transfer document'); await this.initialize(); - const { dpp } = this; - - const document = await this.documents.get(documentId); - - this.logger.silly(`[Document#create] Obtained document ${document.getId()}`); - - if (document === null) { - throw new Error(`Document ${documentId} not found. Ensure contractId ${documentId} is correct.`); - } + const identityContractNonce = await this.nonceManager + .bumpIdentityContractNonce(sender.getId(), document.getDataContractId()); - document.setOwnerId(identity); + const documentsBatchTransition = document + .createTransferTransition(receiver.getId(), BigInt(identityContractNonce)); - const transition = dpp.document.createStateTransition( - { transfer: [document] }, - identity.getId(), - ); + await signStateTransition(this, documentsBatchTransition, sender, 1); - await broadcastStateTransition(this, transition); + await broadcastStateTransition(this, documentsBatchTransition); } export default transfer; diff --git a/packages/rs-dpp/src/document/document_factory/v0/mod.rs b/packages/rs-dpp/src/document/document_factory/v0/mod.rs index 68be2142af8..0280286f346 100644 --- a/packages/rs-dpp/src/document/document_factory/v0/mod.rs +++ b/packages/rs-dpp/src/document/document_factory/v0/mod.rs @@ -263,9 +263,25 @@ impl DocumentFactoryV0 { nonce_counter, platform_version, ), - _ => Err(ProtocolError::InvalidStateTransitionType( - "action type not accounted for".to_string(), + DocumentTransitionActionType::Transfer => Self::document_transfer_transitions( + documents + .into_iter() + .map(|(document, document_type, _)| (document, document_type)) + .collect(), + nonce_counter, + platform_version, + ), + DocumentTransitionActionType::Purchase => { + Err(ProtocolError::InvalidStateTransitionType( + "action type not accounted for Transfer".to_string(), + )) + } + DocumentTransitionActionType::UpdatePrice => Err(ProtocolError::InvalidStateTransitionType( + "action type not accounted for UpdatePrice".to_string(), )), + DocumentTransitionActionType::IgnoreWhileBumpingRevision => Err(ProtocolError::InvalidStateTransitionType( + "action type not accounted for IgnoreWhileBumpingRevision".to_string(), + )) }) .collect::, ProtocolError>>()? .into_iter() diff --git a/packages/rs-dpp/src/document/specialized_document_factory/v0/mod.rs b/packages/rs-dpp/src/document/specialized_document_factory/v0/mod.rs index e482d3822a7..56193af6ad8 100644 --- a/packages/rs-dpp/src/document/specialized_document_factory/v0/mod.rs +++ b/packages/rs-dpp/src/document/specialized_document_factory/v0/mod.rs @@ -270,9 +270,22 @@ impl SpecializedDocumentFactoryV0 { nonce_counter, platform_version, ), - _ => Err(ProtocolError::InvalidStateTransitionType( - "action type not accounted for".to_string(), + DocumentTransitionActionType::Transfer => { + Err(ProtocolError::InvalidStateTransitionType( + "action type not accounted for Transfer".to_string(), + )) + }, + DocumentTransitionActionType::Purchase => { + Err(ProtocolError::InvalidStateTransitionType( + "action type not accounted for Purchase".to_string(), + )) + } + DocumentTransitionActionType::UpdatePrice => Err(ProtocolError::InvalidStateTransitionType( + "action type not accounted for UpdatePrice".to_string(), )), + DocumentTransitionActionType::IgnoreWhileBumpingRevision => Err(ProtocolError::InvalidStateTransitionType( + "action type not accounted for IgnoreWhileBumpingRevision".to_string(), + )) }) .collect::, ProtocolError>>()? .into_iter() diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/documents_batch/transformer/v0/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/documents_batch/transformer/v0/mod.rs index 68ec4de478e..1de6aa765cd 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/documents_batch/transformer/v0/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/documents_batch/transformer/v0/mod.rs @@ -720,7 +720,7 @@ impl DocumentsBatchTransitionInternalTransformerV0 for DocumentsBatchTransition StateError::InvalidDocumentRevisionError(InvalidDocumentRevisionError::new( document_id, Some(previous_revision), - transition_revision, + expected_revision, )), )) } diff --git a/packages/wasm-dpp/src/document/extended_document.rs b/packages/wasm-dpp/src/document/extended_document.rs index a33ab17f293..289c61c873b 100644 --- a/packages/wasm-dpp/src/document/extended_document.rs +++ b/packages/wasm-dpp/src/document/extended_document.rs @@ -1,10 +1,8 @@ -use dpp::document::{ - DocumentV0Getters, DocumentV0Setters, ExtendedDocument, EXTENDED_DOCUMENT_IDENTIFIER_FIELDS, -}; +use dpp::document::{DocumentV0Getters, DocumentV0Setters, ExtendedDocument, EXTENDED_DOCUMENT_IDENTIFIER_FIELDS}; use serde_json::Value as JsonValue; use dpp::platform_value::{Bytes32, Value}; -use dpp::prelude::{Identifier, Revision, TimestampMillis}; +use dpp::prelude::{Identifier, IdentityNonce, Revision, TimestampMillis, UserFeeIncrease}; use dpp::util::json_value::JsonValueExt; @@ -16,12 +14,15 @@ use dpp::ProtocolError; use serde::{Deserialize, Serialize}; use std::convert::TryInto; use wasm_bindgen::prelude::*; +use dpp::state_transition::documents_batch_transition::document_transition::DocumentTransferTransition; +use dpp::state_transition::documents_batch_transition::{DocumentsBatchTransition, DocumentsBatchTransitionV0}; use crate::buffer::Buffer; use crate::data_contract::DataContractWasm; #[allow(deprecated)] // BinaryType is unsed in unused code below use crate::document::BinaryType; use crate::document::{ConversionOptions, DocumentWasm}; +use crate::document_batch_transition::DocumentsBatchTransitionWasm; use crate::errors::RustConversionError; use crate::identifier::{identifier_from_js_value, IdentifierWrapper}; use crate::lodash::lodash_set; @@ -233,6 +234,33 @@ impl ExtendedDocumentWasm { .set_created_at(ts.map(|t| t.get_time() as TimestampMillis)); } + #[wasm_bindgen(js_name=createTransferTransition)] + pub fn create_transfer_transition(&mut self, recipient: IdentifierWrapper, identity_contract_nonce: IdentityNonce) -> DocumentsBatchTransitionWasm { + let mut cloned_document = self.0.document().clone(); + + cloned_document.set_revision(Some(cloned_document.revision().unwrap() + 1)); + + let transfer_transition = DocumentTransferTransition::from_document( + cloned_document, + self.0.document_type().unwrap(), + identity_contract_nonce, + recipient.try_into().expect("identity into failed"), + PlatformVersion::latest(), + None, + None, + ).unwrap(); + + let documents_batch_transition: DocumentsBatchTransition = DocumentsBatchTransitionV0 { + owner_id: self.0.owner_id(), + transitions: vec![transfer_transition.into()], + user_fee_increase: Default::default(), + signature_public_key_id: Default::default(), + signature: Default::default(), + }.try_into().expect("Failed to convert into DocumentsBatchTransition"); + + documents_batch_transition.try_into().expect("Failed to convert into DocumentsBatchTransitionWasm") + } + #[wasm_bindgen(js_name=setUpdatedAt)] pub fn set_updated_at(&mut self, ts: Option) { self.0 diff --git a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_transfer_transition.rs b/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_transfer_transition.rs index b6e9cdfba7e..0ebbf8e508c 100644 --- a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_transfer_transition.rs +++ b/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_transfer_transition.rs @@ -1,30 +1,4 @@ -use std::convert; - -use serde_json::Value as JsonValue; - -use dpp::platform_value::btreemap_extensions::{ - BTreeValueMapHelper, BTreeValueMapReplacementPathHelper, -}; -use dpp::platform_value::ReplacementType; -use dpp::prelude::Revision; -use dpp::{ - prelude::{Identifier}, - ProtocolError, -}; -use wasm_bindgen::prelude::*; -use dpp::data_contract::accessors::v0::DataContractV0Getters; -use dpp::state_transition::documents_batch_transition::document_base_transition::v0::v0_methods::DocumentBaseTransitionV0Methods; - -use crate::{ - buffer::Buffer, - document::state_transition::document_batch_transition::document_transition::to_object, - identifier::IdentifierWrapper, - lodash::lodash_set, - utils::{ToSerdeJSONExt, WithJsError}, - BinaryType, DataContractWasm, -}; -use dpp::state_transition::documents_batch_transition::document_transition::action_type::DocumentTransitionActionType; -use dpp::state_transition::documents_batch_transition::document_transition::document_transfer_transition::v0::v0_methods::DocumentTransferTransitionV0Methods; +use wasm_bindgen::prelude::wasm_bindgen; use dpp::state_transition::documents_batch_transition::document_transition::DocumentTransferTransition; #[wasm_bindgen(js_name=DocumentTransferTransition)] From 7011e0940024a8ee1d6676a2d0436b1f2dcb8179 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Wed, 25 Dec 2024 00:28:32 +0700 Subject: [PATCH 06/50] chore(js-sdk): cleanup --- packages/wasm-dpp/src/document/extended_document.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/wasm-dpp/src/document/extended_document.rs b/packages/wasm-dpp/src/document/extended_document.rs index 289c61c873b..52ff9f668f6 100644 --- a/packages/wasm-dpp/src/document/extended_document.rs +++ b/packages/wasm-dpp/src/document/extended_document.rs @@ -234,8 +234,8 @@ impl ExtendedDocumentWasm { .set_created_at(ts.map(|t| t.get_time() as TimestampMillis)); } - #[wasm_bindgen(js_name=createTransferTransition)] - pub fn create_transfer_transition(&mut self, recipient: IdentifierWrapper, identity_contract_nonce: IdentityNonce) -> DocumentsBatchTransitionWasm { + #[wasm_bindgen(js_name=createTransferStateTransition)] + pub fn create_transfer_state_transition(&mut self, recipient: IdentifierWrapper, identity_contract_nonce: IdentityNonce) -> DocumentsBatchTransitionWasm { let mut cloned_document = self.0.document().clone(); cloned_document.set_revision(Some(cloned_document.revision().unwrap() + 1)); @@ -244,7 +244,7 @@ impl ExtendedDocumentWasm { cloned_document, self.0.document_type().unwrap(), identity_contract_nonce, - recipient.try_into().expect("identity into failed"), + recipient.into(), PlatformVersion::latest(), None, None, @@ -256,9 +256,9 @@ impl ExtendedDocumentWasm { user_fee_increase: Default::default(), signature_public_key_id: Default::default(), signature: Default::default(), - }.try_into().expect("Failed to convert into DocumentsBatchTransition"); + }.into(); - documents_batch_transition.try_into().expect("Failed to convert into DocumentsBatchTransitionWasm") + documents_batch_transition.into() } #[wasm_bindgen(js_name=setUpdatedAt)] From 01975816931b77854f6da41068e1acf2928035f8 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Wed, 25 Dec 2024 00:48:47 +0700 Subject: [PATCH 07/50] chore(js-sdk): cleanup --- .../src/SDK/Client/Platform/methods/documents/broadcast.ts | 5 ++--- .../src/SDK/Client/Platform/methods/documents/transfer.ts | 5 +++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts index cc6bc90f63f..b1ed30b17c8 100644 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts @@ -6,12 +6,12 @@ import { signStateTransition } from '../../signStateTransition'; /** * Broadcast document onto the platform * + * @param {Platform} this - bound instance class * @param {Object} documents * @param {ExtendedDocument[]} [documents.create] * @param {ExtendedDocument[]} [documents.replace] * @param {ExtendedDocument[]} [documents.delete] * @param identity - identity - * @param keyIndex - identity key index */ export default async function broadcast( this: Platform, @@ -21,7 +21,6 @@ export default async function broadcast( delete?: ExtendedDocument[], }, identity: any, - keyIndex : number, ): Promise { this.logger.debug('[Document#broadcast] Broadcast documents', { create: documents.create?.length || 0, @@ -54,7 +53,7 @@ export default async function broadcast( this.logger.silly('[Document#broadcast] Created documents batch transition'); - await signStateTransition(this, documentsBatchTransition, identity, keyIndex ?? 1); + await signStateTransition(this, documentsBatchTransition, identity, 1); // Broadcast state transition also wait for the result to be obtained await broadcastStateTransition(this, documentsBatchTransition); diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts index 43ccb1b39a7..31fa427d113 100644 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts @@ -17,14 +17,15 @@ export async function transfer( receiver: Identity, sender: Identity, ): Promise { - this.logger.debug('[Document#transfer] Transfer document'); + this.logger.debug(`[Document#transfer] Transfer document ${document.getId().toString()} + from ${sender.getId().toString} to {${receiver.getId().toString()}`); await this.initialize(); const identityContractNonce = await this.nonceManager .bumpIdentityContractNonce(sender.getId(), document.getDataContractId()); const documentsBatchTransition = document - .createTransferTransition(receiver.getId(), BigInt(identityContractNonce)); + .createTransferStateTransition(receiver.getId(), BigInt(identityContractNonce)); await signStateTransition(this, documentsBatchTransition, sender, 1); From 9abbd8ff002113c8aba73493741f71c83f05294e Mon Sep 17 00:00:00 2001 From: pshenmic Date: Wed, 25 Dec 2024 00:49:10 +0700 Subject: [PATCH 08/50] chore(wasm-dpp): cleanup --- .../src/document/document_factory/v0/mod.rs | 107 +------- .../specialized_document_factory/v0/mod.rs | 17 +- packages/wasm-dpp/src/document/factory.rs | 8 - .../document_transfer_transition.rs | 247 ------------------ 4 files changed, 4 insertions(+), 375 deletions(-) diff --git a/packages/rs-dpp/src/document/document_factory/v0/mod.rs b/packages/rs-dpp/src/document/document_factory/v0/mod.rs index 0280286f346..6dc531398c7 100644 --- a/packages/rs-dpp/src/document/document_factory/v0/mod.rs +++ b/packages/rs-dpp/src/document/document_factory/v0/mod.rs @@ -263,25 +263,9 @@ impl DocumentFactoryV0 { nonce_counter, platform_version, ), - DocumentTransitionActionType::Transfer => Self::document_transfer_transitions( - documents - .into_iter() - .map(|(document, document_type, _)| (document, document_type)) - .collect(), - nonce_counter, - platform_version, - ), - DocumentTransitionActionType::Purchase => { - Err(ProtocolError::InvalidStateTransitionType( - "action type not accounted for Transfer".to_string(), - )) - } - DocumentTransitionActionType::UpdatePrice => Err(ProtocolError::InvalidStateTransitionType( - "action type not accounted for UpdatePrice".to_string(), + _ => Err(ProtocolError::InvalidStateTransitionType( + "action type not accounted for".to_string(), )), - DocumentTransitionActionType::IgnoreWhileBumpingRevision => Err(ProtocolError::InvalidStateTransitionType( - "action type not accounted for IgnoreWhileBumpingRevision".to_string(), - )) }) .collect::, ProtocolError>>()? .into_iter() @@ -524,93 +508,6 @@ impl DocumentFactoryV0 { // Ok(raw_transitions) } - #[cfg(feature = "state-transitions")] - fn document_transfer_transitions( - documents: Vec<(Document, DocumentTypeRef)>, - nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce - platform_version: &PlatformVersion, - ) -> Result, ProtocolError> { - documents - .into_iter() - .map(|(mut document, document_type)| { - if !document_type.documents_mutable() { - return Err(DocumentError::TryingToReplaceImmutableDocument { - document: Box::new(document), - } - .into()); - } - if document.revision().is_none() { - return Err(DocumentError::RevisionAbsentError { - document: Box::new(document), - } - .into()); - }; - - document.increment_revision()?; - document.set_updated_at(Some(Utc::now().timestamp_millis() as TimestampMillis)); - - let recipient_owner_id = document.owner_id(); - - let nonce = nonce_counter - .entry((document.owner_id(), document_type.data_contract_id())) - .or_default(); - - let transition = DocumentTransferTransition::from_document( - document, - document_type, - *nonce, - recipient_owner_id, - platform_version, - None, - None, - )?; - - *nonce += 1; - - Ok(transition.into()) - }) - .collect() - // let mut raw_transitions = vec![]; - // for (document, document_type) in documents { - // if !document_type.documents_mutable() { - // return Err(DocumentError::TryingToReplaceImmutableDocument { - // document: Box::new(document), - // } - // .into()); - // } - // let Some(document_revision) = document.revision() else { - // return Err(DocumentError::RevisionAbsentError { - // document: Box::new(document), - // }.into()); - // }; - // let mut map = document.to_map_value()?; - // - // map.retain(|key, _| { - // !key.starts_with('$') || DOCUMENT_REPLACE_KEYS_TO_STAY.contains(&key.as_str()) - // }); - // map.insert( - // PROPERTY_ACTION.to_string(), - // Value::U8(DocumentTransitionActionType::Replace as u8), - // ); - // let new_revision = document_revision + 1; - // map.insert(PROPERTY_REVISION.to_string(), Value::U64(new_revision)); - // - // // If document have an originally set `updatedAt` - // // we should update it then - // let contains_updated_at = document_type - // .required_fields() - // .contains(PROPERTY_UPDATED_AT); - // - // if contains_updated_at { - // let now = Utc::now().timestamp_millis() as TimestampMillis; - // map.insert(PROPERTY_UPDATED_AT.to_string(), Value::U64(now)); - // } - // - // raw_transitions.push(map.into()); - // } - // Ok(raw_transitions) - } - #[cfg(feature = "state-transitions")] fn document_delete_transitions( documents: Vec<(Document, DocumentTypeRef)>, diff --git a/packages/rs-dpp/src/document/specialized_document_factory/v0/mod.rs b/packages/rs-dpp/src/document/specialized_document_factory/v0/mod.rs index 56193af6ad8..e482d3822a7 100644 --- a/packages/rs-dpp/src/document/specialized_document_factory/v0/mod.rs +++ b/packages/rs-dpp/src/document/specialized_document_factory/v0/mod.rs @@ -270,22 +270,9 @@ impl SpecializedDocumentFactoryV0 { nonce_counter, platform_version, ), - DocumentTransitionActionType::Transfer => { - Err(ProtocolError::InvalidStateTransitionType( - "action type not accounted for Transfer".to_string(), - )) - }, - DocumentTransitionActionType::Purchase => { - Err(ProtocolError::InvalidStateTransitionType( - "action type not accounted for Purchase".to_string(), - )) - } - DocumentTransitionActionType::UpdatePrice => Err(ProtocolError::InvalidStateTransitionType( - "action type not accounted for UpdatePrice".to_string(), + _ => Err(ProtocolError::InvalidStateTransitionType( + "action type not accounted for".to_string(), )), - DocumentTransitionActionType::IgnoreWhileBumpingRevision => Err(ProtocolError::InvalidStateTransitionType( - "action type not accounted for IgnoreWhileBumpingRevision".to_string(), - )) }) .collect::, ProtocolError>>()? .into_iter() diff --git a/packages/wasm-dpp/src/document/factory.rs b/packages/wasm-dpp/src/document/factory.rs index 09ca8e37c9b..a62dbc3aeca 100644 --- a/packages/wasm-dpp/src/document/factory.rs +++ b/packages/wasm-dpp/src/document/factory.rs @@ -32,7 +32,6 @@ pub struct DocumentTransitions { create: Vec, replace: Vec, delete: Vec, - transfer: Vec, } #[wasm_bindgen(js_class=DocumentTransitions)] @@ -56,11 +55,6 @@ impl DocumentTransitions { pub fn add_transition_delete(&mut self, transition: ExtendedDocumentWasm) { self.delete.push(transition) } - - #[wasm_bindgen(js_name = "addTransitionTransfer")] - pub fn add_transition_transfer(&mut self, transition: ExtendedDocumentWasm) { - self.transfer.push(transition) - } } #[wasm_bindgen(js_name = DocumentFactory)] @@ -289,12 +283,10 @@ fn extract_documents_by_action( let documents_create = extract_documents_of_action(documents, "create").with_js_error()?; let documents_replace = extract_documents_of_action(documents, "replace").with_js_error()?; let documents_delete = extract_documents_of_action(documents, "delete").with_js_error()?; - let documents_transfer = extract_documents_of_action(documents, "transfer").with_js_error()?; documents_by_action.insert(DocumentTransitionActionType::Create, documents_create); documents_by_action.insert(DocumentTransitionActionType::Replace, documents_replace); documents_by_action.insert(DocumentTransitionActionType::Delete, documents_delete); - documents_by_action.insert(DocumentTransitionActionType::Transfer, documents_transfer); Ok(documents_by_action) } diff --git a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_transfer_transition.rs b/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_transfer_transition.rs index 0ebbf8e508c..c9c745d4098 100644 --- a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_transfer_transition.rs +++ b/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_transfer_transition.rs @@ -21,254 +21,7 @@ impl From for DocumentTransferTransition { #[wasm_bindgen(js_class=DocumentTransferTransition)] impl DocumentTransferTransitionWasm { - // #[wasm_bindgen(constructor)] - // pub fn from_object( - // raw_object: JsValue, - // data_contract: &DataContractWasm, - // ) -> Result { - // let mut value = raw_object.with_serde_to_platform_value_map()?; - // let document_type_name = value - // .get_string(dpp::document::extended_document::property_names::DOCUMENT_TYPE_NAME) - // .map_err(ProtocolError::ValueError) - // .with_js_error()?; - // - // let document_type = data_contract - // .inner() - // .document_type_for_name(&document_type_name) - // .with_js_error()?; - // let identifier_paths = document_type.identifier_paths(); - // let binary_paths = document_type.binary_paths(); - // - // value - // .replace_at_paths(identifier_paths, ReplacementType::Identifier) - // .map_err(ProtocolError::ValueError) - // .with_js_error()?; - // - // value - // .replace_at_paths(binary_paths, ReplacementType::BinaryBytes) - // .map_err(ProtocolError::ValueError) - // .with_js_error()?; - // let transition = - // DocumentTransferTransition::from_value_map(value, data_contract).with_js_error()?; - // - // Ok(transition.into()) - // } - // - // #[wasm_bindgen(js_name=getAction)] - // pub fn action(&self) -> u8 { - // DocumentTransitionActionType::Transfer as u8; - // } - // - // #[wasm_bindgen(js_name=getRevision)] - // pub fn revision(&self) -> Revision { - // self.inner.revision() - // } - // - // #[wasm_bindgen(js_name=getUpdatedAt)] - // pub fn updated_at(&self) -> Option { - // self.inner - // .updated_at() - // .map(|timestamp| js_sys::Date::new(&JsValue::from_f64(timestamp as f64))) - // } - // - // #[wasm_bindgen(js_name=toObject)] - // pub fn to_object( - // &self, - // options: &JsValue, - // data_contract: DataContractWasm, - // ) -> Result { - // let document_type = data_contract - // .inner() - // .document_type_for_name(self.inner.base().document_type_name()) - // .with_js_error()?; - // let identifier_paths = document_type.identifier_paths(); - // let binary_paths = document_type.binary_paths(); - // - // to_object( - // self.inner.to_object().with_js_error()?, - // options, - // identifier_paths - // .into_iter() - // .chain(document_transfer_transition::v0::IDENTIFIER_FIELDS), - // binary_paths, - // ) - // } - // - // #[wasm_bindgen(js_name=toJSON)] - // pub fn to_json(&self) -> Result { - // let value = self.inner.to_json().with_js_error()?; - // let serializer = serde_wasm_bindgen::Serializer::json_compatible(); - // let js_value = value.serialize(&serializer)?; - // Ok(js_value) - // } - // - // // AbstractDataDocumentTransition - // #[wasm_bindgen(js_name=getData)] - // pub fn get_data(&self, data_contract: DataContractWasm) -> Result { - // let data = if let Some(ref data) = self.inner.data() { - // data - // } else { - // return Ok(JsValue::undefined()); - // }; - // - // let js_value = data.serialize(&serde_wasm_bindgen::Serializer::json_compatible())?; - // let document_type = data_contract - // .inner() - // .document_type_for_name(self.inner.base().document_type_name()) - // .with_js_error()?; - // let identifier_paths = document_type.identifier_paths(); - // let binary_paths = document_type.binary_paths(); - // - // for path in identifier_paths { - // let bytes = data - // .get_identifier_bytes_at_path(path) - // .map_err(ProtocolError::ValueError) - // .with_js_error()?; - // let id = >::from( - // Identifier::from_bytes(&bytes).unwrap(), - // ); - // lodash_set(&js_value, path, id.into()); - // } - // for path in binary_paths { - // let bytes = data - // .get_binary_bytes_at_path(path) - // .map_err(ProtocolError::ValueError) - // .with_js_error()?; - // let buffer = Buffer::from_bytes(&bytes); - // lodash_set(&js_value, path, buffer.into()); - // } - // - // Ok(js_value) - // } - // - // // AbstractDocumentTransition - // #[wasm_bindgen(js_name=getId)] - // pub fn id(&self) -> IdentifierWrapper { - // self.inner.base().id().into() - // } - // - // #[wasm_bindgen(js_name=getType)] - // pub fn document_type(&self) -> String { - // self.inner.base().document_type_name().clone() - // } - // - // #[wasm_bindgen(js_name=getDataContractId)] - // pub fn data_contract_id(&self) -> IdentifierWrapper { - // self.inner.base().data_contract_id().into() - // } - // - // #[wasm_bindgen(js_name=get)] - // pub fn get(&self, path: String) -> Result { - // let document_data = if let Some(ref data) = self.inner.data() { - // data - // } else { - // return Ok(JsValue::undefined()); - // }; - // - // let value = if let Ok(value) = document_data.get_at_path(&path) { - // value.to_owned() - // } else { - // return Ok(JsValue::undefined()); - // }; - // - // match self.get_binary_type_of_path(&path) { - // BinaryType::Buffer => { - // let bytes: Vec = serde_json::from_value( - // value - // .try_into() - // .map_err(ProtocolError::ValueError) - // .with_js_error()?, - // ) - // .unwrap(); - // let buffer = Buffer::from_bytes(&bytes); - // return Ok(buffer.into()); - // } - // BinaryType::Identifier => { - // let bytes: Vec = serde_json::from_value( - // value - // .try_into() - // .map_err(ProtocolError::ValueError) - // .with_js_error()?, - // ) - // .unwrap(); - // let id = >::from( - // Identifier::from_bytes(&bytes).unwrap(), - // ); - // return Ok(id.into()); - // } - // BinaryType::None => { - // // Do nothing. If is 'None' it means that binary may contain binary data - // // or may not captain it at all - // } - // } - // - // let json_value: JsonValue = value - // .clone() - // .try_into() - // .map_err(ProtocolError::ValueError) - // .with_js_error()?; - // let map = value - // .to_btree_ref_string_map() - // .map_err(ProtocolError::ValueError) - // .with_js_error()?; - // let js_value = json_value.serialize(&serde_wasm_bindgen::Serializer::json_compatible())?; - // let (identifier_paths, binary_paths) = self - // .inner - // .base() - // .data_contract() - // .get_identifiers_and_binary_paths(&self.inner.base().document_type_name()) - // .with_js_error()?; - // - // for property_path in identifier_paths { - // if property_path.starts_with(&path) { - // let (_, suffix) = property_path.split_at(path.len() + 1); - // - // if let Some(bytes) = map - // .get_optional_bytes_at_path(suffix) - // .map_err(ProtocolError::ValueError) - // .with_js_error()? - // { - // let id = >::from( - // Identifier::from_bytes(&bytes).unwrap(), - // ); - // lodash_set(&js_value, suffix, id.into()); - // } - // } - // } - // - // for property_path in binary_paths { - // if property_path.starts_with(&path) { - // let (_, suffix) = property_path.split_at(path.len() + 1); - // - // if let Some(bytes) = map - // .get_optional_bytes_at_path(suffix) - // .map_err(ProtocolError::ValueError) - // .with_js_error()? - // { - // let buffer = Buffer::from_bytes(&bytes); - // lodash_set(&js_value, suffix, buffer.into()); - // } - // } - // } - // - // Ok(js_value) - // } } impl DocumentTransferTransitionWasm { - // fn get_binary_type_of_path(&self, path: &String) -> BinaryType { - // let maybe_binary_properties = self - // .inner - // .get_binary_properties(&self.inner.base().document_type_name()); - // - // if let Ok(binary_properties) = maybe_binary_properties { - // if let Some(data) = binary_properties.get(path) { - // if data.is_type_of_identifier() { - // return BinaryType::Identifier; - // } - // return BinaryType::Buffer; - // } - // } - // BinaryType::None - // } } From 5ddc68cfde3396065ba5de992e6a8d0c7692971b Mon Sep 17 00:00:00 2001 From: pshenmic Date: Wed, 25 Dec 2024 03:30:02 +0700 Subject: [PATCH 09/50] chore(js-sdk): cleanup --- .../src/SDK/Client/Platform/methods/documents/transfer.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts index 31fa427d113..6f8f847d096 100644 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts @@ -17,8 +17,7 @@ export async function transfer( receiver: Identity, sender: Identity, ): Promise { - this.logger.debug(`[Document#transfer] Transfer document ${document.getId().toString()} - from ${sender.getId().toString} to {${receiver.getId().toString()}`); + this.logger.debug(`[Document#transfer] Transfer document ${document.getId().toString()} from ${sender.getId().toString} to {${receiver.getId().toString()}`); await this.initialize(); const identityContractNonce = await this.nonceManager From 7411a01d18948204d626fb3a4c3ea0eb45557e4f Mon Sep 17 00:00:00 2001 From: pshenmic Date: Wed, 25 Dec 2024 03:33:10 +0700 Subject: [PATCH 10/50] chore(js-sdk): revert --- .../src/SDK/Client/Platform/methods/documents/broadcast.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts index b1ed30b17c8..bba6e90b5ff 100644 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts @@ -25,7 +25,7 @@ export default async function broadcast( this.logger.debug('[Document#broadcast] Broadcast documents', { create: documents.create?.length || 0, replace: documents.replace?.length || 0, - delete: documents.delete?.length || 0, + delete: documents.delete?.length || 0 }); await this.initialize(); From 79842cd4c05c3246057d8dacd22371a0b33bf452 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Wed, 25 Dec 2024 03:33:51 +0700 Subject: [PATCH 11/50] chore(js-sdk): cleanup --- .../src/SDK/Client/Platform/methods/documents/broadcast.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts index bba6e90b5ff..27377cbc76e 100644 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts @@ -25,7 +25,7 @@ export default async function broadcast( this.logger.debug('[Document#broadcast] Broadcast documents', { create: documents.create?.length || 0, replace: documents.replace?.length || 0, - delete: documents.delete?.length || 0 + delete: documents.delete?.length || 0, }); await this.initialize(); @@ -35,7 +35,7 @@ export default async function broadcast( const dataContractId = [ ...(documents.create || []), ...(documents.replace || []), - ...(documents.delete || []), + ...(documents.delete || []) ][0]?.getDataContractId(); if (!dataContractId) { From 995918fbdb3cd217a7565678bf67fe5d0b86e95b Mon Sep 17 00:00:00 2001 From: pshenmic Date: Wed, 25 Dec 2024 03:34:14 +0700 Subject: [PATCH 12/50] chore(js-sdk): cleanup --- .../src/SDK/Client/Platform/methods/documents/broadcast.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts index 27377cbc76e..bba6e90b5ff 100644 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts @@ -25,7 +25,7 @@ export default async function broadcast( this.logger.debug('[Document#broadcast] Broadcast documents', { create: documents.create?.length || 0, replace: documents.replace?.length || 0, - delete: documents.delete?.length || 0, + delete: documents.delete?.length || 0 }); await this.initialize(); @@ -35,7 +35,7 @@ export default async function broadcast( const dataContractId = [ ...(documents.create || []), ...(documents.replace || []), - ...(documents.delete || []) + ...(documents.delete || []), ][0]?.getDataContractId(); if (!dataContractId) { From 1c2d730379e1ed098d8a0a96be68e13ffcf5ed2f Mon Sep 17 00:00:00 2001 From: pshenmic Date: Wed, 25 Dec 2024 03:35:06 +0700 Subject: [PATCH 13/50] chore(js-sdk): cleanup --- .../src/SDK/Client/Platform/methods/documents/broadcast.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts index bba6e90b5ff..4a6a7a06026 100644 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts @@ -18,14 +18,14 @@ export default async function broadcast( documents: { create?: ExtendedDocument[], replace?: ExtendedDocument[], - delete?: ExtendedDocument[], + delete?: ExtendedDocument[] }, identity: any, ): Promise { this.logger.debug('[Document#broadcast] Broadcast documents', { create: documents.create?.length || 0, replace: documents.replace?.length || 0, - delete: documents.delete?.length || 0 + delete: documents.delete?.length || 0, }); await this.initialize(); From d23c2d34a5c9f960e3be452724f7eeeca5a1fb04 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Wed, 25 Dec 2024 03:37:10 +0700 Subject: [PATCH 14/50] chore(js-sdk): update doc --- .../src/SDK/Client/Platform/methods/documents/transfer.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts index 6f8f847d096..e211364b27b 100644 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts @@ -6,10 +6,9 @@ import { signStateTransition } from '../../signStateTransition'; * Transfer document in the platform * * @param {Platform} this - bound instance class - * @param {string} typeLocator - type locator - * @param identity - identity - * @param {Object} [data] - options - * @returns {StateTransition} + * @param {ExtendedDocument} document - document from the DAPI + * @param {Identifier} receiver - identifier of the document recipient ownership + * @param {Identifier} sender - identifier of the document owner */ export async function transfer( this: Platform, From ee75036e33cf075d7fc002aba279bb5bae527a04 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Wed, 25 Dec 2024 03:38:29 +0700 Subject: [PATCH 15/50] chore(wasm-dpp): cleanup --- packages/rs-dpp/src/document/document_factory/v0/mod.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/rs-dpp/src/document/document_factory/v0/mod.rs b/packages/rs-dpp/src/document/document_factory/v0/mod.rs index 6dc531398c7..58fc96de91a 100644 --- a/packages/rs-dpp/src/document/document_factory/v0/mod.rs +++ b/packages/rs-dpp/src/document/document_factory/v0/mod.rs @@ -32,7 +32,6 @@ use crate::state_transition::documents_batch_transition::{ DocumentsBatchTransition, DocumentsBatchTransitionV0, }; use itertools::Itertools; -use crate::state_transition::documents_batch_transition::document_transition::DocumentTransferTransition; const PROPERTY_FEATURE_VERSION: &str = "$version"; const PROPERTY_ENTROPY: &str = "$entropy"; From 63cf68ee49727ed2a76dd214ea068e30547c215f Mon Sep 17 00:00:00 2001 From: pshenmic Date: Mon, 20 Jan 2025 18:18:50 +0700 Subject: [PATCH 16/50] feat(wasm-dpp): add nft operations --- .../src/document/extended_document.rs | 56 ++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/packages/wasm-dpp/src/document/extended_document.rs b/packages/wasm-dpp/src/document/extended_document.rs index 52ff9f668f6..cb74431064b 100644 --- a/packages/wasm-dpp/src/document/extended_document.rs +++ b/packages/wasm-dpp/src/document/extended_document.rs @@ -14,8 +14,8 @@ use dpp::ProtocolError; use serde::{Deserialize, Serialize}; use std::convert::TryInto; use wasm_bindgen::prelude::*; -use dpp::state_transition::documents_batch_transition::document_transition::DocumentTransferTransition; use dpp::state_transition::documents_batch_transition::{DocumentsBatchTransition, DocumentsBatchTransitionV0}; +use dpp::state_transition::documents_batch_transition::document_transition::{DocumentPurchaseTransition, DocumentTransferTransition, DocumentUpdatePriceTransition}; use crate::buffer::Buffer; use crate::data_contract::DataContractWasm; @@ -261,6 +261,60 @@ impl ExtendedDocumentWasm { documents_batch_transition.into() } + #[wasm_bindgen(js_name=createUpdatePriceStateTransition)] + pub fn create_update_price_state_transition(&mut self, amount: u32, identity_contract_nonce: IdentityNonce) -> DocumentsBatchTransitionWasm { + let mut cloned_document = self.0.document().clone(); + + cloned_document.set_revision(Some(cloned_document.revision().unwrap() + 1)); + + let update_price_transition = DocumentUpdatePriceTransition::from_document( + cloned_document, + self.0.document_type().unwrap(), + amount as u64, + identity_contract_nonce, + PlatformVersion::latest(), + None, + None, + ).unwrap(); + + let documents_batch_transition: DocumentsBatchTransition = DocumentsBatchTransitionV0 { + owner_id: self.0.owner_id(), + transitions: vec![update_price_transition.into()], + user_fee_increase: Default::default(), + signature_public_key_id: Default::default(), + signature: Default::default(), + }.into(); + + documents_batch_transition.into() + } + + #[wasm_bindgen(js_name=createPurchaseStateTransition)] + pub fn create_update_purchase_transition(&mut self, buyer: IdentifierWrapper, amount: u32, identity_contract_nonce: IdentityNonce) -> DocumentsBatchTransitionWasm { + let mut cloned_document = self.0.document().clone(); + + cloned_document.set_revision(Some(cloned_document.revision().unwrap() + 1)); + + let purchase_transition = DocumentPurchaseTransition::from_document( + cloned_document, + self.0.document_type().unwrap(), + amount as u64, + identity_contract_nonce, + PlatformVersion::latest(), + None, + None, + ).unwrap(); + + let documents_batch_transition: DocumentsBatchTransition = DocumentsBatchTransitionV0 { + owner_id: buyer.into(), + transitions: vec![purchase_transition.into()], + user_fee_increase: Default::default(), + signature_public_key_id: Default::default(), + signature: Default::default(), + }.into(); + + documents_batch_transition.into() + } + #[wasm_bindgen(js_name=setUpdatedAt)] pub fn set_updated_at(&mut self, ts: Option) { self.0 From d14e2966a783fd0d20b6eadf1a5940911f48a79f Mon Sep 17 00:00:00 2001 From: pshenmic Date: Mon, 20 Jan 2025 18:19:47 +0700 Subject: [PATCH 17/50] feat(js-sdk): add transfer def in Platform.ts --- packages/js-dash-sdk/src/SDK/Client/Platform/Platform.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/Platform.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/Platform.ts index cd105ed87b7..7e72d2fa68e 100644 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/Platform.ts +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/Platform.ts @@ -10,6 +10,8 @@ import createAssetLockTransaction from './createAssetLockTransaction'; import broadcastDocument from './methods/documents/broadcast'; import createDocument from './methods/documents/create'; import transferDocument from './methods/documents/transfer'; +import updatePriceDocument from './methods/documents/updatePrice'; +import purchaseDocument from './methods/documents/purchase'; import getDocument from './methods/documents/get'; import publishContract from './methods/contracts/publish'; @@ -60,6 +62,8 @@ interface Records { broadcast: Function, create: Function, transfer: Function, + updatePrice: Function, + purchase: Function, get: Function, } @@ -168,6 +172,8 @@ export class Platform { broadcast: broadcastDocument.bind(this), create: createDocument.bind(this), transfer: transferDocument.bind(this), + updatePrice: updatePriceDocument.bind(this), + purchase: purchaseDocument.bind(this), get: getDocument.bind(this), }; this.contracts = { From 94b60a7d7825afd74a42f70c2532aafa91664e2b Mon Sep 17 00:00:00 2001 From: pshenmic Date: Sun, 26 Jan 2025 21:07:57 +0700 Subject: [PATCH 18/50] feat(js-dash-sdk): uncomment --- .../Platform/methods/documents/purchase.ts | 36 +++++++++++++++++++ .../Platform/methods/documents/updatePrice.ts | 33 +++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/purchase.ts create mode 100644 packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/updatePrice.ts diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/purchase.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/purchase.ts new file mode 100644 index 00000000000..e1c593ffed7 --- /dev/null +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/purchase.ts @@ -0,0 +1,36 @@ +import { Identity, ExtendedDocument } from '@dashevo/wasm-dpp'; +import { Platform } from '../../Platform'; +import broadcastStateTransition from '../../broadcastStateTransition'; +import { signStateTransition } from '../../signStateTransition'; +/** + * Transfer document in the platform + * + * @param {Platform} this - bound instance class + * @param {ExtendedDocument} document - document from the DAPI + * @param {Identifier} receiver - identifier of the document recipient ownership + * @param {Identifier} sender - identifier of the document owner + */ +export async function purchase( + this: Platform, + document: ExtendedDocument, + amount: number, + buyer: Identity, + seller: Identity, +): Promise { + this.logger.debug(`[Document#transfer] Update price for document ${document.getId().toString()} to ${amount}`); + await this.initialize(); + + const identityContractNonce = await this.nonceManager + .bumpIdentityContractNonce(buyer.getId(), document.getDataContractId()); + + const documentsBatchTransition = document + .createPurchaseStateTransition(buyer.getId(), amount, BigInt(identityContractNonce)); + + await signStateTransition(this, documentsBatchTransition, buyer, 1); + + console.log(documentsBatchTransition.toBuffer().toString('hex')); + + await broadcastStateTransition(this, documentsBatchTransition); +} + +export default purchase; diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/updatePrice.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/updatePrice.ts new file mode 100644 index 00000000000..1216bc98bf6 --- /dev/null +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/updatePrice.ts @@ -0,0 +1,33 @@ +import { Identity, ExtendedDocument } from '@dashevo/wasm-dpp'; +import { Platform } from '../../Platform'; +import broadcastStateTransition from '../../broadcastStateTransition'; +import { signStateTransition } from '../../signStateTransition'; +/** + * Transfer document in the platform + * + * @param {Platform} this - bound instance class + * @param {ExtendedDocument} document - document from the DAPI + * @param {Identifier} receiver - identifier of the document recipient ownership + * @param {Identifier} sender - identifier of the document owner + */ +export async function updatePrice( + this: Platform, + document: ExtendedDocument, + amount: number, + identity: Identity, +): Promise { + this.logger.debug(`[Document#transfer] Update price for document ${document.getId().toString()} to ${amount}`); + await this.initialize(); + + const identityContractNonce = await this.nonceManager + .bumpIdentityContractNonce(identity.getId(), document.getDataContractId()); + + const documentsBatchTransition = document + .createUpdatePriceStateTransition(amount, BigInt(identityContractNonce)); + + await signStateTransition(this, documentsBatchTransition, identity, 1); + + await broadcastStateTransition(this, documentsBatchTransition); +} + +export default updatePrice; From b4181bed221baadad40e7015bdf58f87c1c7b1a6 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Thu, 30 Jan 2025 15:26:37 +0700 Subject: [PATCH 19/50] feat(wasm-dpp): move nft create state transition from extended document to factory --- .../src/document/document_factory/mod.rs | 5 +- .../src/document/document_factory/v0/mod.rs | 150 +++++++++++++++++- packages/rs-dpp/src/document/errors.rs | 3 + .../wasm-dpp/src/document/document_facade.rs | 8 +- packages/wasm-dpp/src/document/errors/mod.rs | 5 + ...transfer_nontransferable_document_error.rs | 19 +++ .../src/document/extended_document.rs | 81 ---------- packages/wasm-dpp/src/document/factory.rs | 21 ++- 8 files changed, 201 insertions(+), 91 deletions(-) create mode 100644 packages/wasm-dpp/src/document/errors/trying_to_transfer_nontransferable_document_error.rs diff --git a/packages/rs-dpp/src/document/document_factory/mod.rs b/packages/rs-dpp/src/document/document_factory/mod.rs index 75db720fd59..8245a079f3c 100644 --- a/packages/rs-dpp/src/document/document_factory/mod.rs +++ b/packages/rs-dpp/src/document/document_factory/mod.rs @@ -18,6 +18,7 @@ use crate::state_transition::documents_batch_transition::{ }; use crate::util::entropy_generator::EntropyGenerator; pub use v0::DocumentFactoryV0; +use crate::fee::Credits; /// # Document Factory /// @@ -120,9 +121,11 @@ impl DocumentFactory { ), >, nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce + recipient: Option, + price: Option, ) -> Result { match self { - DocumentFactory::V0(v0) => v0.create_state_transition(documents_iter, nonce_counter), + DocumentFactory::V0(v0) => v0.create_state_transition(documents_iter, nonce_counter, recipient, price), } } diff --git a/packages/rs-dpp/src/document/document_factory/v0/mod.rs b/packages/rs-dpp/src/document/document_factory/v0/mod.rs index 58fc96de91a..38ae3d73433 100644 --- a/packages/rs-dpp/src/document/document_factory/v0/mod.rs +++ b/packages/rs-dpp/src/document/document_factory/v0/mod.rs @@ -32,6 +32,8 @@ use crate::state_transition::documents_batch_transition::{ DocumentsBatchTransition, DocumentsBatchTransitionV0, }; use itertools::Itertools; +use crate::fee::Credits; +use crate::state_transition::documents_batch_transition::document_transition::{DocumentPurchaseTransition, DocumentTransferTransition, DocumentUpdatePriceTransition}; const PROPERTY_FEATURE_VERSION: &str = "$version"; const PROPERTY_ENTROPY: &str = "$entropy"; @@ -209,7 +211,9 @@ impl DocumentFactoryV0 { Vec<(Document, DocumentTypeRef<'a>, Bytes32)>, ), >, - nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce + nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce, + recipient: Option, + price: Option ) -> Result { let platform_version = PlatformVersion::get(self.protocol_version)?; let documents: Vec<( @@ -262,6 +266,33 @@ impl DocumentFactoryV0 { nonce_counter, platform_version, ), + DocumentTransitionActionType::Transfer => Self::document_transfer_transitions( + documents + .into_iter() + .map(|(document, document_type, _)| (document, document_type)) + .collect(), + nonce_counter, + platform_version, + recipient.unwrap() + ), + DocumentTransitionActionType::UpdatePrice => Self::document_update_price_transitions( + documents + .into_iter() + .map(|(document, document_type, _)| (document, document_type)) + .collect(), + nonce_counter, + platform_version, + price.unwrap() + ), + DocumentTransitionActionType::Purchase => Self::document_purchase_transitions( + documents + .into_iter() + .map(|(document, document_type, _)| (document, document_type)) + .collect(), + nonce_counter, + platform_version, + price.unwrap() + ), _ => Err(ProtocolError::InvalidStateTransitionType( "action type not accounted for".to_string(), )), @@ -548,6 +579,123 @@ impl DocumentFactoryV0 { .collect() } + #[cfg(feature = "state-transitions")] + fn document_transfer_transitions( + documents: Vec<(Document, DocumentTypeRef)>, + nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce + platform_version: &PlatformVersion, + recipient_owner_id: Identifier + ) -> Result, ProtocolError> { + documents + .into_iter() + .map(|(document, document_type)| { + if !document_type.documents_transferable().is_transferable() { + return Err(DocumentError::TryingToTransferNonTransferableDocument { + document: Box::new(document), + } + .into()); + } + let Some(_document_revision) = document.revision() else { + return Err(DocumentError::RevisionAbsentError { + document: Box::new(document), + } + .into()); + }; + + let nonce = nonce_counter + .entry((document.owner_id(), document_type.data_contract_id())) + .or_default(); + let transition = DocumentTransferTransition::from_document( + document, + document_type, + *nonce, + recipient_owner_id, + platform_version, + None, + None, + )?; + + *nonce += 1; + + Ok(transition.into()) + }) + .collect() + } + + #[cfg(feature = "state-transitions")] + fn document_update_price_transitions( + documents: Vec<(Document, DocumentTypeRef)>, + nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce + platform_version: &PlatformVersion, + price: Credits + ) -> Result, ProtocolError> { + documents + .into_iter() + .map(|(document, document_type)| { + let Some(_document_revision) = document.revision() else { + return Err(DocumentError::RevisionAbsentError { + document: Box::new(document), + } + .into()); + }; + + let nonce = nonce_counter + .entry((document.owner_id(), document_type.data_contract_id())) + .or_default(); + let transition = DocumentUpdatePriceTransition::from_document( + document, + document_type, + price, + *nonce, + platform_version, + None, + None, + )?; + + *nonce += 1; + + Ok(transition.into()) + }) + .collect() + } + + #[cfg(feature = "state-transitions")] + fn document_purchase_transitions( + documents: Vec<(Document, DocumentTypeRef)>, + nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce + platform_version: &PlatformVersion, + price: Credits + ) -> Result, ProtocolError> { + documents + .into_iter() + .map(|(document, document_type)| { + let Some(_document_revision) = document.revision() else { + return Err(DocumentError::RevisionAbsentError { + document: Box::new(document), + } + .into()); + }; + + let nonce = nonce_counter + .entry((document.owner_id(), document_type.data_contract_id())) + .or_default(); + let transition = DocumentPurchaseTransition::from_document( + document, + document_type, + price, + *nonce, + platform_version, + None, + None, + )?; + + *nonce += 1; + + Ok(transition.into()) + }) + .collect() + } + fn is_ownership_the_same<'a>(ids: impl IntoIterator) -> bool { ids.into_iter().all_equal() } diff --git a/packages/rs-dpp/src/document/errors.rs b/packages/rs-dpp/src/document/errors.rs index d16ca16f1ea..e053bf88605 100644 --- a/packages/rs-dpp/src/document/errors.rs +++ b/packages/rs-dpp/src/document/errors.rs @@ -47,6 +47,9 @@ pub enum DocumentError { #[error("Trying to delete indelible document")] TryingToDeleteIndelibleDocument { document: Box }, + #[error("Trying to transfer non-transferable document")] + TryingToTransferNonTransferableDocument { document: Box }, + #[error("Documents have mixed owner ids")] MismatchOwnerIdsError { documents: Vec }, diff --git a/packages/wasm-dpp/src/document/document_facade.rs b/packages/wasm-dpp/src/document/document_facade.rs index 517bb262c3f..de9acc454d6 100644 --- a/packages/wasm-dpp/src/document/document_facade.rs +++ b/packages/wasm-dpp/src/document/document_facade.rs @@ -1,10 +1,12 @@ use std::rc::Rc; use wasm_bindgen::{prelude::*, JsValue}; - +use dpp::fee::Credits; +use dpp::identifier::Identifier; use crate::document::factory::DocumentFactoryWASM; use crate::{DataContractWasm, ExtendedDocumentWasm}; use crate::document::state_transition::document_batch_transition::DocumentsBatchTransitionWasm; +use crate::identifier::IdentifierWrapper; #[derive(Clone)] #[wasm_bindgen(js_name=DocumentFacade)] @@ -96,9 +98,11 @@ impl DocumentFacadeWasm { &self, documents: &JsValue, nonce_counter_value: &js_sys::Object, //IdentityID/ContractID -> nonce (BigInt) + recipient: Option, + price: Option ) -> Result { self.factory - .create_state_transition(documents, nonce_counter_value) + .create_state_transition(documents, nonce_counter_value, recipient, price) } // /// Creates Documents State Transition diff --git a/packages/wasm-dpp/src/document/errors/mod.rs b/packages/wasm-dpp/src/document/errors/mod.rs index 7b90ac63dbd..f900fde35d1 100644 --- a/packages/wasm-dpp/src/document/errors/mod.rs +++ b/packages/wasm-dpp/src/document/errors/mod.rs @@ -6,6 +6,7 @@ use crate::document::errors::invalid_action_error::InvalidActionError; use crate::document::errors::revision_absent_error::RevisionAbsentError; use crate::document::errors::trying_to_delete_immutable_document_error::TryingToDeleteImmutableDocumentError; use crate::document::errors::trying_to_replace_immutable_document_error::TryingToReplaceImmutableDocumentError; +use crate::document::errors::trying_to_transfer_nontransferable_document_error::TryingToTransferNonTransferableDocumentError; pub use document_already_exists_error::*; pub use document_not_provided_error::*; use dpp::document::errors::DocumentError; @@ -32,6 +33,7 @@ mod no_documents_supplied_error; mod revision_absent_error; mod trying_to_delete_immutable_document_error; mod trying_to_replace_immutable_document_error; +mod trying_to_transfer_nontransferable_document_error; pub fn from_document_to_js_error(e: DocumentError) -> JsValue { match e { @@ -77,6 +79,9 @@ pub fn from_document_to_js_error(e: DocumentError) -> JsValue { DocumentError::InvalidActionError(action) => InvalidActionError::new(action.into()).into(), DocumentError::TryingToDeleteIndelibleDocument { document } => { TryingToDeleteImmutableDocumentError::new((*document).into()).into() + }, + DocumentError::TryingToTransferNonTransferableDocument { document } => { + TryingToTransferNonTransferableDocumentError::new((*document).into()).into() } } } diff --git a/packages/wasm-dpp/src/document/errors/trying_to_transfer_nontransferable_document_error.rs b/packages/wasm-dpp/src/document/errors/trying_to_transfer_nontransferable_document_error.rs new file mode 100644 index 00000000000..60ff00f03d4 --- /dev/null +++ b/packages/wasm-dpp/src/document/errors/trying_to_transfer_nontransferable_document_error.rs @@ -0,0 +1,19 @@ +use crate::document::DocumentWasm; +use thiserror::Error; + +use super::*; + +#[wasm_bindgen] +#[derive(Error, Debug)] +#[error("Trying to transfer an non transferable document")] +pub struct TryingToTransferNonTransferableDocumentError { + document: DocumentWasm, +} + +#[wasm_bindgen] +impl TryingToTransferNonTransferableDocumentError { + #[wasm_bindgen(constructor)] + pub fn new(document: DocumentWasm) -> Self { + TryingToTransferNonTransferableDocumentError { document } + } +} diff --git a/packages/wasm-dpp/src/document/extended_document.rs b/packages/wasm-dpp/src/document/extended_document.rs index cb74431064b..de4f8d98337 100644 --- a/packages/wasm-dpp/src/document/extended_document.rs +++ b/packages/wasm-dpp/src/document/extended_document.rs @@ -234,87 +234,6 @@ impl ExtendedDocumentWasm { .set_created_at(ts.map(|t| t.get_time() as TimestampMillis)); } - #[wasm_bindgen(js_name=createTransferStateTransition)] - pub fn create_transfer_state_transition(&mut self, recipient: IdentifierWrapper, identity_contract_nonce: IdentityNonce) -> DocumentsBatchTransitionWasm { - let mut cloned_document = self.0.document().clone(); - - cloned_document.set_revision(Some(cloned_document.revision().unwrap() + 1)); - - let transfer_transition = DocumentTransferTransition::from_document( - cloned_document, - self.0.document_type().unwrap(), - identity_contract_nonce, - recipient.into(), - PlatformVersion::latest(), - None, - None, - ).unwrap(); - - let documents_batch_transition: DocumentsBatchTransition = DocumentsBatchTransitionV0 { - owner_id: self.0.owner_id(), - transitions: vec![transfer_transition.into()], - user_fee_increase: Default::default(), - signature_public_key_id: Default::default(), - signature: Default::default(), - }.into(); - - documents_batch_transition.into() - } - - #[wasm_bindgen(js_name=createUpdatePriceStateTransition)] - pub fn create_update_price_state_transition(&mut self, amount: u32, identity_contract_nonce: IdentityNonce) -> DocumentsBatchTransitionWasm { - let mut cloned_document = self.0.document().clone(); - - cloned_document.set_revision(Some(cloned_document.revision().unwrap() + 1)); - - let update_price_transition = DocumentUpdatePriceTransition::from_document( - cloned_document, - self.0.document_type().unwrap(), - amount as u64, - identity_contract_nonce, - PlatformVersion::latest(), - None, - None, - ).unwrap(); - - let documents_batch_transition: DocumentsBatchTransition = DocumentsBatchTransitionV0 { - owner_id: self.0.owner_id(), - transitions: vec![update_price_transition.into()], - user_fee_increase: Default::default(), - signature_public_key_id: Default::default(), - signature: Default::default(), - }.into(); - - documents_batch_transition.into() - } - - #[wasm_bindgen(js_name=createPurchaseStateTransition)] - pub fn create_update_purchase_transition(&mut self, buyer: IdentifierWrapper, amount: u32, identity_contract_nonce: IdentityNonce) -> DocumentsBatchTransitionWasm { - let mut cloned_document = self.0.document().clone(); - - cloned_document.set_revision(Some(cloned_document.revision().unwrap() + 1)); - - let purchase_transition = DocumentPurchaseTransition::from_document( - cloned_document, - self.0.document_type().unwrap(), - amount as u64, - identity_contract_nonce, - PlatformVersion::latest(), - None, - None, - ).unwrap(); - - let documents_batch_transition: DocumentsBatchTransition = DocumentsBatchTransitionV0 { - owner_id: buyer.into(), - transitions: vec![purchase_transition.into()], - user_fee_increase: Default::default(), - signature_public_key_id: Default::default(), - signature: Default::default(), - }.into(); - - documents_batch_transition.into() - } - #[wasm_bindgen(js_name=setUpdatedAt)] pub fn set_updated_at(&mut self, ts: Option) { self.0 diff --git a/packages/wasm-dpp/src/document/factory.rs b/packages/wasm-dpp/src/document/factory.rs index a62dbc3aeca..7e592cb0380 100644 --- a/packages/wasm-dpp/src/document/factory.rs +++ b/packages/wasm-dpp/src/document/factory.rs @@ -13,6 +13,11 @@ use dpp::document::Document; use dpp::prelude::ExtendedDocument; +use dpp::identifier::Identifier; +use dpp::state_transition::documents_batch_transition::document_transition::action_type::DocumentTransitionActionType; +use dpp::version::PlatformVersion; +use std::convert::TryFrom; +use dpp::fee::Credits; use crate::document_batch_transition::DocumentsBatchTransitionWasm; use crate::entropy_generator::ExternalEntropyGenerator; use crate::{ @@ -20,11 +25,7 @@ use crate::{ utils::{IntoWasm, ToSerdeJSONExt, WithJsError}, DataContractWasm, ExtendedDocumentWasm, }; -use dpp::identifier::Identifier; -use dpp::state_transition::documents_batch_transition::document_transition::action_type::DocumentTransitionActionType; -use dpp::version::PlatformVersion; -use std::convert::TryFrom; -use std::str::FromStr; +use crate::identifier::IdentifierWrapper; #[wasm_bindgen(js_name=DocumentTransitions)] #[derive(Debug, Default)] @@ -109,6 +110,8 @@ impl DocumentFactoryWASM { &self, documents: &JsValue, nonce_counter_value: &js_sys::Object, //IdentityID/ContractID -> nonce + recipient: Option, + price: Option ) -> Result { let mut nonce_counter = BTreeMap::new(); let mut contract_ids_to_check = HashSet::<&Identifier>::new(); @@ -181,7 +184,7 @@ impl DocumentFactoryWASM { let batch_transition = self .0 - .create_state_transition(documents, &mut nonce_counter) + .create_state_transition(documents, &mut nonce_counter, recipient.map(|e| { Identifier::from(e)}), price) .with_js_error()?; Ok(batch_transition.into()) @@ -283,10 +286,16 @@ fn extract_documents_by_action( let documents_create = extract_documents_of_action(documents, "create").with_js_error()?; let documents_replace = extract_documents_of_action(documents, "replace").with_js_error()?; let documents_delete = extract_documents_of_action(documents, "delete").with_js_error()?; + let documents_transfer = extract_documents_of_action(documents, "transfer").with_js_error()?; + let documents_update_price = extract_documents_of_action(documents, "updatePrice").with_js_error()?; + let documents_purchase = extract_documents_of_action(documents, "purchase").with_js_error()?; documents_by_action.insert(DocumentTransitionActionType::Create, documents_create); documents_by_action.insert(DocumentTransitionActionType::Replace, documents_replace); documents_by_action.insert(DocumentTransitionActionType::Delete, documents_delete); + documents_by_action.insert(DocumentTransitionActionType::Transfer, documents_transfer); + documents_by_action.insert(DocumentTransitionActionType::UpdatePrice, documents_update_price); + documents_by_action.insert(DocumentTransitionActionType::Purchase, documents_purchase); Ok(documents_by_action) } From f195f8735525d04fa25b6751e8f4f70095b5fb16 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Thu, 30 Jan 2025 20:11:32 +0700 Subject: [PATCH 20/50] fix(js-dash-sdk): fix types --- .../src/SDK/Client/Platform/Platform.ts | 9 ----- .../Platform/methods/documents/broadcast.ts | 14 ++++++-- .../Platform/methods/documents/purchase.ts | 36 ------------------- .../Platform/methods/documents/transfer.ts | 33 ----------------- .../Platform/methods/documents/updatePrice.ts | 33 ----------------- 5 files changed, 12 insertions(+), 113 deletions(-) delete mode 100644 packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/purchase.ts delete mode 100644 packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts delete mode 100644 packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/updatePrice.ts diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/Platform.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/Platform.ts index 7e72d2fa68e..873fe62c53d 100644 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/Platform.ts +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/Platform.ts @@ -9,9 +9,6 @@ import createAssetLockTransaction from './createAssetLockTransaction'; import broadcastDocument from './methods/documents/broadcast'; import createDocument from './methods/documents/create'; -import transferDocument from './methods/documents/transfer'; -import updatePriceDocument from './methods/documents/updatePrice'; -import purchaseDocument from './methods/documents/purchase'; import getDocument from './methods/documents/get'; import publishContract from './methods/contracts/publish'; @@ -61,9 +58,6 @@ export interface PlatformOpts { interface Records { broadcast: Function, create: Function, - transfer: Function, - updatePrice: Function, - purchase: Function, get: Function, } @@ -171,9 +165,6 @@ export class Platform { this.documents = { broadcast: broadcastDocument.bind(this), create: createDocument.bind(this), - transfer: transferDocument.bind(this), - updatePrice: updatePriceDocument.bind(this), - purchase: purchaseDocument.bind(this), get: getDocument.bind(this), }; this.contracts = { diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts index 4a6a7a06026..58a207ec863 100644 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts @@ -18,14 +18,18 @@ export default async function broadcast( documents: { create?: ExtendedDocument[], replace?: ExtendedDocument[], - delete?: ExtendedDocument[] + delete?: ExtendedDocument[], + transfer?: ExtendedDocument[] }, identity: any, + options: any, ): Promise { + console.log(documents) this.logger.debug('[Document#broadcast] Broadcast documents', { create: documents.create?.length || 0, replace: documents.replace?.length || 0, delete: documents.delete?.length || 0, + transfer: documents.transfer?.length || 0, }); await this.initialize(); @@ -36,12 +40,17 @@ export default async function broadcast( ...(documents.create || []), ...(documents.replace || []), ...(documents.delete || []), + ...(documents.transfer || []), ][0]?.getDataContractId(); if (!dataContractId) { throw new Error('Data contract ID is not found'); } + if (documents.transfer?.length && !options.recipient) { + throw new Error('Receiver identity is not found for transfer transition'); + } + const identityContractNonce = await this.nonceManager .bumpIdentityContractNonce(identityId, dataContractId); @@ -49,7 +58,7 @@ export default async function broadcast( [identityId.toString()]: { [dataContractId.toString()]: identityContractNonce.toString(), }, - }); + }, options.recipient, options.price); this.logger.silly('[Document#broadcast] Created documents batch transition'); @@ -79,6 +88,7 @@ export default async function broadcast( create: documents.create?.length || 0, replace: documents.replace?.length || 0, delete: documents.delete?.length || 0, + transfer: documents.transfer?.length || 0, }); return documentsBatchTransition; diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/purchase.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/purchase.ts deleted file mode 100644 index e1c593ffed7..00000000000 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/purchase.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { Identity, ExtendedDocument } from '@dashevo/wasm-dpp'; -import { Platform } from '../../Platform'; -import broadcastStateTransition from '../../broadcastStateTransition'; -import { signStateTransition } from '../../signStateTransition'; -/** - * Transfer document in the platform - * - * @param {Platform} this - bound instance class - * @param {ExtendedDocument} document - document from the DAPI - * @param {Identifier} receiver - identifier of the document recipient ownership - * @param {Identifier} sender - identifier of the document owner - */ -export async function purchase( - this: Platform, - document: ExtendedDocument, - amount: number, - buyer: Identity, - seller: Identity, -): Promise { - this.logger.debug(`[Document#transfer] Update price for document ${document.getId().toString()} to ${amount}`); - await this.initialize(); - - const identityContractNonce = await this.nonceManager - .bumpIdentityContractNonce(buyer.getId(), document.getDataContractId()); - - const documentsBatchTransition = document - .createPurchaseStateTransition(buyer.getId(), amount, BigInt(identityContractNonce)); - - await signStateTransition(this, documentsBatchTransition, buyer, 1); - - console.log(documentsBatchTransition.toBuffer().toString('hex')); - - await broadcastStateTransition(this, documentsBatchTransition); -} - -export default purchase; diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts deleted file mode 100644 index e211364b27b..00000000000 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/transfer.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { Identity, ExtendedDocument } from '@dashevo/wasm-dpp'; -import { Platform } from '../../Platform'; -import broadcastStateTransition from '../../broadcastStateTransition'; -import { signStateTransition } from '../../signStateTransition'; -/** - * Transfer document in the platform - * - * @param {Platform} this - bound instance class - * @param {ExtendedDocument} document - document from the DAPI - * @param {Identifier} receiver - identifier of the document recipient ownership - * @param {Identifier} sender - identifier of the document owner - */ -export async function transfer( - this: Platform, - document: ExtendedDocument, - receiver: Identity, - sender: Identity, -): Promise { - this.logger.debug(`[Document#transfer] Transfer document ${document.getId().toString()} from ${sender.getId().toString} to {${receiver.getId().toString()}`); - await this.initialize(); - - const identityContractNonce = await this.nonceManager - .bumpIdentityContractNonce(sender.getId(), document.getDataContractId()); - - const documentsBatchTransition = document - .createTransferStateTransition(receiver.getId(), BigInt(identityContractNonce)); - - await signStateTransition(this, documentsBatchTransition, sender, 1); - - await broadcastStateTransition(this, documentsBatchTransition); -} - -export default transfer; diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/updatePrice.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/updatePrice.ts deleted file mode 100644 index 1216bc98bf6..00000000000 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/updatePrice.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { Identity, ExtendedDocument } from '@dashevo/wasm-dpp'; -import { Platform } from '../../Platform'; -import broadcastStateTransition from '../../broadcastStateTransition'; -import { signStateTransition } from '../../signStateTransition'; -/** - * Transfer document in the platform - * - * @param {Platform} this - bound instance class - * @param {ExtendedDocument} document - document from the DAPI - * @param {Identifier} receiver - identifier of the document recipient ownership - * @param {Identifier} sender - identifier of the document owner - */ -export async function updatePrice( - this: Platform, - document: ExtendedDocument, - amount: number, - identity: Identity, -): Promise { - this.logger.debug(`[Document#transfer] Update price for document ${document.getId().toString()} to ${amount}`); - await this.initialize(); - - const identityContractNonce = await this.nonceManager - .bumpIdentityContractNonce(identity.getId(), document.getDataContractId()); - - const documentsBatchTransition = document - .createUpdatePriceStateTransition(amount, BigInt(identityContractNonce)); - - await signStateTransition(this, documentsBatchTransition, identity, 1); - - await broadcastStateTransition(this, documentsBatchTransition); -} - -export default updatePrice; From a7046291c7975f1f967ae753da7cd8bb527706ec Mon Sep 17 00:00:00 2001 From: pshenmic Date: Fri, 31 Jan 2025 18:06:00 +0700 Subject: [PATCH 21/50] fix(js-dash-sdk): finalize nft transitions --- .../Platform/methods/documents/broadcast.ts | 48 +++++++++++++---- .../src/document/document_factory/v0/mod.rs | 53 +++++++++++++------ .../document_transition/action_type.rs | 17 +++++- 3 files changed, 92 insertions(+), 26 deletions(-) diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts index 58a207ec863..96538401266 100644 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts @@ -1,17 +1,23 @@ -import { ExtendedDocument } from '@dashevo/wasm-dpp'; +import { ExtendedDocument, Identifier } from '@dashevo/wasm-dpp'; import { Platform } from '../../Platform'; import broadcastStateTransition from '../../broadcastStateTransition'; import { signStateTransition } from '../../signStateTransition'; +class DocumentTransitionParams { + receiver?: Identifier; + + price?: bigint; +} + /** * Broadcast document onto the platform * - * @param {Platform} this - bound instance class * @param {Object} documents * @param {ExtendedDocument[]} [documents.create] * @param {ExtendedDocument[]} [documents.replace] * @param {ExtendedDocument[]} [documents.delete] - * @param identity - identity + * @param {Identity} identity + * @param options {DocumentTransitionParams} optional params for NFT functions */ export default async function broadcast( this: Platform, @@ -19,17 +25,20 @@ export default async function broadcast( create?: ExtendedDocument[], replace?: ExtendedDocument[], delete?: ExtendedDocument[], - transfer?: ExtendedDocument[] + transfer?: ExtendedDocument[], + updatePrice?: ExtendedDocument[], + purchase?: ExtendedDocument[], }, identity: any, - options: any, + options?: DocumentTransitionParams, ): Promise { - console.log(documents) this.logger.debug('[Document#broadcast] Broadcast documents', { create: documents.create?.length || 0, replace: documents.replace?.length || 0, delete: documents.delete?.length || 0, transfer: documents.transfer?.length || 0, + updatePrice: documents.updatePrice?.length || 0, + purchase: documents.purchase?.length || 0, }); await this.initialize(); @@ -41,24 +50,45 @@ export default async function broadcast( ...(documents.replace || []), ...(documents.delete || []), ...(documents.transfer || []), + ...(documents.updatePrice || []), + ...(documents.purchase || []), ][0]?.getDataContractId(); if (!dataContractId) { throw new Error('Data contract ID is not found'); } - if (documents.transfer?.length && !options.recipient) { + if (documents.transfer?.length && !options?.receiver) { throw new Error('Receiver identity is not found for transfer transition'); } + if (documents.updatePrice?.length && !options?.price) { + throw new Error('Price must be provided for UpdatePrice operation'); + } + + if (documents.purchase?.length) { + if (!options?.price && !options?.receiver) { + throw new Error('Price and Receiver must be provided for Purchase operation'); + } + + documents.purchase.forEach((document) => document.setOwnerId(options.receiver)); + } + const identityContractNonce = await this.nonceManager .bumpIdentityContractNonce(identityId, dataContractId); - const documentsBatchTransition = dpp.document.createStateTransition(documents, { + const identityNonceObj = { [identityId.toString()]: { [dataContractId.toString()]: identityContractNonce.toString(), }, - }, options.recipient, options.price); + }; + + const documentsBatchTransition = dpp.document.createStateTransition( + documents, + identityNonceObj, + options?.receiver, + options?.price, + ); this.logger.silly('[Document#broadcast] Created documents batch transition'); diff --git a/packages/rs-dpp/src/document/document_factory/v0/mod.rs b/packages/rs-dpp/src/document/document_factory/v0/mod.rs index 38ae3d73433..36ed8e1e480 100644 --- a/packages/rs-dpp/src/document/document_factory/v0/mod.rs +++ b/packages/rs-dpp/src/document/document_factory/v0/mod.rs @@ -273,7 +273,7 @@ impl DocumentFactoryV0 { .collect(), nonce_counter, platform_version, - recipient.unwrap() + recipient ), DocumentTransitionActionType::UpdatePrice => Self::document_update_price_transitions( documents @@ -282,7 +282,7 @@ impl DocumentFactoryV0 { .collect(), nonce_counter, platform_version, - price.unwrap() + price ), DocumentTransitionActionType::Purchase => Self::document_purchase_transitions( documents @@ -291,11 +291,15 @@ impl DocumentFactoryV0 { .collect(), nonce_counter, platform_version, - price.unwrap() + price, + recipient ), - _ => Err(ProtocolError::InvalidStateTransitionType( - "action type not accounted for".to_string(), - )), + _ => { + let action_type_name: &str = action.into(); + + Err(ProtocolError::InvalidStateTransitionType( + action_type_name.to_string(), + ))}, }) .collect::, ProtocolError>>()? .into_iter() @@ -584,11 +588,11 @@ impl DocumentFactoryV0 { documents: Vec<(Document, DocumentTypeRef)>, nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce platform_version: &PlatformVersion, - recipient_owner_id: Identifier + recipient_owner_id: Option ) -> Result, ProtocolError> { documents .into_iter() - .map(|(document, document_type)| { + .map(|(mut document, document_type)| { if !document_type.documents_transferable().is_transferable() { return Err(DocumentError::TryingToTransferNonTransferableDocument { document: Box::new(document), @@ -602,14 +606,18 @@ impl DocumentFactoryV0 { .into()); }; + document.increment_revision()?; + document.set_updated_at(Some(Utc::now().timestamp_millis() as TimestampMillis)); + let nonce = nonce_counter .entry((document.owner_id(), document_type.data_contract_id())) .or_default(); + let transition = DocumentTransferTransition::from_document( document, document_type, *nonce, - recipient_owner_id, + recipient_owner_id.unwrap(), platform_version, None, None, @@ -627,11 +635,11 @@ impl DocumentFactoryV0 { documents: Vec<(Document, DocumentTypeRef)>, nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce platform_version: &PlatformVersion, - price: Credits + price: Option ) -> Result, ProtocolError> { documents .into_iter() - .map(|(document, document_type)| { + .map(|(mut document, document_type)| { let Some(_document_revision) = document.revision() else { return Err(DocumentError::RevisionAbsentError { document: Box::new(document), @@ -642,10 +650,17 @@ impl DocumentFactoryV0 { let nonce = nonce_counter .entry((document.owner_id(), document_type.data_contract_id())) .or_default(); + + let now = Utc::now().timestamp_millis() as TimestampMillis; + + document.increment_revision()?; + document.set_updated_at(Some(now)); + document.set_transferred_at(Some(now)); + let transition = DocumentUpdatePriceTransition::from_document( document, document_type, - price, + price.unwrap(), *nonce, platform_version, None, @@ -664,11 +679,12 @@ impl DocumentFactoryV0 { documents: Vec<(Document, DocumentTypeRef)>, nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce platform_version: &PlatformVersion, - price: Credits + price: Option, + recipient: Option ) -> Result, ProtocolError> { documents .into_iter() - .map(|(document, document_type)| { + .map(|(mut document, document_type)| { let Some(_document_revision) = document.revision() else { return Err(DocumentError::RevisionAbsentError { document: Box::new(document), @@ -677,12 +693,17 @@ impl DocumentFactoryV0 { }; let nonce = nonce_counter - .entry((document.owner_id(), document_type.data_contract_id())) + .entry((recipient.unwrap(), document_type.data_contract_id())) .or_default(); + + //document.set_owner_id(recipient.unwrap()); + document.increment_revision()?; + document.set_updated_at(Some(Utc::now().timestamp_millis() as TimestampMillis)); + let transition = DocumentPurchaseTransition::from_document( document, document_type, - price, + price.unwrap(), *nonce, platform_version, None, diff --git a/packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/action_type.rs b/packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/action_type.rs index 4b61c44fe55..fb4cf51ccf1 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/action_type.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/action_type.rs @@ -39,11 +39,26 @@ impl TryFrom<&str> for DocumentTransitionActionType { "replace" => Ok(DocumentTransitionActionType::Replace), "delete" => Ok(DocumentTransitionActionType::Delete), "transfer" => Ok(DocumentTransitionActionType::Transfer), - "purchase" => Ok(DocumentTransitionActionType::Purchase), "updatePrice" => Ok(DocumentTransitionActionType::UpdatePrice), + "purchase" => Ok(DocumentTransitionActionType::Purchase), action_type => Err(ProtocolError::Generic(format!( "unknown action type {action_type}" ))), } } } + + +impl From for &str { + fn from(value: DocumentTransitionActionType) -> Self { + match value { + DocumentTransitionActionType::Create => "Create", + DocumentTransitionActionType::Replace => "Replace", + DocumentTransitionActionType::Delete => "Delete", + DocumentTransitionActionType::Transfer => "Transfer", + DocumentTransitionActionType::Purchase => "Purchase", + DocumentTransitionActionType::UpdatePrice => "UpdatePrice", + DocumentTransitionActionType::IgnoreWhileBumpingRevision => "IgnoreWhileBumpingRevision" + } + } +} From 03204f3aaf4e00f2c7083dd8879b787163098249 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Fri, 31 Jan 2025 18:18:52 +0700 Subject: [PATCH 22/50] fix(wasm-dpp): lint fix --- .../src/document/document_factory/mod.rs | 6 ++- .../src/document/document_factory/v0/mod.rs | 41 +++++++++++-------- .../document_transition/action_type.rs | 5 ++- .../get_document_transitions_fixture.rs | 2 +- 4 files changed, 31 insertions(+), 23 deletions(-) diff --git a/packages/rs-dpp/src/document/document_factory/mod.rs b/packages/rs-dpp/src/document/document_factory/mod.rs index 8245a079f3c..b8aa2f56e9b 100644 --- a/packages/rs-dpp/src/document/document_factory/mod.rs +++ b/packages/rs-dpp/src/document/document_factory/mod.rs @@ -12,13 +12,13 @@ use crate::data_contract::document_type::DocumentTypeRef; use crate::document::Document; #[cfg(feature = "extended-document")] use crate::document::ExtendedDocument; +use crate::fee::Credits; #[cfg(feature = "state-transitions")] use crate::state_transition::documents_batch_transition::{ document_transition::action_type::DocumentTransitionActionType, DocumentsBatchTransition, }; use crate::util::entropy_generator::EntropyGenerator; pub use v0::DocumentFactoryV0; -use crate::fee::Credits; /// # Document Factory /// @@ -125,7 +125,9 @@ impl DocumentFactory { price: Option, ) -> Result { match self { - DocumentFactory::V0(v0) => v0.create_state_transition(documents_iter, nonce_counter, recipient, price), + DocumentFactory::V0(v0) => { + v0.create_state_transition(documents_iter, nonce_counter, recipient, price) + } } } diff --git a/packages/rs-dpp/src/document/document_factory/v0/mod.rs b/packages/rs-dpp/src/document/document_factory/v0/mod.rs index 36ed8e1e480..efca3e23801 100644 --- a/packages/rs-dpp/src/document/document_factory/v0/mod.rs +++ b/packages/rs-dpp/src/document/document_factory/v0/mod.rs @@ -22,7 +22,11 @@ use crate::document::{ extended_document::v0::ExtendedDocumentV0, serialization_traits::DocumentPlatformConversionMethodsV0, ExtendedDocument, }; +use crate::fee::Credits; use crate::prelude::{BlockHeight, CoreBlockHeight, TimestampMillis}; +use crate::state_transition::documents_batch_transition::document_transition::{ + DocumentPurchaseTransition, DocumentTransferTransition, DocumentUpdatePriceTransition, +}; #[cfg(feature = "state-transitions")] use crate::state_transition::documents_batch_transition::{ document_transition::{ @@ -32,8 +36,6 @@ use crate::state_transition::documents_batch_transition::{ DocumentsBatchTransition, DocumentsBatchTransitionV0, }; use itertools::Itertools; -use crate::fee::Credits; -use crate::state_transition::documents_batch_transition::document_transition::{DocumentPurchaseTransition, DocumentTransferTransition, DocumentUpdatePriceTransition}; const PROPERTY_FEATURE_VERSION: &str = "$version"; const PROPERTY_ENTROPY: &str = "$entropy"; @@ -213,7 +215,7 @@ impl DocumentFactoryV0 { >, nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce, recipient: Option, - price: Option + price: Option, ) -> Result { let platform_version = PlatformVersion::get(self.protocol_version)?; let documents: Vec<( @@ -273,17 +275,19 @@ impl DocumentFactoryV0 { .collect(), nonce_counter, platform_version, - recipient - ), - DocumentTransitionActionType::UpdatePrice => Self::document_update_price_transitions( - documents - .into_iter() - .map(|(document, document_type, _)| (document, document_type)) - .collect(), - nonce_counter, - platform_version, - price + recipient, ), + DocumentTransitionActionType::UpdatePrice => { + Self::document_update_price_transitions( + documents + .into_iter() + .map(|(document, document_type, _)| (document, document_type)) + .collect(), + nonce_counter, + platform_version, + price, + ) + } DocumentTransitionActionType::Purchase => Self::document_purchase_transitions( documents .into_iter() @@ -292,14 +296,15 @@ impl DocumentFactoryV0 { nonce_counter, platform_version, price, - recipient + recipient, ), _ => { let action_type_name: &str = action.into(); Err(ProtocolError::InvalidStateTransitionType( action_type_name.to_string(), - ))}, + )) + } }) .collect::, ProtocolError>>()? .into_iter() @@ -588,7 +593,7 @@ impl DocumentFactoryV0 { documents: Vec<(Document, DocumentTypeRef)>, nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce platform_version: &PlatformVersion, - recipient_owner_id: Option + recipient_owner_id: Option, ) -> Result, ProtocolError> { documents .into_iter() @@ -635,7 +640,7 @@ impl DocumentFactoryV0 { documents: Vec<(Document, DocumentTypeRef)>, nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce platform_version: &PlatformVersion, - price: Option + price: Option, ) -> Result, ProtocolError> { documents .into_iter() @@ -680,7 +685,7 @@ impl DocumentFactoryV0 { nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce platform_version: &PlatformVersion, price: Option, - recipient: Option + recipient: Option, ) -> Result, ProtocolError> { documents .into_iter() diff --git a/packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/action_type.rs b/packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/action_type.rs index fb4cf51ccf1..afc2943983f 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/action_type.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/action_type.rs @@ -48,7 +48,6 @@ impl TryFrom<&str> for DocumentTransitionActionType { } } - impl From for &str { fn from(value: DocumentTransitionActionType) -> Self { match value { @@ -58,7 +57,9 @@ impl From for &str { DocumentTransitionActionType::Transfer => "Transfer", DocumentTransitionActionType::Purchase => "Purchase", DocumentTransitionActionType::UpdatePrice => "UpdatePrice", - DocumentTransitionActionType::IgnoreWhileBumpingRevision => "IgnoreWhileBumpingRevision" + DocumentTransitionActionType::IgnoreWhileBumpingRevision => { + "IgnoreWhileBumpingRevision" + } } } } diff --git a/packages/rs-dpp/src/tests/fixtures/get_document_transitions_fixture.rs b/packages/rs-dpp/src/tests/fixtures/get_document_transitions_fixture.rs index dfb531b5546..9c78a2b2e6e 100644 --- a/packages/rs-dpp/src/tests/fixtures/get_document_transitions_fixture.rs +++ b/packages/rs-dpp/src/tests/fixtures/get_document_transitions_fixture.rs @@ -24,7 +24,7 @@ pub fn get_document_transitions_fixture<'a>( DocumentFactory::new(protocol_version).expect("expected to get document factory"); document_factory - .create_state_transition(documents, nonce_counter) + .create_state_transition(documents, nonce_counter, None, None) .expect("the transitions should be created") .transitions() .to_owned() From 5484b65d988a9e9538e7b5569867f321ab6db7e9 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Fri, 31 Jan 2025 18:24:06 +0700 Subject: [PATCH 23/50] chore(wasm-dpp): remove unused --- .../document_transfer_transition.rs | 27 ------------------- .../document_transition/mod.rs | 1 - 2 files changed, 28 deletions(-) delete mode 100644 packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_transfer_transition.rs diff --git a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_transfer_transition.rs b/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_transfer_transition.rs deleted file mode 100644 index c9c745d4098..00000000000 --- a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_transfer_transition.rs +++ /dev/null @@ -1,27 +0,0 @@ -use wasm_bindgen::prelude::wasm_bindgen; -use dpp::state_transition::documents_batch_transition::document_transition::DocumentTransferTransition; - -#[wasm_bindgen(js_name=DocumentTransferTransition)] -#[derive(Debug, Clone)] -pub struct DocumentTransferTransitionWasm { - inner: DocumentTransferTransition, -} - -impl From for DocumentTransferTransitionWasm { - fn from(v: DocumentTransferTransition) -> Self { - Self { inner: v } - } -} - -impl From for DocumentTransferTransition { - fn from(v: DocumentTransferTransitionWasm) -> Self { - v.inner - } -} - -#[wasm_bindgen(js_class=DocumentTransferTransition)] -impl DocumentTransferTransitionWasm { -} - -impl DocumentTransferTransitionWasm { -} diff --git a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs b/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs index 300ed732ee5..d4ad4e89f5f 100644 --- a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs +++ b/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs @@ -1,5 +1,4 @@ mod document_create_transition; -mod document_transfer_transition; // mod document_delete_transition; // mod document_replace_transition; From e96b20a224fea5b1ec7b1adfa3eeb421fe964f04 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Fri, 31 Jan 2025 18:55:48 +0700 Subject: [PATCH 24/50] feat(js-dash-sdk): add NFT state transitions docs --- .../docs/platform/documents/broadcast.md | 18 ++++++---- .../docs/platform/documents/purchase.md | 33 +++++++++++++++++++ .../docs/platform/documents/transfer.md | 31 +++++++++++++++++ .../docs/platform/documents/updatePrice.md | 29 ++++++++++++++++ 4 files changed, 104 insertions(+), 7 deletions(-) create mode 100644 packages/js-dash-sdk/docs/platform/documents/purchase.md create mode 100644 packages/js-dash-sdk/docs/platform/documents/transfer.md create mode 100644 packages/js-dash-sdk/docs/platform/documents/updatePrice.md diff --git a/packages/js-dash-sdk/docs/platform/documents/broadcast.md b/packages/js-dash-sdk/docs/platform/documents/broadcast.md index 67e59a2d991..8ee2238d0ed 100644 --- a/packages/js-dash-sdk/docs/platform/documents/broadcast.md +++ b/packages/js-dash-sdk/docs/platform/documents/broadcast.md @@ -3,13 +3,17 @@ Parameters: -| parameters | type | required | Description | -|----------------------------|------------|----------|------------------------------------------------------------------------------| -| **documents** | Object | yes | | -| **documents.create** | ExtendedDocument[] | no | array of valid [created document](../documents/create.md) to create | -| **documents.replace** | ExtendedDocument[] | no | array of valid [created document](../documents/create.md) to replace | -| **documents.delete** | ExtendedDocument[] | no | array of valid [created document](../documents/create.md) to delete | -| **identity** | Identity | yes | A valid [registered identity](../identities/register.md) | +| parameters | type | required | Description | +|---------------------------|--------------------|----------|----------------------------------------------------------------------------------------| +| **documents** | Object | yes | | +| **documents.create** | ExtendedDocument[] | no | array of valid [created document](../documents/create.md) to create | +| **documents.replace** | ExtendedDocument[] | no | array of valid [created document](../documents/create.md) to replace | +| **documents.delete** | ExtendedDocument[] | no | array of valid [created document](../documents/create.md) to delete | +| **documents.transfer** | ExtendedDocument[] | no | array of valid [created document](../documents/create.md) to transfer | +| **documents.updatePrice** | ExtendedDocument[] | no | array of valid [created document](../documents/create.md) to set price | +| **documents.purchase** | ExtendedDocument[] | no | array of valid [created document](../documents/create.md) to purchase | +| **identity** | Identity | yes | A valid [registered identity](../identities/register.md) | +| **options** | DocumentTransitionParams | no | An object with two optional fields `price` and `receiver` that is used for NFT actions | **Example**: diff --git a/packages/js-dash-sdk/docs/platform/documents/purchase.md b/packages/js-dash-sdk/docs/platform/documents/purchase.md new file mode 100644 index 00000000000..e88d17db08a --- /dev/null +++ b/packages/js-dash-sdk/docs/platform/documents/purchase.md @@ -0,0 +1,33 @@ +**Usage**: `client.platform.documents.broadcast(documents, identity, options)` +**Description**: This method will broadcast a purchase state transition that buys the given document from other Identity. + +Parameters: + +| parameters | type | required | Description | +|------------------------|---------|------------------ |-------------------------------------------------------------------| +| **documents.purchase** | ExtendedDocument[] | no | array of valid [created document](../documents/create.md) to buy | +| **identity** | Identity | yes | A valid [registered identity](../identities/register.md) | +| **options** | DocumentTransitionParams | no | An object with field `price` (BigInt) and `receiver` (Identifier) | + +**Example**: +```js +const identityId = '';// Your identity identifier +const receiverId = ''; // Receiver identity identifier +const documentId = '' // Your document id +const price = BigInt(1000000) + +const identity = await client.platform.identities.get(identityId); +const receiverIdentity = await client.platform.identities.get(receiverId); + +const identity = await client.platform.identities.get(identityId); + +const [document] = await dash.platform.documents.get( + 'helloWorldContract.note', + { where: [['$id', '==', documentId]] }, +); + +await dash.platform.documents.broadcast({ updatePrice: [document], }, identity, { price, receiver: receiverIdentity.getId() }); +``` +**Note**: This method will change the ownership of the document to your identity, and seller identity will be credited with the amount specified in the updatePrice deducted from your balance. + +Returns: DocumentsBatchTransition diff --git a/packages/js-dash-sdk/docs/platform/documents/transfer.md b/packages/js-dash-sdk/docs/platform/documents/transfer.md new file mode 100644 index 00000000000..9200618a547 --- /dev/null +++ b/packages/js-dash-sdk/docs/platform/documents/transfer.md @@ -0,0 +1,31 @@ +**Usage**: `client.platform.documents.broadcast(documents, identity, options)` +**Description**: This method will broadcast a document transfer + +Parameters: + +| parameters | type | required | Description | +|-------------------|---------|------------------ |-----------------------------------------------------------------------| +| **documents.transfer** | ExtendedDocument[] | no | array of valid [created document](../documents/create.md) to transfer | +| **identity** | Identity | yes | A valid [registered identity](../identities/register.md) | +| **options** | DocumentTransitionParams | no | An object with `receiver` field | + +**Example**: +```js +const identityId = '';// Your identity identifier +const receiverId = ''; // Receiver identity identifier +const documentId = '' // Your document id + +const identity = await client.platform.identities.get(identityId); +const receiverIdentity = await client.platform.identities.get(receiverId); + +const [document] = await dash.platform.documents.get( + 'helloWorldContract.note', + { where: [['$id', '==', documentId]] }, +); + +await dash.platform.documents.broadcast({ transfer: [document], }, identity, { receiver: receiverIdentity.getId() }); +``` + +**Note**: Transfer transition changes the ownership of the given document to the receiver identity + +Returns: DocumentsBatchTransition diff --git a/packages/js-dash-sdk/docs/platform/documents/updatePrice.md b/packages/js-dash-sdk/docs/platform/documents/updatePrice.md new file mode 100644 index 00000000000..d1c4c284b10 --- /dev/null +++ b/packages/js-dash-sdk/docs/platform/documents/updatePrice.md @@ -0,0 +1,29 @@ +**Usage**: `client.platform.documents.broadcast(documents, identity, options)` +**Description**: This method will broadcast an update price state transition that sets a price for the given document. + +Parameters: + +| parameters | type | required | Description | +|---------------------------|---------|------------------ |---------------------------------------------------------------------------| +| **documents.updatePrice** | ExtendedDocument[] | no | array of valid [created document](../documents/create.md) to update price | +| **identity** | Identity | yes | A valid [registered identity](../identities/register.md) | +| **options** | DocumentTransitionParams | no | An object with field `price` (BigInt) | + +**Example**: +```js +const identityId = '';// Your identity identifier +const documentId = '' // Your document id +const price = BigInt(1000000) + +const identity = await client.platform.identities.get(identityId); + +const [document] = await dash.platform.documents.get( + 'helloWorldContract.note', + { where: [['$id', '==', documentId]] }, +); + +await dash.platform.documents.broadcast({ updatePrice: [document], }, identity, { price }); +``` +**Note**: This method sets the same price on all documents in the batch (only one is possible right now) + +Returns: DocumentsBatchTransition From 7cdf3c6ac86832216a48431d9e766064afa081bf Mon Sep 17 00:00:00 2001 From: pshenmic Date: Fri, 14 Feb 2025 22:30:12 +0700 Subject: [PATCH 25/50] fix(wasm-dpp): lint fix --- .../wasm-dpp/src/document/document_facade.rs | 10 +++---- packages/wasm-dpp/src/document/errors/mod.rs | 2 +- .../src/document/extended_document.rs | 12 ++++++-- packages/wasm-dpp/src/document/factory.rs | 29 ++++++++++++------- 4 files changed, 34 insertions(+), 19 deletions(-) diff --git a/packages/wasm-dpp/src/document/document_facade.rs b/packages/wasm-dpp/src/document/document_facade.rs index de9acc454d6..8aad5da99a8 100644 --- a/packages/wasm-dpp/src/document/document_facade.rs +++ b/packages/wasm-dpp/src/document/document_facade.rs @@ -1,9 +1,9 @@ -use std::rc::Rc; -use wasm_bindgen::{prelude::*, JsValue}; -use dpp::fee::Credits; -use dpp::identifier::Identifier; use crate::document::factory::DocumentFactoryWASM; use crate::{DataContractWasm, ExtendedDocumentWasm}; +use dpp::fee::Credits; +use dpp::identifier::Identifier; +use std::rc::Rc; +use wasm_bindgen::{prelude::*, JsValue}; use crate::document::state_transition::document_batch_transition::DocumentsBatchTransitionWasm; use crate::identifier::IdentifierWrapper; @@ -99,7 +99,7 @@ impl DocumentFacadeWasm { documents: &JsValue, nonce_counter_value: &js_sys::Object, //IdentityID/ContractID -> nonce (BigInt) recipient: Option, - price: Option + price: Option, ) -> Result { self.factory .create_state_transition(documents, nonce_counter_value, recipient, price) diff --git a/packages/wasm-dpp/src/document/errors/mod.rs b/packages/wasm-dpp/src/document/errors/mod.rs index f900fde35d1..3b3b2018d38 100644 --- a/packages/wasm-dpp/src/document/errors/mod.rs +++ b/packages/wasm-dpp/src/document/errors/mod.rs @@ -79,7 +79,7 @@ pub fn from_document_to_js_error(e: DocumentError) -> JsValue { DocumentError::InvalidActionError(action) => InvalidActionError::new(action.into()).into(), DocumentError::TryingToDeleteIndelibleDocument { document } => { TryingToDeleteImmutableDocumentError::new((*document).into()).into() - }, + } DocumentError::TryingToTransferNonTransferableDocument { document } => { TryingToTransferNonTransferableDocumentError::new((*document).into()).into() } diff --git a/packages/wasm-dpp/src/document/extended_document.rs b/packages/wasm-dpp/src/document/extended_document.rs index de4f8d98337..85d0d5c3022 100644 --- a/packages/wasm-dpp/src/document/extended_document.rs +++ b/packages/wasm-dpp/src/document/extended_document.rs @@ -1,4 +1,6 @@ -use dpp::document::{DocumentV0Getters, DocumentV0Setters, ExtendedDocument, EXTENDED_DOCUMENT_IDENTIFIER_FIELDS}; +use dpp::document::{ + DocumentV0Getters, DocumentV0Setters, ExtendedDocument, EXTENDED_DOCUMENT_IDENTIFIER_FIELDS, +}; use serde_json::Value as JsonValue; use dpp::platform_value::{Bytes32, Value}; @@ -9,13 +11,17 @@ use dpp::util::json_value::JsonValueExt; use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; use dpp::document::serialization_traits::ExtendedDocumentPlatformConversionMethodsV0; use dpp::platform_value::converter::serde_json::BTreeValueJsonConverter; +use dpp::state_transition::documents_batch_transition::document_transition::{ + DocumentPurchaseTransition, DocumentTransferTransition, DocumentUpdatePriceTransition, +}; +use dpp::state_transition::documents_batch_transition::{ + DocumentsBatchTransition, DocumentsBatchTransitionV0, +}; use dpp::version::PlatformVersion; use dpp::ProtocolError; use serde::{Deserialize, Serialize}; use std::convert::TryInto; use wasm_bindgen::prelude::*; -use dpp::state_transition::documents_batch_transition::{DocumentsBatchTransition, DocumentsBatchTransitionV0}; -use dpp::state_transition::documents_batch_transition::document_transition::{DocumentPurchaseTransition, DocumentTransferTransition, DocumentUpdatePriceTransition}; use crate::buffer::Buffer; use crate::data_contract::DataContractWasm; diff --git a/packages/wasm-dpp/src/document/factory.rs b/packages/wasm-dpp/src/document/factory.rs index 7e592cb0380..56c09923dca 100644 --- a/packages/wasm-dpp/src/document/factory.rs +++ b/packages/wasm-dpp/src/document/factory.rs @@ -13,19 +13,19 @@ use dpp::document::Document; use dpp::prelude::ExtendedDocument; -use dpp::identifier::Identifier; -use dpp::state_transition::documents_batch_transition::document_transition::action_type::DocumentTransitionActionType; -use dpp::version::PlatformVersion; -use std::convert::TryFrom; -use dpp::fee::Credits; use crate::document_batch_transition::DocumentsBatchTransitionWasm; use crate::entropy_generator::ExternalEntropyGenerator; +use crate::identifier::IdentifierWrapper; use crate::{ identifier::identifier_from_js_value, utils::{IntoWasm, ToSerdeJSONExt, WithJsError}, DataContractWasm, ExtendedDocumentWasm, }; -use crate::identifier::IdentifierWrapper; +use dpp::fee::Credits; +use dpp::identifier::Identifier; +use dpp::state_transition::documents_batch_transition::document_transition::action_type::DocumentTransitionActionType; +use dpp::version::PlatformVersion; +use std::convert::TryFrom; #[wasm_bindgen(js_name=DocumentTransitions)] #[derive(Debug, Default)] @@ -111,7 +111,7 @@ impl DocumentFactoryWASM { documents: &JsValue, nonce_counter_value: &js_sys::Object, //IdentityID/ContractID -> nonce recipient: Option, - price: Option + price: Option, ) -> Result { let mut nonce_counter = BTreeMap::new(); let mut contract_ids_to_check = HashSet::<&Identifier>::new(); @@ -184,7 +184,12 @@ impl DocumentFactoryWASM { let batch_transition = self .0 - .create_state_transition(documents, &mut nonce_counter, recipient.map(|e| { Identifier::from(e)}), price) + .create_state_transition( + documents, + &mut nonce_counter, + recipient.map(|e| Identifier::from(e)), + price, + ) .with_js_error()?; Ok(batch_transition.into()) @@ -287,14 +292,18 @@ fn extract_documents_by_action( let documents_replace = extract_documents_of_action(documents, "replace").with_js_error()?; let documents_delete = extract_documents_of_action(documents, "delete").with_js_error()?; let documents_transfer = extract_documents_of_action(documents, "transfer").with_js_error()?; - let documents_update_price = extract_documents_of_action(documents, "updatePrice").with_js_error()?; + let documents_update_price = + extract_documents_of_action(documents, "updatePrice").with_js_error()?; let documents_purchase = extract_documents_of_action(documents, "purchase").with_js_error()?; documents_by_action.insert(DocumentTransitionActionType::Create, documents_create); documents_by_action.insert(DocumentTransitionActionType::Replace, documents_replace); documents_by_action.insert(DocumentTransitionActionType::Delete, documents_delete); documents_by_action.insert(DocumentTransitionActionType::Transfer, documents_transfer); - documents_by_action.insert(DocumentTransitionActionType::UpdatePrice, documents_update_price); + documents_by_action.insert( + DocumentTransitionActionType::UpdatePrice, + documents_update_price, + ); documents_by_action.insert(DocumentTransitionActionType::Purchase, documents_purchase); Ok(documents_by_action) From 9471b11032153380b8a44fa6e426053afefb3335 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Fri, 14 Feb 2025 22:32:37 +0700 Subject: [PATCH 26/50] fix(js-dash-sdk): doc fix --- packages/js-dash-sdk/docs/platform/documents/purchase.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/js-dash-sdk/docs/platform/documents/purchase.md b/packages/js-dash-sdk/docs/platform/documents/purchase.md index e88d17db08a..96269296f0b 100644 --- a/packages/js-dash-sdk/docs/platform/documents/purchase.md +++ b/packages/js-dash-sdk/docs/platform/documents/purchase.md @@ -26,7 +26,7 @@ const [document] = await dash.platform.documents.get( { where: [['$id', '==', documentId]] }, ); -await dash.platform.documents.broadcast({ updatePrice: [document], }, identity, { price, receiver: receiverIdentity.getId() }); +await dash.platform.documents.broadcast({ purchase: [document], }, identity, { price, receiver: receiverIdentity.getId() }); ``` **Note**: This method will change the ownership of the document to your identity, and seller identity will be credited with the amount specified in the updatePrice deducted from your balance. From 5cc19229f860173bdf11774cdcb166dc4eaae473 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Mon, 17 Feb 2025 11:09:59 +0700 Subject: [PATCH 27/50] fix(wasm-dpp): feature error --- packages/rs-dpp/src/document/document_factory/v0/mod.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/rs-dpp/src/document/document_factory/v0/mod.rs b/packages/rs-dpp/src/document/document_factory/v0/mod.rs index efca3e23801..4d78b49f3c5 100644 --- a/packages/rs-dpp/src/document/document_factory/v0/mod.rs +++ b/packages/rs-dpp/src/document/document_factory/v0/mod.rs @@ -24,14 +24,12 @@ use crate::document::{ }; use crate::fee::Credits; use crate::prelude::{BlockHeight, CoreBlockHeight, TimestampMillis}; -use crate::state_transition::documents_batch_transition::document_transition::{ - DocumentPurchaseTransition, DocumentTransferTransition, DocumentUpdatePriceTransition, -}; #[cfg(feature = "state-transitions")] use crate::state_transition::documents_batch_transition::{ document_transition::{ action_type::DocumentTransitionActionType, DocumentCreateTransition, DocumentDeleteTransition, DocumentReplaceTransition, DocumentTransition, + DocumentPurchaseTransition, DocumentTransferTransition, DocumentUpdatePriceTransition }, DocumentsBatchTransition, DocumentsBatchTransitionV0, }; From db2cc9af232a46f3dbac1d729f09d8f1e4ab4779 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Mon, 17 Feb 2025 11:18:29 +0700 Subject: [PATCH 28/50] fix(wasm-dpp): lint fix --- packages/rs-dpp/src/document/document_factory/v0/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/rs-dpp/src/document/document_factory/v0/mod.rs b/packages/rs-dpp/src/document/document_factory/v0/mod.rs index 4d78b49f3c5..84508aa3cf5 100644 --- a/packages/rs-dpp/src/document/document_factory/v0/mod.rs +++ b/packages/rs-dpp/src/document/document_factory/v0/mod.rs @@ -28,8 +28,8 @@ use crate::prelude::{BlockHeight, CoreBlockHeight, TimestampMillis}; use crate::state_transition::documents_batch_transition::{ document_transition::{ action_type::DocumentTransitionActionType, DocumentCreateTransition, - DocumentDeleteTransition, DocumentReplaceTransition, DocumentTransition, - DocumentPurchaseTransition, DocumentTransferTransition, DocumentUpdatePriceTransition + DocumentDeleteTransition, DocumentPurchaseTransition, DocumentReplaceTransition, + DocumentTransferTransition, DocumentTransition, DocumentUpdatePriceTransition, }, DocumentsBatchTransition, DocumentsBatchTransitionV0, }; From 322a3e30a10351474b754f51beb1e406b1a41c1d Mon Sep 17 00:00:00 2001 From: pshenmic Date: Tue, 25 Feb 2025 03:15:24 +0700 Subject: [PATCH 29/50] feat(wasm-dpp): implement document transition params --- .../Platform/methods/documents/broadcast.ts | 52 ++++++------ .../src/document/document_factory/mod.rs | 9 +-- .../src/document/document_factory/v0/mod.rs | 68 +++++++--------- packages/rs-dpp/src/document/mod.rs | 7 ++ .../wasm-dpp/src/document/document_facade.rs | 7 +- .../src/document/extended_document.rs | 9 +-- packages/wasm-dpp/src/document/factory.rs | 81 ++++++++++++------- packages/wasm-dpp/src/document/mod.rs | 2 +- .../document_transition/mod.rs | 16 ++-- packages/wasm-dpp/src/metadata.rs | 2 - 10 files changed, 135 insertions(+), 118 deletions(-) diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts index 96538401266..0d2b9bf07d5 100644 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts @@ -3,34 +3,39 @@ import { Platform } from '../../Platform'; import broadcastStateTransition from '../../broadcastStateTransition'; import { signStateTransition } from '../../signStateTransition'; -class DocumentTransitionParams { +interface DocumentTransitionParams { receiver?: Identifier; - price?: bigint; } +interface DocumentSubmittable { + document: ExtendedDocument; + params?: DocumentTransitionParams; +} + /** * Broadcast document onto the platform * * @param {Object} documents - * @param {ExtendedDocument[]} [documents.create] - * @param {ExtendedDocument[]} [documents.replace] - * @param {ExtendedDocument[]} [documents.delete] + * @param {DocumentSubmittable[]} [documents.create] + * @param {DocumentSubmittable[]} [documents.replace] + * @param {DocumentSubmittable[]} [documents.delete] + * @param {DocumentSubmittable[]} [documents.transfer] + * @param {DocumentSubmittable[]} [documents.updatePrice] + * @param {DocumentSubmittable[]} [documents.purchase] * @param {Identity} identity - * @param options {DocumentTransitionParams} optional params for NFT functions */ export default async function broadcast( this: Platform, documents: { - create?: ExtendedDocument[], - replace?: ExtendedDocument[], - delete?: ExtendedDocument[], - transfer?: ExtendedDocument[], - updatePrice?: ExtendedDocument[], - purchase?: ExtendedDocument[], + create?: DocumentSubmittable[], + replace?: DocumentSubmittable[], + delete?: DocumentSubmittable[], + transfer?: DocumentSubmittable[], + updatePrice?: DocumentSubmittable[], + purchase?: DocumentSubmittable[], }, identity: any, - options?: DocumentTransitionParams, ): Promise { this.logger.debug('[Document#broadcast] Broadcast documents', { create: documents.create?.length || 0, @@ -52,26 +57,29 @@ export default async function broadcast( ...(documents.transfer || []), ...(documents.updatePrice || []), ...(documents.purchase || []), - ][0]?.getDataContractId(); + ][0]?.document.getDataContractId(); if (!dataContractId) { throw new Error('Data contract ID is not found'); } - if (documents.transfer?.length && !options?.receiver) { + if (documents.transfer?.length && (documents.transfer + .some(({ params }) => !params?.receiver))) { throw new Error('Receiver identity is not found for transfer transition'); } - if (documents.updatePrice?.length && !options?.price) { + if (documents.updatePrice?.length && (documents.updatePrice + .some(({ params }) => !params?.price))) { throw new Error('Price must be provided for UpdatePrice operation'); } if (documents.purchase?.length) { - if (!options?.price && !options?.receiver) { - throw new Error('Price and Receiver must be provided for Purchase operation'); + if (documents.purchase?.length && (documents.purchase + .some(({ params }) => !params?.price && !params?.receiver))) { + throw new Error('Price must be provided for UpdatePrice operation'); } - documents.purchase.forEach((document) => document.setOwnerId(options.receiver)); + documents.purchase.forEach(({ document, params }) => document.setOwnerId(params!.receiver)); } const identityContractNonce = await this.nonceManager @@ -86,8 +94,6 @@ export default async function broadcast( const documentsBatchTransition = dpp.document.createStateTransition( documents, identityNonceObj, - options?.receiver, - options?.price, ); this.logger.silly('[Document#broadcast] Created documents batch transition'); @@ -100,7 +106,7 @@ export default async function broadcast( // Acknowledge documents identifiers to handle retry attempts to mitigate // state transition propagation lag if (documents.create) { - documents.create.forEach((document) => { + documents.create.forEach(({ document }) => { const documentLocator = `${document.getDataContractId().toString()}/${document.getType()}`; this.fetcher.acknowledgeKey(documentLocator); }); @@ -108,7 +114,7 @@ export default async function broadcast( // Forget documents identifiers to not retry on them anymore if (documents.delete) { - documents.delete.forEach((document) => { + documents.delete.forEach(({ document }) => { const documentLocator = `${document.getDataContractId().toString()}/${document.getType()}`; this.fetcher.forgetKey(documentLocator); }); diff --git a/packages/rs-dpp/src/document/document_factory/mod.rs b/packages/rs-dpp/src/document/document_factory/mod.rs index b8aa2f56e9b..52f86e6dc87 100644 --- a/packages/rs-dpp/src/document/document_factory/mod.rs +++ b/packages/rs-dpp/src/document/document_factory/mod.rs @@ -9,10 +9,9 @@ use derive_more::From; use platform_value::{Bytes32, Identifier, Value}; use crate::data_contract::document_type::DocumentTypeRef; -use crate::document::Document; +use crate::document::{Document, DocumentTransitionParams}; #[cfg(feature = "extended-document")] use crate::document::ExtendedDocument; -use crate::fee::Credits; #[cfg(feature = "state-transitions")] use crate::state_transition::documents_batch_transition::{ document_transition::action_type::DocumentTransitionActionType, DocumentsBatchTransition, @@ -117,16 +116,14 @@ impl DocumentFactory { documents_iter: impl IntoIterator< Item = ( DocumentTransitionActionType, - Vec<(Document, DocumentTypeRef<'a>, Bytes32)>, + Vec<(Document, Option, DocumentTypeRef<'a>, Bytes32)>, ), >, nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce - recipient: Option, - price: Option, ) -> Result { match self { DocumentFactory::V0(v0) => { - v0.create_state_transition(documents_iter, nonce_counter, recipient, price) + v0.create_state_transition(documents_iter, nonce_counter) } } } diff --git a/packages/rs-dpp/src/document/document_factory/v0/mod.rs b/packages/rs-dpp/src/document/document_factory/v0/mod.rs index 84508aa3cf5..db7a2ffab51 100644 --- a/packages/rs-dpp/src/document/document_factory/v0/mod.rs +++ b/packages/rs-dpp/src/document/document_factory/v0/mod.rs @@ -5,7 +5,7 @@ use crate::data_contract::document_type::DocumentTypeRef; use crate::data_contract::errors::DataContractError; use crate::data_contract::DataContract; use crate::document::errors::DocumentError; -use crate::document::{Document, DocumentV0Getters, DocumentV0Setters, INITIAL_REVISION}; +use crate::document::{Document, DocumentTransitionParams, DocumentV0Getters, DocumentV0Setters, INITIAL_REVISION}; use chrono::Utc; use std::collections::BTreeMap; @@ -22,7 +22,6 @@ use crate::document::{ extended_document::v0::ExtendedDocumentV0, serialization_traits::DocumentPlatformConversionMethodsV0, ExtendedDocument, }; -use crate::fee::Credits; use crate::prelude::{BlockHeight, CoreBlockHeight, TimestampMillis}; #[cfg(feature = "state-transitions")] use crate::state_transition::documents_batch_transition::{ @@ -208,35 +207,33 @@ impl DocumentFactoryV0 { documents_iter: impl IntoIterator< Item = ( DocumentTransitionActionType, - Vec<(Document, DocumentTypeRef<'a>, Bytes32)>, + Vec<(Document, Option, DocumentTypeRef<'a>, Bytes32)>, ), >, - nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce, - recipient: Option, - price: Option, + nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce ) -> Result { let platform_version = PlatformVersion::get(self.protocol_version)?; let documents: Vec<( DocumentTransitionActionType, - Vec<(Document, DocumentTypeRef, Bytes32)>, + Vec<(Document, Option, DocumentTypeRef, Bytes32)>, )> = documents_iter.into_iter().collect(); let mut flattened_documents_iter = documents.iter().flat_map(|(_, v)| v).peekable(); - let Some((first_document, _, _)) = flattened_documents_iter.peek() else { + let Some((first_document, _, _, _)) = flattened_documents_iter.peek() else { return Err(DocumentError::NoDocumentsSuppliedError.into()); }; let owner_id = first_document.owner_id(); let is_the_same_owner = - flattened_documents_iter.all(|(document, _, _)| document.owner_id() == owner_id); + flattened_documents_iter.all(|(document, _, _, _)| document.owner_id() == owner_id); if !is_the_same_owner { return Err(DocumentError::MismatchOwnerIdsError { documents: documents .into_iter() .flat_map(|(_, v)| { v.into_iter() - .map(|(document, _, _)| document) + .map(|(document, _, _, _)| document) .collect::>() }) .collect(), @@ -247,13 +244,18 @@ impl DocumentFactoryV0 { let transitions: Vec<_> = documents .into_iter() .map(|(action, documents)| match action { - DocumentTransitionActionType::Create => { - Self::document_create_transitions(documents, nonce_counter, platform_version) - } + DocumentTransitionActionType::Create => Self::document_create_transitions( + documents + .into_iter() + .map(|(document, _, document_type, bytes,)| (document, document_type, bytes)) + .collect(), + nonce_counter, + platform_version, + ), DocumentTransitionActionType::Delete => Self::document_delete_transitions( documents .into_iter() - .map(|(document, document_type, _)| (document, document_type)) + .map(|(document, _, document_type, _,)| (document, document_type)) .collect(), nonce_counter, platform_version, @@ -261,7 +263,7 @@ impl DocumentFactoryV0 { DocumentTransitionActionType::Replace => Self::document_replace_transitions( documents .into_iter() - .map(|(document, document_type, _)| (document, document_type)) + .map(|(document, _, document_type, _)| (document, document_type)) .collect(), nonce_counter, platform_version, @@ -269,32 +271,28 @@ impl DocumentFactoryV0 { DocumentTransitionActionType::Transfer => Self::document_transfer_transitions( documents .into_iter() - .map(|(document, document_type, _)| (document, document_type)) + .map(|(document, document_params, document_type, _)| (document, document_params.unwrap(), document_type)) .collect(), nonce_counter, platform_version, - recipient, ), DocumentTransitionActionType::UpdatePrice => { Self::document_update_price_transitions( documents .into_iter() - .map(|(document, document_type, _)| (document, document_type)) + .map(|(document, document_params, document_type, _)| (document, document_params.unwrap(), document_type)) .collect(), nonce_counter, platform_version, - price, ) } DocumentTransitionActionType::Purchase => Self::document_purchase_transitions( documents .into_iter() - .map(|(document, document_type, _)| (document, document_type)) + .map(|(document, document_params, document_type, _)| (document, document_params.unwrap(), document_type)) .collect(), nonce_counter, platform_version, - price, - recipient, ), _ => { let action_type_name: &str = action.into(); @@ -588,14 +586,13 @@ impl DocumentFactoryV0 { #[cfg(feature = "state-transitions")] fn document_transfer_transitions( - documents: Vec<(Document, DocumentTypeRef)>, + documents: Vec<(Document, DocumentTransitionParams, DocumentTypeRef)>, nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce - platform_version: &PlatformVersion, - recipient_owner_id: Option, + platform_version: &PlatformVersion ) -> Result, ProtocolError> { documents .into_iter() - .map(|(mut document, document_type)| { + .map(|(mut document, document_params, document_type)| { if !document_type.documents_transferable().is_transferable() { return Err(DocumentError::TryingToTransferNonTransferableDocument { document: Box::new(document), @@ -620,7 +617,7 @@ impl DocumentFactoryV0 { document, document_type, *nonce, - recipient_owner_id.unwrap(), + document_params.receiver.unwrap(), platform_version, None, None, @@ -635,14 +632,13 @@ impl DocumentFactoryV0 { #[cfg(feature = "state-transitions")] fn document_update_price_transitions( - documents: Vec<(Document, DocumentTypeRef)>, + documents: Vec<(Document, DocumentTransitionParams, DocumentTypeRef)>, nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce platform_version: &PlatformVersion, - price: Option, ) -> Result, ProtocolError> { documents .into_iter() - .map(|(mut document, document_type)| { + .map(|(mut document, document_params, document_type)| { let Some(_document_revision) = document.revision() else { return Err(DocumentError::RevisionAbsentError { document: Box::new(document), @@ -663,7 +659,7 @@ impl DocumentFactoryV0 { let transition = DocumentUpdatePriceTransition::from_document( document, document_type, - price.unwrap(), + document_params.price.unwrap(), *nonce, platform_version, None, @@ -679,15 +675,13 @@ impl DocumentFactoryV0 { #[cfg(feature = "state-transitions")] fn document_purchase_transitions( - documents: Vec<(Document, DocumentTypeRef)>, + documents: Vec<(Document, DocumentTransitionParams, DocumentTypeRef)>, nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce platform_version: &PlatformVersion, - price: Option, - recipient: Option, ) -> Result, ProtocolError> { documents .into_iter() - .map(|(mut document, document_type)| { + .map(|(mut document, document_params, document_type)| { let Some(_document_revision) = document.revision() else { return Err(DocumentError::RevisionAbsentError { document: Box::new(document), @@ -696,7 +690,7 @@ impl DocumentFactoryV0 { }; let nonce = nonce_counter - .entry((recipient.unwrap(), document_type.data_contract_id())) + .entry((document_params.receiver.unwrap(), document_type.data_contract_id())) .or_default(); //document.set_owner_id(recipient.unwrap()); @@ -706,7 +700,7 @@ impl DocumentFactoryV0 { let transition = DocumentPurchaseTransition::from_document( document, document_type, - price.unwrap(), + document_params.price.unwrap(), *nonce, platform_version, None, diff --git a/packages/rs-dpp/src/document/mod.rs b/packages/rs-dpp/src/document/mod.rs index 29d2ec24a32..7adfe7f1c16 100644 --- a/packages/rs-dpp/src/document/mod.rs +++ b/packages/rs-dpp/src/document/mod.rs @@ -47,6 +47,7 @@ use serde::{Deserialize, Serialize}; use std::fmt; use std::fmt::Formatter; +use platform_value::Identifier; #[derive(Clone, Debug, PartialEq, From)] #[cfg_attr( @@ -59,6 +60,12 @@ pub enum Document { V0(DocumentV0), } +#[derive(Clone, Debug)] +pub struct DocumentTransitionParams { + pub receiver: Option, + pub price: Option +} + impl fmt::Display for Document { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { diff --git a/packages/wasm-dpp/src/document/document_facade.rs b/packages/wasm-dpp/src/document/document_facade.rs index 8aad5da99a8..b25f49d7a7a 100644 --- a/packages/wasm-dpp/src/document/document_facade.rs +++ b/packages/wasm-dpp/src/document/document_facade.rs @@ -1,12 +1,9 @@ use crate::document::factory::DocumentFactoryWASM; use crate::{DataContractWasm, ExtendedDocumentWasm}; -use dpp::fee::Credits; -use dpp::identifier::Identifier; use std::rc::Rc; use wasm_bindgen::{prelude::*, JsValue}; use crate::document::state_transition::document_batch_transition::DocumentsBatchTransitionWasm; -use crate::identifier::IdentifierWrapper; #[derive(Clone)] #[wasm_bindgen(js_name=DocumentFacade)] @@ -98,11 +95,9 @@ impl DocumentFacadeWasm { &self, documents: &JsValue, nonce_counter_value: &js_sys::Object, //IdentityID/ContractID -> nonce (BigInt) - recipient: Option, - price: Option, ) -> Result { self.factory - .create_state_transition(documents, nonce_counter_value, recipient, price) + .create_state_transition(documents, nonce_counter_value) } // /// Creates Documents State Transition diff --git a/packages/wasm-dpp/src/document/extended_document.rs b/packages/wasm-dpp/src/document/extended_document.rs index 85d0d5c3022..a33ab17f293 100644 --- a/packages/wasm-dpp/src/document/extended_document.rs +++ b/packages/wasm-dpp/src/document/extended_document.rs @@ -4,19 +4,13 @@ use dpp::document::{ use serde_json::Value as JsonValue; use dpp::platform_value::{Bytes32, Value}; -use dpp::prelude::{Identifier, IdentityNonce, Revision, TimestampMillis, UserFeeIncrease}; +use dpp::prelude::{Identifier, Revision, TimestampMillis}; use dpp::util::json_value::JsonValueExt; use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; use dpp::document::serialization_traits::ExtendedDocumentPlatformConversionMethodsV0; use dpp::platform_value::converter::serde_json::BTreeValueJsonConverter; -use dpp::state_transition::documents_batch_transition::document_transition::{ - DocumentPurchaseTransition, DocumentTransferTransition, DocumentUpdatePriceTransition, -}; -use dpp::state_transition::documents_batch_transition::{ - DocumentsBatchTransition, DocumentsBatchTransitionV0, -}; use dpp::version::PlatformVersion; use dpp::ProtocolError; use serde::{Deserialize, Serialize}; @@ -28,7 +22,6 @@ use crate::data_contract::DataContractWasm; #[allow(deprecated)] // BinaryType is unsed in unused code below use crate::document::BinaryType; use crate::document::{ConversionOptions, DocumentWasm}; -use crate::document_batch_transition::DocumentsBatchTransitionWasm; use crate::errors::RustConversionError; use crate::identifier::{identifier_from_js_value, IdentifierWrapper}; use crate::lodash::lodash_set; diff --git a/packages/wasm-dpp/src/document/factory.rs b/packages/wasm-dpp/src/document/factory.rs index 56c09923dca..d980fd9db13 100644 --- a/packages/wasm-dpp/src/document/factory.rs +++ b/packages/wasm-dpp/src/document/factory.rs @@ -9,23 +9,20 @@ use crate::document::errors::InvalidActionNameError; use crate::document::platform_value::Bytes32; use dpp::data_contract::accessors::v0::DataContractV0Getters; use dpp::data_contract::document_type::DocumentTypeRef; -use dpp::document::Document; +use dpp::document::{Document, DocumentTransitionParams}; use dpp::prelude::ExtendedDocument; use crate::document_batch_transition::DocumentsBatchTransitionWasm; use crate::entropy_generator::ExternalEntropyGenerator; -use crate::identifier::IdentifierWrapper; -use crate::{ - identifier::identifier_from_js_value, - utils::{IntoWasm, ToSerdeJSONExt, WithJsError}, - DataContractWasm, ExtendedDocumentWasm, -}; -use dpp::fee::Credits; +use crate::{identifier::identifier_from_js_value, utils::{IntoWasm, ToSerdeJSONExt, WithJsError}, DataContractWasm, ExtendedDocumentWasm}; use dpp::identifier::Identifier; use dpp::state_transition::documents_batch_transition::document_transition::action_type::DocumentTransitionActionType; use dpp::version::PlatformVersion; use std::convert::TryFrom; +use js_sys::Uint8Array; +use web_sys::console; +use dpp::platform_value::string_encoding::Encoding::Base58; #[wasm_bindgen(js_name=DocumentTransitions)] #[derive(Debug, Default)] @@ -110,8 +107,6 @@ impl DocumentFactoryWASM { &self, documents: &JsValue, nonce_counter_value: &js_sys::Object, //IdentityID/ContractID -> nonce - recipient: Option, - price: Option, ) -> Result { let mut nonce_counter = BTreeMap::new(); let mut contract_ids_to_check = HashSet::<&Identifier>::new(); @@ -137,6 +132,7 @@ impl DocumentFactoryWASM { .unwrap() .parse::() .unwrap(); + nonce_counter.insert((identity_id, contract_id), nonce); }); }); @@ -149,7 +145,7 @@ impl DocumentFactoryWASM { let documents_by_action = extract_documents_by_action(documents)?; for (_, documents) in documents_by_action.iter() { - for document in documents.iter() { + for (document, _) in documents.iter() { if !contract_ids_to_check.contains(&document.data_contract().id()) { return Err(JsValue::from_str( "Document's data contract is not in the nonce counter", @@ -160,15 +156,16 @@ impl DocumentFactoryWASM { let documents: Vec<( DocumentTransitionActionType, - Vec<(Document, DocumentTypeRef, Bytes32)>, + Vec<(Document, Option, DocumentTypeRef, Bytes32)>, )> = documents_by_action .iter() .map(|(action_type, documents)| { - let documents_with_refs: Vec<(Document, DocumentTypeRef, Bytes32)> = documents - .iter() - .map(|extended_document| { + let documents_with_refs: Vec<(Document, Option, DocumentTypeRef, Bytes32)> = documents + .into_iter() + .map(|(extended_document, document_params)| { ( extended_document.document().clone(), + document_params.clone(), extended_document .data_contract() .document_type_for_name(extended_document.document_type_name()) @@ -187,8 +184,6 @@ impl DocumentFactoryWASM { .create_state_transition( documents, &mut nonce_counter, - recipient.map(|e| Identifier::from(e)), - price, ) .with_js_error()?; @@ -282,10 +277,10 @@ impl DocumentFactoryWASM { // fn extract_documents_by_action( documents: &JsValue, -) -> Result>, JsValue> { +) -> Result)>>, JsValue> { check_actions(documents)?; - let mut documents_by_action: HashMap> = + let mut documents_by_action: HashMap)>> = Default::default(); let documents_create = extract_documents_of_action(documents, "create").with_js_error()?; @@ -334,21 +329,53 @@ fn check_actions(documents: &JsValue) -> Result<(), JsValue> { fn extract_documents_of_action( documents: &JsValue, action: &str, -) -> Result, anyhow::Error> { - let documents_with_action = +) -> Result)>, anyhow::Error> { + let documents_submittable_with_action = js_sys::Reflect::get(documents, &action.to_string().into()).unwrap_or(JsValue::NULL); - if documents_with_action.is_null() || documents_with_action.is_undefined() { + if documents_submittable_with_action.is_null() || documents_submittable_with_action.is_undefined() { return Ok(vec![]); } - let documents_array = js_sys::Array::try_from(documents_with_action) + let documents_submittable_array = js_sys::Array::try_from(documents_submittable_with_action) .map_err(|e| anyhow!("property '{}' isn't an array: {}", action, e))?; - documents_array + documents_submittable_array .iter() - .map(|js_document| { - js_document + .map(|js_document_submittable| { + let document = js_sys::Reflect::get(&js_document_submittable, &"document".into()).unwrap(); + + let params: Option = js_sys::Reflect::get(&js_document_submittable, &"params".to_string().into()).map(|js_value| { + if js_value.is_undefined() || js_value.is_null() { + return None + } + + let receiver_id = js_sys::Reflect::get(&js_value, &"receiver".to_string().into()).map(|js_value| { + if js_value.is_undefined() || js_value.is_null() { + return None + } + + let buffer = Uint8Array::new(&js_value); + let bytes = Identifier::from_vec(buffer.to_vec()).unwrap(); + + Some(bytes) + }).unwrap(); + + let price: Option = js_sys::Reflect::get(&js_value, &"price".to_string().into()).map(|js_value| { + if js_value.is_undefined() || js_value.is_null() { + return None + } + + let price = u64::try_from(JsValue::from(&js_value)).unwrap(); + + return Some(price); + }) + .unwrap_or(None); + + Some(DocumentTransitionParams { receiver: receiver_id, price: price.map(|e| e.clone()) }) + }).unwrap(); + + document .to_wasm::("ExtendedDocument") .map_err(|e| { anyhow!( @@ -357,7 +384,7 @@ fn extract_documents_of_action( e ) }) - .map(|wasm_doc| wasm_doc.clone().into()) + .map(|wasm_doc| (wasm_doc.clone().into(), params)) }) .collect() } diff --git a/packages/wasm-dpp/src/document/mod.rs b/packages/wasm-dpp/src/document/mod.rs index 60de8050371..e1f2272baed 100644 --- a/packages/wasm-dpp/src/document/mod.rs +++ b/packages/wasm-dpp/src/document/mod.rs @@ -14,7 +14,7 @@ use crate::utils::WithJsError; use crate::utils::{with_serde_to_json_value, ToSerdeJSONExt}; use dpp::document::document_methods::DocumentMethodsV0; -use dpp::document::DocumentV0Getters; +use dpp::document::{ DocumentV0Getters}; pub mod errors; pub use state_transition::*; pub mod document_facade; diff --git a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs b/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs index d4ad4e89f5f..a36ce2665a1 100644 --- a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs +++ b/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs @@ -64,10 +64,10 @@ impl DocumentTransitionWasm { .serialize(&serde_wasm_bindgen::Serializer::json_compatible()) .unwrap() } - DocumentTransition::Delete(document_delete_transition) => JsValue::null(), - DocumentTransition::Transfer(document_transfer_transition) => JsValue::null(), - DocumentTransition::UpdatePrice(document_update_price_transition) => JsValue::null(), - DocumentTransition::Purchase(document_purchase_transition) => JsValue::null(), + DocumentTransition::Delete(_) => JsValue::null(), + DocumentTransition::Transfer(_) => JsValue::null(), + DocumentTransition::UpdatePrice(_) => JsValue::null(), + DocumentTransition::Purchase(_) => JsValue::null(), } } @@ -107,7 +107,7 @@ impl DocumentTransitionWasm { #[wasm_bindgen(js_name=get_price)] pub fn get_price(&self) -> Option { match &self.0 { - DocumentTransition::Create(create) => None, + DocumentTransition::Create(_) => None, DocumentTransition::Replace(_) => None, DocumentTransition::Delete(_) => None, DocumentTransition::Transfer(_) => None, @@ -119,12 +119,12 @@ impl DocumentTransitionWasm { #[wasm_bindgen(js_name=getReceiverId)] pub fn get_receiver_id(&self) -> Option { match &self.0 { - DocumentTransition::Create(create) => None, + DocumentTransition::Create(_) => None, DocumentTransition::Replace(_) => None, DocumentTransition::Delete(_) => None, DocumentTransition::Transfer(transfer) => Some(transfer.recipient_owner_id().into()), - DocumentTransition::UpdatePrice(update_price) => None, - DocumentTransition::Purchase(purchase) => None, + DocumentTransition::UpdatePrice(_) => None, + DocumentTransition::Purchase(_) => None, } } diff --git a/packages/wasm-dpp/src/metadata.rs b/packages/wasm-dpp/src/metadata.rs index ff4d1c65d77..4cd11b17235 100644 --- a/packages/wasm-dpp/src/metadata.rs +++ b/packages/wasm-dpp/src/metadata.rs @@ -3,10 +3,8 @@ pub use serde::Serialize; use wasm_bindgen::prelude::*; -use crate::utils::ToSerdeJSONExt; use dpp::metadata::Metadata; use dpp::util::deserializer::ProtocolVersion; -use dpp::util::json_value::JsonValueExt; #[wasm_bindgen(js_name=Metadata)] #[derive(Clone, Debug)] From 8831379c2a8279598e652df14447a8633f965c8f Mon Sep 17 00:00:00 2001 From: pshenmic Date: Tue, 25 Feb 2025 03:16:53 +0700 Subject: [PATCH 30/50] feat(wasm-dpp): fix cargo lint --- packages/wasm-dpp/src/document/factory.rs | 113 ++++++++++++++-------- packages/wasm-dpp/src/document/mod.rs | 2 +- 2 files changed, 74 insertions(+), 41 deletions(-) diff --git a/packages/wasm-dpp/src/document/factory.rs b/packages/wasm-dpp/src/document/factory.rs index d980fd9db13..eea4ab00886 100644 --- a/packages/wasm-dpp/src/document/factory.rs +++ b/packages/wasm-dpp/src/document/factory.rs @@ -15,14 +15,18 @@ use dpp::prelude::ExtendedDocument; use crate::document_batch_transition::DocumentsBatchTransitionWasm; use crate::entropy_generator::ExternalEntropyGenerator; -use crate::{identifier::identifier_from_js_value, utils::{IntoWasm, ToSerdeJSONExt, WithJsError}, DataContractWasm, ExtendedDocumentWasm}; +use crate::{ + identifier::identifier_from_js_value, + utils::{IntoWasm, ToSerdeJSONExt, WithJsError}, + DataContractWasm, ExtendedDocumentWasm, +}; use dpp::identifier::Identifier; +use dpp::platform_value::string_encoding::Encoding::Base58; use dpp::state_transition::documents_batch_transition::document_transition::action_type::DocumentTransitionActionType; use dpp::version::PlatformVersion; -use std::convert::TryFrom; use js_sys::Uint8Array; +use std::convert::TryFrom; use web_sys::console; -use dpp::platform_value::string_encoding::Encoding::Base58; #[wasm_bindgen(js_name=DocumentTransitions)] #[derive(Debug, Default)] @@ -156,11 +160,21 @@ impl DocumentFactoryWASM { let documents: Vec<( DocumentTransitionActionType, - Vec<(Document, Option, DocumentTypeRef, Bytes32)>, + Vec<( + Document, + Option, + DocumentTypeRef, + Bytes32, + )>, )> = documents_by_action .iter() .map(|(action_type, documents)| { - let documents_with_refs: Vec<(Document, Option, DocumentTypeRef, Bytes32)> = documents + let documents_with_refs: Vec<( + Document, + Option, + DocumentTypeRef, + Bytes32, + )> = documents .into_iter() .map(|(extended_document, document_params)| { ( @@ -181,10 +195,7 @@ impl DocumentFactoryWASM { let batch_transition = self .0 - .create_state_transition( - documents, - &mut nonce_counter, - ) + .create_state_transition(documents, &mut nonce_counter) .with_js_error()?; Ok(batch_transition.into()) @@ -277,11 +288,19 @@ impl DocumentFactoryWASM { // fn extract_documents_by_action( documents: &JsValue, -) -> Result)>>, JsValue> { +) -> Result< + HashMap< + DocumentTransitionActionType, + Vec<(ExtendedDocument, Option)>, + >, + JsValue, +> { check_actions(documents)?; - let mut documents_by_action: HashMap)>> = - Default::default(); + let mut documents_by_action: HashMap< + DocumentTransitionActionType, + Vec<(ExtendedDocument, Option)>, + > = Default::default(); let documents_create = extract_documents_of_action(documents, "create").with_js_error()?; let documents_replace = extract_documents_of_action(documents, "replace").with_js_error()?; @@ -333,7 +352,9 @@ fn extract_documents_of_action( let documents_submittable_with_action = js_sys::Reflect::get(documents, &action.to_string().into()).unwrap_or(JsValue::NULL); - if documents_submittable_with_action.is_null() || documents_submittable_with_action.is_undefined() { + if documents_submittable_with_action.is_null() + || documents_submittable_with_action.is_undefined() + { return Ok(vec![]); } @@ -343,37 +364,49 @@ fn extract_documents_of_action( documents_submittable_array .iter() .map(|js_document_submittable| { - let document = js_sys::Reflect::get(&js_document_submittable, &"document".into()).unwrap(); - - let params: Option = js_sys::Reflect::get(&js_document_submittable, &"params".to_string().into()).map(|js_value| { - if js_value.is_undefined() || js_value.is_null() { - return None - } - - let receiver_id = js_sys::Reflect::get(&js_value, &"receiver".to_string().into()).map(|js_value| { - if js_value.is_undefined() || js_value.is_null() { - return None - } - - let buffer = Uint8Array::new(&js_value); - let bytes = Identifier::from_vec(buffer.to_vec()).unwrap(); - - Some(bytes) - }).unwrap(); + let document = + js_sys::Reflect::get(&js_document_submittable, &"document".into()).unwrap(); + + let params: Option = + js_sys::Reflect::get(&js_document_submittable, &"params".to_string().into()) + .map(|js_value| { + if js_value.is_undefined() || js_value.is_null() { + return None; + } + + let receiver_id = + js_sys::Reflect::get(&js_value, &"receiver".to_string().into()) + .map(|js_value| { + if js_value.is_undefined() || js_value.is_null() { + return None; + } + + let buffer = Uint8Array::new(&js_value); + let bytes = Identifier::from_vec(buffer.to_vec()).unwrap(); + + Some(bytes) + }) + .unwrap(); - let price: Option = js_sys::Reflect::get(&js_value, &"price".to_string().into()).map(|js_value| { - if js_value.is_undefined() || js_value.is_null() { - return None - } + let price: Option = + js_sys::Reflect::get(&js_value, &"price".to_string().into()) + .map(|js_value| { + if js_value.is_undefined() || js_value.is_null() { + return None; + } - let price = u64::try_from(JsValue::from(&js_value)).unwrap(); + let price = u64::try_from(JsValue::from(&js_value)).unwrap(); - return Some(price); - }) - .unwrap_or(None); + return Some(price); + }) + .unwrap_or(None); - Some(DocumentTransitionParams { receiver: receiver_id, price: price.map(|e| e.clone()) }) - }).unwrap(); + Some(DocumentTransitionParams { + receiver: receiver_id, + price: price.map(|e| e.clone()), + }) + }) + .unwrap(); document .to_wasm::("ExtendedDocument") diff --git a/packages/wasm-dpp/src/document/mod.rs b/packages/wasm-dpp/src/document/mod.rs index e1f2272baed..60de8050371 100644 --- a/packages/wasm-dpp/src/document/mod.rs +++ b/packages/wasm-dpp/src/document/mod.rs @@ -14,7 +14,7 @@ use crate::utils::WithJsError; use crate::utils::{with_serde_to_json_value, ToSerdeJSONExt}; use dpp::document::document_methods::DocumentMethodsV0; -use dpp::document::{ DocumentV0Getters}; +use dpp::document::DocumentV0Getters; pub mod errors; pub use state_transition::*; pub mod document_facade; From 84382372c972a5b91dd79c469f6395656f1380c6 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Tue, 25 Feb 2025 03:22:28 +0700 Subject: [PATCH 31/50] chore(sdk): fix audit --- .yarnrc.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.yarnrc.yml b/.yarnrc.yml index 6abc82a3a7c..48e8ba682fd 100644 --- a/.yarnrc.yml +++ b/.yarnrc.yml @@ -24,6 +24,7 @@ npmAuditExcludePackages: - level-errors # TODO: Update leveldb - level-concat-iterator # TODO: Update leveldb - lodash.get # TODO: update sinon + - serialize-javascript # TODO: update mocha packageExtensions: "@dashevo/protobufjs@*": From 134f86dec99755a116b8395a1f37de869c8b9e27 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Tue, 25 Feb 2025 03:23:13 +0700 Subject: [PATCH 32/50] fix(rs-dpp): fmt lint fix --- .../src/document/document_factory/mod.rs | 13 +++--- .../src/document/document_factory/v0/mod.rs | 41 ++++++++++++++----- packages/rs-dpp/src/document/mod.rs | 4 +- 3 files changed, 41 insertions(+), 17 deletions(-) diff --git a/packages/rs-dpp/src/document/document_factory/mod.rs b/packages/rs-dpp/src/document/document_factory/mod.rs index 52f86e6dc87..d24989ddc81 100644 --- a/packages/rs-dpp/src/document/document_factory/mod.rs +++ b/packages/rs-dpp/src/document/document_factory/mod.rs @@ -9,9 +9,9 @@ use derive_more::From; use platform_value::{Bytes32, Identifier, Value}; use crate::data_contract::document_type::DocumentTypeRef; -use crate::document::{Document, DocumentTransitionParams}; #[cfg(feature = "extended-document")] use crate::document::ExtendedDocument; +use crate::document::{Document, DocumentTransitionParams}; #[cfg(feature = "state-transitions")] use crate::state_transition::documents_batch_transition::{ document_transition::action_type::DocumentTransitionActionType, DocumentsBatchTransition, @@ -116,15 +116,18 @@ impl DocumentFactory { documents_iter: impl IntoIterator< Item = ( DocumentTransitionActionType, - Vec<(Document, Option, DocumentTypeRef<'a>, Bytes32)>, + Vec<( + Document, + Option, + DocumentTypeRef<'a>, + Bytes32, + )>, ), >, nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce ) -> Result { match self { - DocumentFactory::V0(v0) => { - v0.create_state_transition(documents_iter, nonce_counter) - } + DocumentFactory::V0(v0) => v0.create_state_transition(documents_iter, nonce_counter), } } diff --git a/packages/rs-dpp/src/document/document_factory/v0/mod.rs b/packages/rs-dpp/src/document/document_factory/v0/mod.rs index db7a2ffab51..8a3cb9a9619 100644 --- a/packages/rs-dpp/src/document/document_factory/v0/mod.rs +++ b/packages/rs-dpp/src/document/document_factory/v0/mod.rs @@ -5,7 +5,9 @@ use crate::data_contract::document_type::DocumentTypeRef; use crate::data_contract::errors::DataContractError; use crate::data_contract::DataContract; use crate::document::errors::DocumentError; -use crate::document::{Document, DocumentTransitionParams, DocumentV0Getters, DocumentV0Setters, INITIAL_REVISION}; +use crate::document::{ + Document, DocumentTransitionParams, DocumentV0Getters, DocumentV0Setters, INITIAL_REVISION, +}; use chrono::Utc; use std::collections::BTreeMap; @@ -207,7 +209,12 @@ impl DocumentFactoryV0 { documents_iter: impl IntoIterator< Item = ( DocumentTransitionActionType, - Vec<(Document, Option, DocumentTypeRef<'a>, Bytes32)>, + Vec<( + Document, + Option, + DocumentTypeRef<'a>, + Bytes32, + )>, ), >, nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce @@ -215,7 +222,12 @@ impl DocumentFactoryV0 { let platform_version = PlatformVersion::get(self.protocol_version)?; let documents: Vec<( DocumentTransitionActionType, - Vec<(Document, Option, DocumentTypeRef, Bytes32)>, + Vec<( + Document, + Option, + DocumentTypeRef, + Bytes32, + )>, )> = documents_iter.into_iter().collect(); let mut flattened_documents_iter = documents.iter().flat_map(|(_, v)| v).peekable(); @@ -247,7 +259,7 @@ impl DocumentFactoryV0 { DocumentTransitionActionType::Create => Self::document_create_transitions( documents .into_iter() - .map(|(document, _, document_type, bytes,)| (document, document_type, bytes)) + .map(|(document, _, document_type, bytes)| (document, document_type, bytes)) .collect(), nonce_counter, platform_version, @@ -255,7 +267,7 @@ impl DocumentFactoryV0 { DocumentTransitionActionType::Delete => Self::document_delete_transitions( documents .into_iter() - .map(|(document, _, document_type, _,)| (document, document_type)) + .map(|(document, _, document_type, _)| (document, document_type)) .collect(), nonce_counter, platform_version, @@ -271,7 +283,9 @@ impl DocumentFactoryV0 { DocumentTransitionActionType::Transfer => Self::document_transfer_transitions( documents .into_iter() - .map(|(document, document_params, document_type, _)| (document, document_params.unwrap(), document_type)) + .map(|(document, document_params, document_type, _)| { + (document, document_params.unwrap(), document_type) + }) .collect(), nonce_counter, platform_version, @@ -280,7 +294,9 @@ impl DocumentFactoryV0 { Self::document_update_price_transitions( documents .into_iter() - .map(|(document, document_params, document_type, _)| (document, document_params.unwrap(), document_type)) + .map(|(document, document_params, document_type, _)| { + (document, document_params.unwrap(), document_type) + }) .collect(), nonce_counter, platform_version, @@ -289,7 +305,9 @@ impl DocumentFactoryV0 { DocumentTransitionActionType::Purchase => Self::document_purchase_transitions( documents .into_iter() - .map(|(document, document_params, document_type, _)| (document, document_params.unwrap(), document_type)) + .map(|(document, document_params, document_type, _)| { + (document, document_params.unwrap(), document_type) + }) .collect(), nonce_counter, platform_version, @@ -588,7 +606,7 @@ impl DocumentFactoryV0 { fn document_transfer_transitions( documents: Vec<(Document, DocumentTransitionParams, DocumentTypeRef)>, nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce - platform_version: &PlatformVersion + platform_version: &PlatformVersion, ) -> Result, ProtocolError> { documents .into_iter() @@ -690,7 +708,10 @@ impl DocumentFactoryV0 { }; let nonce = nonce_counter - .entry((document_params.receiver.unwrap(), document_type.data_contract_id())) + .entry(( + document_params.receiver.unwrap(), + document_type.data_contract_id(), + )) .or_default(); //document.set_owner_id(recipient.unwrap()); diff --git a/packages/rs-dpp/src/document/mod.rs b/packages/rs-dpp/src/document/mod.rs index 7adfe7f1c16..2edd1c1ea17 100644 --- a/packages/rs-dpp/src/document/mod.rs +++ b/packages/rs-dpp/src/document/mod.rs @@ -45,9 +45,9 @@ use derive_more::From; #[cfg(feature = "document-serde-conversion")] use serde::{Deserialize, Serialize}; +use platform_value::Identifier; use std::fmt; use std::fmt::Formatter; -use platform_value::Identifier; #[derive(Clone, Debug, PartialEq, From)] #[cfg_attr( @@ -63,7 +63,7 @@ pub enum Document { #[derive(Clone, Debug)] pub struct DocumentTransitionParams { pub receiver: Option, - pub price: Option + pub price: Option, } impl fmt::Display for Document { From e17ddda1629992a04d7f7eab377c5b8c585905c1 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Tue, 25 Feb 2025 03:32:48 +0700 Subject: [PATCH 33/50] fix(rs-dpp): clippy --- .../src/tests/fixtures/get_document_transitions_fixture.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/rs-dpp/src/tests/fixtures/get_document_transitions_fixture.rs b/packages/rs-dpp/src/tests/fixtures/get_document_transitions_fixture.rs index 9c78a2b2e6e..fa35253205d 100644 --- a/packages/rs-dpp/src/tests/fixtures/get_document_transitions_fixture.rs +++ b/packages/rs-dpp/src/tests/fixtures/get_document_transitions_fixture.rs @@ -4,7 +4,7 @@ use platform_value::{Bytes32, Identifier}; use platform_version::version::PlatformVersion; use std::collections::BTreeMap; -use crate::document::Document; +use crate::document::{Document, DocumentTransitionParams}; use crate::state_transition::documents_batch_transition::document_transition::action_type::DocumentTransitionActionType; use crate::state_transition::documents_batch_transition::document_transition::DocumentTransition; @@ -14,7 +14,7 @@ pub fn get_document_transitions_fixture<'a>( documents: impl IntoIterator< Item = ( DocumentTransitionActionType, - Vec<(Document, DocumentTypeRef<'a>, Bytes32)>, + Vec<(Document, Option, DocumentTypeRef<'a>, Bytes32)>, ), >, nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce @@ -24,7 +24,7 @@ pub fn get_document_transitions_fixture<'a>( DocumentFactory::new(protocol_version).expect("expected to get document factory"); document_factory - .create_state_transition(documents, nonce_counter, None, None) + .create_state_transition(documents, nonce_counter) .expect("the transitions should be created") .transitions() .to_owned() From 0e207f736da8b8225e117199c632c9b9877347fc Mon Sep 17 00:00:00 2001 From: pshenmic Date: Tue, 25 Feb 2025 03:36:59 +0700 Subject: [PATCH 34/50] fix(rs-dpp): fmt check --- .../src/tests/fixtures/get_document_transitions_fixture.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/rs-dpp/src/tests/fixtures/get_document_transitions_fixture.rs b/packages/rs-dpp/src/tests/fixtures/get_document_transitions_fixture.rs index fa35253205d..8d66b211fda 100644 --- a/packages/rs-dpp/src/tests/fixtures/get_document_transitions_fixture.rs +++ b/packages/rs-dpp/src/tests/fixtures/get_document_transitions_fixture.rs @@ -14,7 +14,12 @@ pub fn get_document_transitions_fixture<'a>( documents: impl IntoIterator< Item = ( DocumentTransitionActionType, - Vec<(Document, Option, DocumentTypeRef<'a>, Bytes32)>, + Vec<( + Document, + Option, + DocumentTypeRef<'a>, + Bytes32, + )>, ), >, nonce_counter: &mut BTreeMap<(Identifier, Identifier), u64>, //IdentityID/ContractID -> nonce From 57045732f3d76e82e28338f571f4977d36d8a42c Mon Sep 17 00:00:00 2001 From: pshenmic Date: Tue, 25 Feb 2025 03:38:45 +0700 Subject: [PATCH 35/50] fix(rs-dpp): fix test --- packages/rs-dpp/src/state_transition/serialization.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/rs-dpp/src/state_transition/serialization.rs b/packages/rs-dpp/src/state_transition/serialization.rs index c36ae53db4f..f371889eec1 100644 --- a/packages/rs-dpp/src/state_transition/serialization.rs +++ b/packages/rs-dpp/src/state_transition/serialization.rs @@ -331,6 +331,7 @@ mod tests { let data_contract = extended_document.data_contract(); ( document, + None, data_contract .document_type_for_name(extended_document.document_type_name()) .unwrap(), From 50b2a39cb273adfa4dbe79bdd6eb8e9f0bc76b39 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Tue, 25 Feb 2025 03:58:10 +0700 Subject: [PATCH 36/50] chore(sdk): cleanup --- .../Platform/methods/documents/broadcast.ts | 20 +++++++++---------- .../src/document/document_factory/v0/mod.rs | 1 - packages/rs-dpp/src/document/mod.rs | 2 +- .../document_transition/action_type.rs | 2 +- packages/wasm-dpp/src/document/factory.rs | 4 +--- 5 files changed, 12 insertions(+), 17 deletions(-) diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts index 0d2b9bf07d5..55d365455c7 100644 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts @@ -63,23 +63,21 @@ export default async function broadcast( throw new Error('Data contract ID is not found'); } - if (documents.transfer?.length && (documents.transfer - .some(({ params }) => !params?.receiver))) { + if (documents.transfer?.length && documents.transfer + .some(({ params }) => !params?.receiver)) { throw new Error('Receiver identity is not found for transfer transition'); } - if (documents.updatePrice?.length && (documents.updatePrice - .some(({ params }) => !params?.price))) { + if (documents.updatePrice?.length && documents.updatePrice + .some(({ params }) => !params?.price)) { throw new Error('Price must be provided for UpdatePrice operation'); } - if (documents.purchase?.length) { - if (documents.purchase?.length && (documents.purchase - .some(({ params }) => !params?.price && !params?.receiver))) { - throw new Error('Price must be provided for UpdatePrice operation'); - } - - documents.purchase.forEach(({ document, params }) => document.setOwnerId(params!.receiver)); + if (documents.purchase?.length && documents.purchase + .some(({ params }) => !params?.price && !params?.receiver)) { + throw new Error('Receiver and Price must be provided for UpdatePrice operation'); + } else { + documents.purchase!.forEach(({ document, params }) => document.setOwnerId(params!.receiver)); } const identityContractNonce = await this.nonceManager diff --git a/packages/rs-dpp/src/document/document_factory/v0/mod.rs b/packages/rs-dpp/src/document/document_factory/v0/mod.rs index 8a3cb9a9619..6a0987ef1f3 100644 --- a/packages/rs-dpp/src/document/document_factory/v0/mod.rs +++ b/packages/rs-dpp/src/document/document_factory/v0/mod.rs @@ -714,7 +714,6 @@ impl DocumentFactoryV0 { )) .or_default(); - //document.set_owner_id(recipient.unwrap()); document.increment_revision()?; document.set_updated_at(Some(Utc::now().timestamp_millis() as TimestampMillis)); diff --git a/packages/rs-dpp/src/document/mod.rs b/packages/rs-dpp/src/document/mod.rs index 2edd1c1ea17..8beec28744c 100644 --- a/packages/rs-dpp/src/document/mod.rs +++ b/packages/rs-dpp/src/document/mod.rs @@ -60,7 +60,7 @@ pub enum Document { V0(DocumentV0), } -#[derive(Clone, Debug)] +#[derive(Serialize, Deserialize)] pub struct DocumentTransitionParams { pub receiver: Option, pub price: Option, diff --git a/packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/action_type.rs b/packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/action_type.rs index afc2943983f..a0ea0011508 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/action_type.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/document/documents_batch_transition/document_transition/action_type.rs @@ -55,8 +55,8 @@ impl From for &str { DocumentTransitionActionType::Replace => "Replace", DocumentTransitionActionType::Delete => "Delete", DocumentTransitionActionType::Transfer => "Transfer", - DocumentTransitionActionType::Purchase => "Purchase", DocumentTransitionActionType::UpdatePrice => "UpdatePrice", + DocumentTransitionActionType::Purchase => "Purchase", DocumentTransitionActionType::IgnoreWhileBumpingRevision => { "IgnoreWhileBumpingRevision" } diff --git a/packages/wasm-dpp/src/document/factory.rs b/packages/wasm-dpp/src/document/factory.rs index eea4ab00886..cb2cd7be01a 100644 --- a/packages/wasm-dpp/src/document/factory.rs +++ b/packages/wasm-dpp/src/document/factory.rs @@ -21,12 +21,10 @@ use crate::{ DataContractWasm, ExtendedDocumentWasm, }; use dpp::identifier::Identifier; -use dpp::platform_value::string_encoding::Encoding::Base58; use dpp::state_transition::documents_batch_transition::document_transition::action_type::DocumentTransitionActionType; use dpp::version::PlatformVersion; use js_sys::Uint8Array; use std::convert::TryFrom; -use web_sys::console; #[wasm_bindgen(js_name=DocumentTransitions)] #[derive(Debug, Default)] @@ -399,7 +397,7 @@ fn extract_documents_of_action( return Some(price); }) - .unwrap_or(None); + .unwrap(); Some(DocumentTransitionParams { receiver: receiver_id, From 3b91adff70d0c661b42674506576e313f00f7e6c Mon Sep 17 00:00:00 2001 From: pshenmic Date: Tue, 25 Feb 2025 04:11:03 +0700 Subject: [PATCH 37/50] fix(wasm-dpp): fix unit test --- .../test/integration/document/DocumentFacade.spec.js | 2 +- .../stateTransition/StateTransitionFacade.spec.js | 2 +- .../wasm-dpp/test/unit/document/DocumentFactory.spec.js | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/wasm-dpp/test/integration/document/DocumentFacade.spec.js b/packages/wasm-dpp/test/integration/document/DocumentFacade.spec.js index 6ba89726f11..6b4f5a2ba5e 100644 --- a/packages/wasm-dpp/test/integration/document/DocumentFacade.spec.js +++ b/packages/wasm-dpp/test/integration/document/DocumentFacade.spec.js @@ -100,7 +100,7 @@ describe('DocumentFacade', () => { const contractId = documents[0].getDataContractId(); const result = dpp.document.createStateTransition({ - create: documents, + create: documents.map((d) => ({ document: d, params: null })), }, { [identityId.toString()]: { [contractId.toString()]: '1', diff --git a/packages/wasm-dpp/test/integration/stateTransition/StateTransitionFacade.spec.js b/packages/wasm-dpp/test/integration/stateTransition/StateTransitionFacade.spec.js index 76e5d81ca47..49bd3acbb0e 100644 --- a/packages/wasm-dpp/test/integration/stateTransition/StateTransitionFacade.spec.js +++ b/packages/wasm-dpp/test/integration/stateTransition/StateTransitionFacade.spec.js @@ -99,7 +99,7 @@ describe('StateTransitionFacade', () => { const documents = await getDocumentsFixture(dataContract); documentsBatchTransition = documentFactory.createStateTransition({ - create: documents, + create: documents.map((d) => ({ document: d, params: null })), }, { [documents[0].getOwnerId().toString()]: { [documents[0].getDataContractId().toString()]: '0', diff --git a/packages/wasm-dpp/test/unit/document/DocumentFactory.spec.js b/packages/wasm-dpp/test/unit/document/DocumentFactory.spec.js index 2ed208c04ee..ace54d99131 100644 --- a/packages/wasm-dpp/test/unit/document/DocumentFactory.spec.js +++ b/packages/wasm-dpp/test/unit/document/DocumentFactory.spec.js @@ -232,7 +232,7 @@ describe('DocumentFactory', () => { it('should throw and error if documents have unknown action', async () => { try { factory.createStateTransition({ - unknown: documents, + unknown: documents.map((d) => ({ document: d, params: null })), }, {}); expect.fail('Error was not thrown'); @@ -274,7 +274,7 @@ describe('DocumentFactory', () => { const expectedDocument = documents[0].toObject(); try { factory.createStateTransition({ - create: documents, + create: documents.map((d) => ({ document: d, params: null })), }); expect.fail('Error was not thrown'); } catch (e) { @@ -290,8 +290,8 @@ describe('DocumentFactory', () => { const identityId = newDocument.getOwnerId(); const stateTransition = factory.createStateTransition({ - create: documents, - replace: [newDocument], + create: documents.map((d) => ({ document: d, params: null })), + replace: [newDocument].map((d) => ({ document: d, params: null })), }, { [identityId.toString()]: { [dataContract.getId().toString()]: '1', From de035d540f0ff45569022a8a921bc570f0015f46 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Tue, 25 Feb 2025 04:26:21 +0700 Subject: [PATCH 38/50] fix(wasm-dpp): get back clone --- packages/rs-dpp/src/document/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/rs-dpp/src/document/mod.rs b/packages/rs-dpp/src/document/mod.rs index 8beec28744c..19212535280 100644 --- a/packages/rs-dpp/src/document/mod.rs +++ b/packages/rs-dpp/src/document/mod.rs @@ -60,7 +60,7 @@ pub enum Document { V0(DocumentV0), } -#[derive(Serialize, Deserialize)] +#[derive(Clone)] pub struct DocumentTransitionParams { pub receiver: Option, pub price: Option, From c225f9f60f011aee09e09eb72fcefaff2579a97b Mon Sep 17 00:00:00 2001 From: pshenmic Date: Tue, 25 Feb 2025 04:34:01 +0700 Subject: [PATCH 39/50] fix(rs-drive-abci): fix tests --- .../data_triggers/triggers/dashpay/v0/mod.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/documents_batch/data_triggers/triggers/dashpay/v0/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/documents_batch/data_triggers/triggers/dashpay/v0/mod.rs index b1b183ef24d..f1c117a5b34 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/documents_batch/data_triggers/triggers/dashpay/v0/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/documents_batch/data_triggers/triggers/dashpay/v0/mod.rs @@ -168,7 +168,7 @@ mod test { let document_transitions = get_document_transitions_fixture( [( DocumentTransitionActionType::Create, - vec![(contact_request_document, document_type, Bytes32::default())], + vec![(contact_request_document, None, document_type, Bytes32::default())], )], &mut nonce_counter, ); @@ -271,7 +271,7 @@ mod test { let document_transitions = get_document_transitions_fixture( [( DocumentTransitionActionType::Create, - vec![(contact_request_document, document_type, Bytes32::default())], + vec![(contact_request_document, None, document_type, Bytes32::default())], )], &mut nonce_counter, ); @@ -399,7 +399,7 @@ mod test { let document_transitions = get_document_transitions_fixture( [( DocumentTransitionActionType::Create, - vec![(contact_request_document, document_type, Bytes32::default())], + vec![(contact_request_document, None, document_type, Bytes32::default())], )], &mut nonce_counter, ); From a579bd5266319b113b3fb6e150690c6e0259bb92 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Tue, 25 Feb 2025 05:03:04 +0700 Subject: [PATCH 40/50] fix(rs-drive-abci): fix formatting --- .../data_triggers/triggers/dashpay/v0/mod.rs | 21 ++++++++++++++++--- .../data_triggers/triggers/dpns/v0/mod.rs | 2 +- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/documents_batch/data_triggers/triggers/dashpay/v0/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/documents_batch/data_triggers/triggers/dashpay/v0/mod.rs index f1c117a5b34..62867910925 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/documents_batch/data_triggers/triggers/dashpay/v0/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/documents_batch/data_triggers/triggers/dashpay/v0/mod.rs @@ -168,7 +168,12 @@ mod test { let document_transitions = get_document_transitions_fixture( [( DocumentTransitionActionType::Create, - vec![(contact_request_document, None, document_type, Bytes32::default())], + vec![( + contact_request_document, + None, + document_type, + Bytes32::default(), + )], )], &mut nonce_counter, ); @@ -271,7 +276,12 @@ mod test { let document_transitions = get_document_transitions_fixture( [( DocumentTransitionActionType::Create, - vec![(contact_request_document, None, document_type, Bytes32::default())], + vec![( + contact_request_document, + None, + document_type, + Bytes32::default(), + )], )], &mut nonce_counter, ); @@ -399,7 +409,12 @@ mod test { let document_transitions = get_document_transitions_fixture( [( DocumentTransitionActionType::Create, - vec![(contact_request_document, None, document_type, Bytes32::default())], + vec![( + contact_request_document, + None, + document_type, + Bytes32::default(), + )], )], &mut nonce_counter, ); diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/documents_batch/data_triggers/triggers/dpns/v0/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/documents_batch/data_triggers/triggers/dpns/v0/mod.rs index a790d727bd8..c12c941af16 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/documents_batch/data_triggers/triggers/dpns/v0/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/documents_batch/data_triggers/triggers/dpns/v0/mod.rs @@ -484,7 +484,7 @@ mod test { let transitions = get_document_transitions_fixture( [( DocumentTransitionActionType::Create, - vec![(document, document_type, Bytes32::default())], + vec![(document, None, document_type, Bytes32::default())], )], &mut nonce_counter, ); From 4ac03e1a0b09456b32483a49954a1502e30d7c82 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Tue, 25 Feb 2025 05:20:33 +0700 Subject: [PATCH 41/50] fix(js-dash-sdk): fix test --- packages/js-dash-sdk/src/SDK/Client/Client.spec.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/js-dash-sdk/src/SDK/Client/Client.spec.ts b/packages/js-dash-sdk/src/SDK/Client/Client.spec.ts index bc6fa96bd42..25765401c72 100644 --- a/packages/js-dash-sdk/src/SDK/Client/Client.spec.ts +++ b/packages/js-dash-sdk/src/SDK/Client/Client.spec.ts @@ -313,7 +313,7 @@ describe('Dash - Client', function suite() { let error; try { await client.platform.documents.broadcast({ - create: documentsFixture, + create: documentsFixture.map((d) => ({ document: d, params: null })), }, identityFixture); } catch (e) { error = e; @@ -332,7 +332,7 @@ describe('Dash - Client', function suite() { dapiClientMock.platform.waitForStateTransitionResult.resolves(proofResponse); await client.platform.documents.broadcast({ - create: documentsFixture, + create: documentsFixture.map((d) => ({ document: d, params: null })), }, identityFixture); const serializedSt = dapiClientMock.platform.broadcastStateTransition.getCall(0).args[0]; From f19a9a435101c32c7a4663ae874f0aa416437930 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Tue, 25 Feb 2025 05:52:48 +0700 Subject: [PATCH 42/50] fix(js-dash-sdk): fix broadcast condition --- .../Client/Platform/methods/documents/broadcast.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts index 55d365455c7..10e3687c932 100644 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts @@ -73,11 +73,13 @@ export default async function broadcast( throw new Error('Price must be provided for UpdatePrice operation'); } - if (documents.purchase?.length && documents.purchase - .some(({ params }) => !params?.price && !params?.receiver)) { - throw new Error('Receiver and Price must be provided for UpdatePrice operation'); - } else { - documents.purchase!.forEach(({ document, params }) => document.setOwnerId(params!.receiver)); + if (documents.purchase?.length) { + if (documents.purchase + .some(({ params }) => !params?.price || !params?.receiver)) { + throw new Error('Receiver and Price must be provided for UpdatePrice operation'); + } else { + documents.purchase.forEach(({ document, params }) => document.setOwnerId(params!.receiver)); + } } const identityContractNonce = await this.nonceManager From 857a4463ceff3b8236218a2be5687d768f74db63 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Wed, 26 Feb 2025 02:27:34 +0700 Subject: [PATCH 43/50] fix(platform-test-suite): fix e2e tests --- .../Client/Platform/methods/names/register.ts | 4 ++-- .../test/e2e/contacts.spec.js | 12 ++++++------ .../platform-test-suite/test/e2e/dpns.spec.js | 2 +- .../test/e2e/withdrawals.spec.js | 8 ++++---- .../functional/platform/DataContract.spec.js | 2 +- .../test/functional/platform/Document.spec.js | 16 ++++++++-------- .../test/functional/platform/Identity.spec.js | 4 ++-- .../functional/platform/featureFlags.spec.js | 4 ++-- 8 files changed, 26 insertions(+), 26 deletions(-) diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/names/register.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/names/register.ts index 07f6576e782..6bb0cc964a3 100644 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/names/register.ts +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/names/register.ts @@ -74,7 +74,7 @@ export async function register( await this.documents.broadcast( { - create: [preorderDocument], + create: [{ document: preorderDocument }], }, identity, ); @@ -99,7 +99,7 @@ export async function register( // 4. Create and send domain state transition await this.documents.broadcast( { - create: [domainDocument], + create: [{ document: domainDocument }], }, identity, ); diff --git a/packages/platform-test-suite/test/e2e/contacts.spec.js b/packages/platform-test-suite/test/e2e/contacts.spec.js index fe8eaf2fced..14be962f707 100644 --- a/packages/platform-test-suite/test/e2e/contacts.spec.js +++ b/packages/platform-test-suite/test/e2e/contacts.spec.js @@ -145,7 +145,7 @@ describe('e2e', () => { }); await bobClient.platform.documents.broadcast({ - create: [profile], + create: [{ document: profile }], }, bobIdentity); // Additional wait time to mitigate testnet latency @@ -244,7 +244,7 @@ describe('e2e', () => { }); await aliceClient.platform.documents.broadcast({ - create: [aliceProfile], + create: [{ document: aliceProfile }], }, aliceIdentity); // Additional wait time to mitigate testnet latency @@ -265,7 +265,7 @@ describe('e2e', () => { // 2. Broadcast change await aliceClient.platform.documents.broadcast({ - replace: [aliceProfile], + replace: [{ document: aliceProfile }], }, aliceIdentity); // Additional wait time to mitigate testnet latency @@ -299,7 +299,7 @@ describe('e2e', () => { }); await bobClient.platform.documents.broadcast({ - create: [bobContactRequest], + create: [{ document: bobContactRequest }], }, bobIdentity); // Additional wait time to mitigate testnet latency @@ -324,7 +324,7 @@ describe('e2e', () => { }); await aliceClient.platform.documents.broadcast({ - create: [aliceContactAcceptance], + create: [{ document: aliceContactAcceptance }], }, aliceIdentity); // Additional wait time to mitigate testnet latency @@ -344,7 +344,7 @@ describe('e2e', () => { it('should be able to remove contact approval', async () => { // 1. Broadcast document deletion await aliceClient.platform.documents.broadcast({ - delete: [aliceContactAcceptance], + delete: [{ document: aliceContactAcceptance }], }, aliceIdentity); // Additional wait time to mitigate testnet latency diff --git a/packages/platform-test-suite/test/e2e/dpns.spec.js b/packages/platform-test-suite/test/e2e/dpns.spec.js index 786f583f873..12107e24885 100644 --- a/packages/platform-test-suite/test/e2e/dpns.spec.js +++ b/packages/platform-test-suite/test/e2e/dpns.spec.js @@ -260,7 +260,7 @@ describe('DPNS', () => { try { await client.platform.documents.broadcast({ - delete: [registeredDomain], + delete: [{ document: registeredDomain }], }, identity); } catch (e) { broadcastError = e; diff --git a/packages/platform-test-suite/test/e2e/withdrawals.spec.js b/packages/platform-test-suite/test/e2e/withdrawals.spec.js index b7afc0fb2c7..a19968f158e 100644 --- a/packages/platform-test-suite/test/e2e/withdrawals.spec.js +++ b/packages/platform-test-suite/test/e2e/withdrawals.spec.js @@ -114,7 +114,7 @@ describe('Withdrawals', function withdrawalsTest() { // Should allow deleting of the withdrawal document await client.platform.documents.broadcast({ - delete: [withdrawalDocument], + delete: [{ document: withdrawalDocument }], }, identity); }); @@ -216,7 +216,7 @@ describe('Withdrawals', function withdrawalsTest() { try { await client.platform.documents.broadcast({ - create: [withdrawal], + create: [{ document: withdrawal }], }, identity); expect.fail('should throw broadcast error'); @@ -260,7 +260,7 @@ describe('Withdrawals', function withdrawalsTest() { try { await client.platform.documents.broadcast({ - delete: [withdrawalDocument], + delete: [{ document: withdrawalDocument }], }, identity); expect.fail('should throw broadcast error'); @@ -283,7 +283,7 @@ describe('Withdrawals', function withdrawalsTest() { try { await client.platform.documents.broadcast({ - replace: [withdrawalDocument], + replace: [{ document: withdrawalDocument }], }, identity); expect.fail('should throw broadcast error'); diff --git a/packages/platform-test-suite/test/functional/platform/DataContract.spec.js b/packages/platform-test-suite/test/functional/platform/DataContract.spec.js index 28fe50b14ec..3d29c5add32 100644 --- a/packages/platform-test-suite/test/functional/platform/DataContract.spec.js +++ b/packages/platform-test-suite/test/functional/platform/DataContract.spec.js @@ -206,7 +206,7 @@ describe('Platform', () => { ); await client.platform.documents.broadcast({ - create: [document], + create: [{ document }], }, identity); // Additional wait time to mitigate testnet latency diff --git a/packages/platform-test-suite/test/functional/platform/Document.spec.js b/packages/platform-test-suite/test/functional/platform/Document.spec.js index 85f9abf963a..5ddb3ce5618 100644 --- a/packages/platform-test-suite/test/functional/platform/Document.spec.js +++ b/packages/platform-test-suite/test/functional/platform/Document.spec.js @@ -101,7 +101,7 @@ describe('Platform', () => { try { await client.platform.documents.broadcast({ - create: [newDocument], + create: [{ document: newDocument }], }, identity); } catch (e) { broadcastError = e; @@ -134,7 +134,7 @@ describe('Platform', () => { try { await client.platform.documents.broadcast({ - create: [document], + create: [{ document }], }, unknownIdentity); } catch (e) { broadcastError = e; @@ -165,7 +165,7 @@ describe('Platform', () => { ); await client.platform.documents.broadcast({ - create: [firstDocument], + create: [{ document: firstDocument }], }, identity); // Additional wait time to mitigate testnet latency @@ -184,7 +184,7 @@ describe('Platform', () => { try { await client.platform.documents.broadcast({ - create: [secondDocument], + create: [{ document: secondDocument }], }, identity); } catch (e) { broadcastError = e; @@ -213,7 +213,7 @@ describe('Platform', () => { ); await client.platform.documents.broadcast({ - create: [document], + create: [{ document }], }, identity); // Additional wait time to mitigate testnet latency @@ -262,7 +262,7 @@ describe('Platform', () => { storedDocument.set('firstName', 'updatedName'); await client.platform.documents.broadcast({ - replace: [storedDocument], + replace: [{ document: storedDocument }], }, identity); // Additional wait time to mitigate testnet latency @@ -292,7 +292,7 @@ describe('Platform', () => { storedDocument.set('firstName', 'updatedName'); const documentsBatchTransition = await client.platform.documents.broadcast({ - replace: [storedDocument], + replace: [{ document: storedDocument }], }, identity); // Additional wait time to mitigate testnet latency @@ -368,7 +368,7 @@ describe('Platform', () => { it('should be able to delete a document', async () => { await client.platform.documents.broadcast({ - delete: [document], + delete: [{ document }], }, identity); await waitForSTPropagated(); diff --git a/packages/platform-test-suite/test/functional/platform/Identity.spec.js b/packages/platform-test-suite/test/functional/platform/Identity.spec.js index 8f5e8994c40..fb2a76b8f90 100644 --- a/packages/platform-test-suite/test/functional/platform/Identity.spec.js +++ b/packages/platform-test-suite/test/functional/platform/Identity.spec.js @@ -358,7 +358,7 @@ describe('Platform', () => { try { await client.platform.documents.broadcast({ - create: [document], + create: [{ document }], }, lowBalanceIdentity); } catch (e) { broadcastError = e; @@ -445,7 +445,7 @@ describe('Platform', () => { ); await client.platform.documents.broadcast({ - create: [document], + create: [{ document }], }, identity); // Additional wait time to mitigate testnet latency diff --git a/packages/platform-test-suite/test/functional/platform/featureFlags.spec.js b/packages/platform-test-suite/test/functional/platform/featureFlags.spec.js index 2325a8ac7b1..b024c93bad5 100644 --- a/packages/platform-test-suite/test/functional/platform/featureFlags.spec.js +++ b/packages/platform-test-suite/test/functional/platform/featureFlags.spec.js @@ -103,12 +103,12 @@ describe.skip('Platform', () => { ); await ownerClient.platform.documents.broadcast({ - create: [documentUpdate], + create: [{ document: documentUpdate }], }, identity); // forcing creation of additional block (enableAtHeight + 1) await ownerClient.platform.documents.broadcast({ - create: [documentRevert], + create: [{ document: documentRevert }], }, identity); // forcing creation of additional block (enableAtHeight + 2) From 5fc6eb47a19490870348bd370c8bbd3fa4c66f3c Mon Sep 17 00:00:00 2001 From: pshenmic Date: Thu, 27 Feb 2025 14:44:07 +0700 Subject: [PATCH 44/50] fix(wasm-dpp): merge fixes --- packages/rs-dpp/src/document/document_factory/v0/mod.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/rs-dpp/src/document/document_factory/v0/mod.rs b/packages/rs-dpp/src/document/document_factory/v0/mod.rs index cea1949b4d2..51a0fe6ee0d 100644 --- a/packages/rs-dpp/src/document/document_factory/v0/mod.rs +++ b/packages/rs-dpp/src/document/document_factory/v0/mod.rs @@ -30,13 +30,12 @@ use crate::state_transition::batch_transition::{ batched_transition::{ document_transition_action_type::DocumentTransitionActionType, DocumentCreateTransition, DocumentDeleteTransition, - DocumentReplaceTransition, DocumentTransferTransition, - DocumentUpdatePriceTransition, DocumentPurchaseTransition, - DocumentTransferTransition, DocumentTransition, DocumentUpdatePriceTransition, + DocumentReplaceTransition, DocumentPurchaseTransition, }, BatchTransition, BatchTransitionV0, }; use itertools::Itertools; +use crate::state_transition::batch_transition::batched_transition::{DocumentTransferTransition, DocumentUpdatePriceTransition}; #[cfg(feature = "state-transitions")] use crate::state_transition::state_transitions::document::batch_transition::batched_transition::document_transition::DocumentTransition; From 05b6f66483f582acdfef9529e7bd1bfdfc823887 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Thu, 27 Feb 2025 14:48:28 +0700 Subject: [PATCH 45/50] fix(rs-dpp): missing import --- .../src/tests/fixtures/get_document_transitions_fixture.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/rs-dpp/src/tests/fixtures/get_document_transitions_fixture.rs b/packages/rs-dpp/src/tests/fixtures/get_document_transitions_fixture.rs index 5c767f1ffa3..815359a872a 100644 --- a/packages/rs-dpp/src/tests/fixtures/get_document_transitions_fixture.rs +++ b/packages/rs-dpp/src/tests/fixtures/get_document_transitions_fixture.rs @@ -4,7 +4,7 @@ use platform_value::{Bytes32, Identifier}; use platform_version::version::PlatformVersion; use std::collections::BTreeMap; -use crate::document::Document; +use crate::document::{Document, DocumentTransitionParams}; use crate::state_transition::batch_transition::accessors::DocumentsBatchTransitionAccessorsV0; use crate::state_transition::batch_transition::batched_transition::BatchedTransition; use crate::state_transition::batch_transition::batched_transition::document_transition_action_type::DocumentTransitionActionType; From fb363c98dc5c17b486f69db8174a4f84a78538b4 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Thu, 27 Feb 2025 15:03:14 +0700 Subject: [PATCH 46/50] fix(rs-dpp): fix features --- packages/rs-dpp/src/document/document_factory/v0/mod.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/rs-dpp/src/document/document_factory/v0/mod.rs b/packages/rs-dpp/src/document/document_factory/v0/mod.rs index 51a0fe6ee0d..795f93aae57 100644 --- a/packages/rs-dpp/src/document/document_factory/v0/mod.rs +++ b/packages/rs-dpp/src/document/document_factory/v0/mod.rs @@ -35,9 +35,8 @@ use crate::state_transition::batch_transition::{ BatchTransition, BatchTransitionV0, }; use itertools::Itertools; -use crate::state_transition::batch_transition::batched_transition::{DocumentTransferTransition, DocumentUpdatePriceTransition}; #[cfg(feature = "state-transitions")] -use crate::state_transition::state_transitions::document::batch_transition::batched_transition::document_transition::DocumentTransition; +use crate::state_transition::state_transitions::document::batch_transition::batched_transition::{DocumentTransition, DocumentTransferTransition, DocumentUpdatePriceTransition}; const PROPERTY_FEATURE_VERSION: &str = "$version"; const PROPERTY_ENTROPY: &str = "$entropy"; From 9a7593873e3bb2202d7b06560e453adb1ad16160 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Thu, 27 Feb 2025 15:18:43 +0700 Subject: [PATCH 47/50] fix(rs-dpp): fix features --- packages/rs-dpp/src/document/document_factory/v0/mod.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/rs-dpp/src/document/document_factory/v0/mod.rs b/packages/rs-dpp/src/document/document_factory/v0/mod.rs index 795f93aae57..9156b95aa9f 100644 --- a/packages/rs-dpp/src/document/document_factory/v0/mod.rs +++ b/packages/rs-dpp/src/document/document_factory/v0/mod.rs @@ -36,7 +36,8 @@ use crate::state_transition::batch_transition::{ }; use itertools::Itertools; #[cfg(feature = "state-transitions")] -use crate::state_transition::state_transitions::document::batch_transition::batched_transition::{DocumentTransition, DocumentTransferTransition, DocumentUpdatePriceTransition}; +use crate::state_transition::batch_transition::batched_transition::document_transition::DocumentTransition; +use crate::state_transition::state_transitions::document::batch_transition::batched_transition::{DocumentTransferTransition, DocumentUpdatePriceTransition}; const PROPERTY_FEATURE_VERSION: &str = "$version"; const PROPERTY_ENTROPY: &str = "$entropy"; From c15202b131d8b138a8e273b2fa731f3d29d47d5f Mon Sep 17 00:00:00 2001 From: pshenmic Date: Thu, 27 Feb 2025 15:25:54 +0700 Subject: [PATCH 48/50] fix(rs-dpp): lint fix --- .../src/document/document_factory/v0/mod.rs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/packages/rs-dpp/src/document/document_factory/v0/mod.rs b/packages/rs-dpp/src/document/document_factory/v0/mod.rs index 9156b95aa9f..45c2f377703 100644 --- a/packages/rs-dpp/src/document/document_factory/v0/mod.rs +++ b/packages/rs-dpp/src/document/document_factory/v0/mod.rs @@ -22,22 +22,23 @@ use crate::document::document_methods::DocumentMethodsV0; #[cfg(feature = "extended-document")] use crate::document::{ extended_document::v0::ExtendedDocumentV0, - ExtendedDocument, serialization_traits::DocumentPlatformConversionMethodsV0, + serialization_traits::DocumentPlatformConversionMethodsV0, ExtendedDocument, }; use crate::prelude::{BlockHeight, CoreBlockHeight, TimestampMillis}; #[cfg(feature = "state-transitions")] +use crate::state_transition::batch_transition::batched_transition::document_transition::DocumentTransition; +#[cfg(feature = "state-transitions")] use crate::state_transition::batch_transition::{ batched_transition::{ - document_transition_action_type::DocumentTransitionActionType, - DocumentCreateTransition, DocumentDeleteTransition, - DocumentReplaceTransition, DocumentPurchaseTransition, + document_transition_action_type::DocumentTransitionActionType, DocumentCreateTransition, + DocumentDeleteTransition, DocumentPurchaseTransition, DocumentReplaceTransition, }, BatchTransition, BatchTransitionV0, }; +use crate::state_transition::state_transitions::document::batch_transition::batched_transition::{ + DocumentTransferTransition, DocumentUpdatePriceTransition, +}; use itertools::Itertools; -#[cfg(feature = "state-transitions")] -use crate::state_transition::batch_transition::batched_transition::document_transition::DocumentTransition; -use crate::state_transition::state_transitions::document::batch_transition::batched_transition::{DocumentTransferTransition, DocumentUpdatePriceTransition}; const PROPERTY_FEATURE_VERSION: &str = "$version"; const PROPERTY_ENTROPY: &str = "$entropy"; From d4f62e7e1601fd7b9baf01e148b88b2854123039 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Thu, 27 Feb 2025 15:29:00 +0700 Subject: [PATCH 49/50] fix(js-dash-sdk): fix logging name --- .../src/SDK/Client/Platform/methods/documents/broadcast.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts index 10e3687c932..3b899de321b 100644 --- a/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts +++ b/packages/js-dash-sdk/src/SDK/Client/Platform/methods/documents/broadcast.ts @@ -65,7 +65,7 @@ export default async function broadcast( if (documents.transfer?.length && documents.transfer .some(({ params }) => !params?.receiver)) { - throw new Error('Receiver identity is not found for transfer transition'); + throw new Error('Receiver Identity is not found for Transfer transition'); } if (documents.updatePrice?.length && documents.updatePrice @@ -76,7 +76,7 @@ export default async function broadcast( if (documents.purchase?.length) { if (documents.purchase .some(({ params }) => !params?.price || !params?.receiver)) { - throw new Error('Receiver and Price must be provided for UpdatePrice operation'); + throw new Error('Receiver and Price must be provided for Purchase operation'); } else { documents.purchase.forEach(({ document, params }) => document.setOwnerId(params!.receiver)); } From 51d1ee827b32e9568cb3e63925f5263c64e68089 Mon Sep 17 00:00:00 2001 From: pshenmic Date: Thu, 27 Feb 2025 16:23:01 +0700 Subject: [PATCH 50/50] fix(dapi): fix unit test --- .../drive/fetchProofForStateTransitionFactory.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/dapi/test/unit/externalApis/drive/fetchProofForStateTransitionFactory.spec.js b/packages/dapi/test/unit/externalApis/drive/fetchProofForStateTransitionFactory.spec.js index eae636a6bc3..442c41e3f86 100644 --- a/packages/dapi/test/unit/externalApis/drive/fetchProofForStateTransitionFactory.spec.js +++ b/packages/dapi/test/unit/externalApis/drive/fetchProofForStateTransitionFactory.spec.js @@ -109,7 +109,7 @@ describe('fetchProofForStateTransition', () => { const contractId = documents[0].getDataContractId(); const transition = dpp.document.createStateTransition({ - create: documents, + create: documents.map((d) => ({ document: d })), }, { [identityId.toString()]: { [contractId.toString()]: '1',