Skip to content

Commit

Permalink
feat(js-sdk): implement working document transfers
Browse files Browse the repository at this point in the history
  • Loading branch information
pshenmic committed Dec 24, 2024
1 parent 10998f7 commit fbe5dbc
Show file tree
Hide file tree
Showing 7 changed files with 83 additions and 61 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,27 @@ 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,
documents: {
create?: ExtendedDocument[],
replace?: ExtendedDocument[],
delete?: ExtendedDocument[],
transfer?: ExtendedDocument[]
},
identity: any,
keyIndex : number,
): Promise<any> {
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();

Expand All @@ -38,7 +37,6 @@ export default async function broadcast(
...(documents.create || []),
...(documents.replace || []),
...(documents.delete || []),
...(documents.transfer || []),
][0]?.getDataContractId();

if (!dataContractId) {
Expand All @@ -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);
Expand All @@ -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;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,40 +1,34 @@
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 {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<any> {
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;
20 changes: 18 additions & 2 deletions packages/rs-dpp/src/document/document_factory/v0/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Result<Vec<_>, ProtocolError>>()?
.into_iter()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Result<Vec<_>, ProtocolError>>()?
.into_iter()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -720,7 +720,7 @@ impl DocumentsBatchTransitionInternalTransformerV0 for DocumentsBatchTransition
StateError::InvalidDocumentRevisionError(InvalidDocumentRevisionError::new(
document_id,
Some(previous_revision),
transition_revision,
expected_revision,
)),
))
}
Expand Down
36 changes: 32 additions & 4 deletions packages/wasm-dpp/src/document/extended_document.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -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;
Expand Down Expand Up @@ -235,6 +236,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<js_sys::Date>) {
self.0
Expand Down
Original file line number Diff line number Diff line change
@@ -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)]
Expand Down

0 comments on commit fbe5dbc

Please sign in to comment.