Skip to content

Commit

Permalink
fix(js-dash-sdk): finalize nft transitions
Browse files Browse the repository at this point in the history
  • Loading branch information
pshenmic committed Jan 31, 2025
1 parent dac6932 commit b7da382
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 25 deletions.
Original file line number Diff line number Diff line change
@@ -1,35 +1,44 @@
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,
documents: {
create?: ExtendedDocument[],
replace?: ExtendedDocument[],
delete?: ExtendedDocument[],
transfer?: ExtendedDocument[]
transfer?: ExtendedDocument[],
updatePrice?: ExtendedDocument[],
purchase?: ExtendedDocument[],
},
identity: any,
options: any,
options?: DocumentTransitionParams,
): Promise<any> {
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();

Expand All @@ -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,
},
}, options.recipient, options.price);
};

const documentsBatchTransition = dpp.document.createStateTransition(
documents,
identityNonceObj,
options?.receiver,
options?.price,
);

this.logger.silly('[Document#broadcast] Created documents batch transition');

Expand Down
53 changes: 37 additions & 16 deletions packages/rs-dpp/src/document/document_factory/v0/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ impl DocumentFactoryV0 {
.collect(),
nonce_counter,
platform_version,
recipient.unwrap()
recipient
),
DocumentTransitionActionType::UpdatePrice => Self::document_update_price_transitions(
documents
Expand All @@ -282,7 +282,7 @@ impl DocumentFactoryV0 {
.collect(),
nonce_counter,
platform_version,
price.unwrap()
price
),
DocumentTransitionActionType::Purchase => Self::document_purchase_transitions(
documents
Expand All @@ -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::<Result<Vec<_>, ProtocolError>>()?
.into_iter()
Expand Down Expand Up @@ -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<Identifier>
) -> Result<Vec<DocumentTransition>, 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),
Expand All @@ -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,
Expand All @@ -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<Credits>
) -> Result<Vec<DocumentTransition>, 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),
Expand All @@ -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,
Expand All @@ -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<Credits>,
recipient: Option<Identifier>
) -> Result<Vec<DocumentTransition>, 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),
Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,26 @@ impl TryFrom<&str> for DocumentTransitionActionType {
"replace" => Ok(DocumentTransitionActionType::Replace),
"delete" => Ok(DocumentTransitionActionType::Delete),
"transfer" => Ok(DocumentTransitionActionType::Transfer),
"updatePrice" => Ok(DocumentTransitionActionType::UpdatePrice),
"purchase" => Ok(DocumentTransitionActionType::Purchase),
action_type => Err(ProtocolError::Generic(format!(
"unknown action type {action_type}"
))),
}
}
}


impl From<DocumentTransitionActionType> 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"
}
}
}

0 comments on commit b7da382

Please sign in to comment.