Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add token transitions to SDK and DAPI #2434

Merged
merged 12 commits into from
Jan 27, 2025
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,21 @@ const {
GetProofsRequest,
},
} = require('@dashevo/dapi-grpc');
const { StateTransitionTypes } = require('@dashevo/wasm-dpp');

const {
StateTransitionTypes,
TokenTransition,
DocumentTransition,
TokenTransitionType,
} = require('@dashevo/wasm-dpp');
const { GetDataContractRequest } = require('@dashevo/dapi-grpc/clients/platform/v0/web/platform_pb');

/**
* @param {PlatformPromiseClient} driveClient
* @param {DashPlatformProtocol} dpp
* @return {fetchProofForStateTransition}
*/
function fetchProofForStateTransitionFactory(driveClient) {
function fetchProofForStateTransitionFactory(driveClient, dpp) {
/**
* @typedef {fetchProofForStateTransition}
* @param {AbstractStateTransition} stateTransition
Expand All @@ -22,25 +30,160 @@ function fetchProofForStateTransitionFactory(driveClient) {

const requestV0 = new GetProofsRequestV0();

let dataContractsCache = {};

if (stateTransition.isDocumentStateTransition()) {
const { DocumentRequest } = GetProofsRequestV0;
const {
DocumentRequest,
IdentityTokenBalanceRequest,
IdentityTokenInfoRequest,
TokenStatusRequest,
} = GetProofsRequestV0;

const documentsList = stateTransition.getTransitions().map((documentTransition) => {
const documentRequest = new DocumentRequest();
documentRequest.setContractId(documentTransition.getDataContractId().toBuffer());
documentRequest.setDocumentType(documentTransition.getType());
documentRequest.setDocumentId(documentTransition.getId().toBuffer());
const documentsList = [];
const identityTokenBalancesList = [];
const identityTokenInfosList = [];
const tokenStatusesList = [];

const status = documentTransition.hasPrefundedBalance()
? DocumentRequest.DocumentContestedStatus.CONTESTED
: DocumentRequest.DocumentContestedStatus.NOT_CONTESTED;
for (const batchedTransition of stateTransition.getTransitions()) {
if (batchedTransition instanceof TokenTransition) {
switch (batchedTransition.getTransitionType()) {
case TokenTransitionType.Burn: {
const request = new IdentityTokenBalanceRequest({
tokenId: batchedTransition.getTokenId()
.toBuffer(),
identityId: stateTransition.getOwnerId()
.toBuffer(),
});

documentRequest.setDocumentContestedStatus(status);
identityTokenBalancesList.push(request);
break;
}
case TokenTransitionType.Mint: {
// Fetch data contract to determine correct recipient identity
const dataContractId = batchedTransition.getDataContractId();
const dataContractIdString = dataContractId.toString();

return documentRequest;
});
if (!dataContractsCache[dataContractIdString]) {
const dataContractRequestV0 = new GetDataContractRequest.GetDataContractRequestV0({
id: dataContractId.toBuffer(),
});

const dataContractRequest = new GetDataContractRequest();
dataContractRequest.setV0(dataContractRequestV0);

const dataContractResponse = await driveClient.getDataContract(dataContractRequest);

const dataContractBuffer = Buffer.from(
dataContractResponse.getV0().getDataContract_asU8(),
);

dataContractsCache[dataContractIdString] = await dpp.dataContract
.createFromBuffer(dataContractBuffer);
}

const dataContract = dataContractsCache[dataContractIdString];

const tokenConfiguration = dataContract.getTokenConfiguration(
batchedTransition.getTokenContractPosition(),
);

const request = new IdentityTokenBalanceRequest({
tokenId: batchedTransition.getTokenId()
.toBuffer(),
identityId: batchedTransition.toTransition().getRecipientId(tokenConfiguration)
.toBuffer(),
});

identityTokenBalancesList.push(request);
break;
}
case TokenTransitionType.Transfer: {
const requestSender = new IdentityTokenBalanceRequest({
tokenId: batchedTransition.getTokenId()
.toBuffer(),
identityId: stateTransition.getOwnerId().toBuffer(),
});

const requestRecipient = new IdentityTokenBalanceRequest({
tokenId: batchedTransition.getTokenId()
.toBuffer(),
identityId: batchedTransition.toTransition().getRecipientId()
.toBuffer(),
});

identityTokenBalancesList.push(requestSender, requestRecipient);
break;
}
case TokenTransitionType.DestroyFrozenFunds: {
const request = new IdentityTokenBalanceRequest({
tokenId: batchedTransition.getTokenId()
.toBuffer(),
identityId: batchedTransition.toTransition().getFrozenIdentityId()
.toBuffer(),
});

identityTokenBalancesList.push(request);
break;
}
case TokenTransitionType.EmergencyAction:
{
const request = new TokenStatusRequest({
tokenId: batchedTransition.getTokenId()
.toBuffer(),
});

requestV0.setDocumentsList(documentsList);
tokenStatusesList.push(request);
break;
}
case TokenTransitionType.Freeze:
case TokenTransitionType.Unfreeze: {
const request = new IdentityTokenInfoRequest({
tokenId: batchedTransition.getTokenId()
.toBuffer(),
identityId: batchedTransition.toTransition().getFrozenIdentityId()
.toBuffer(),
});

identityTokenInfosList.push(request);
break;
}
default:
throw new Error(`Unsupported token transition type ${batchedTransition.getTransitionType()}`);
}
} else if (batchedTransition instanceof DocumentTransition) {
const documentRequest = new DocumentRequest();
documentRequest.setContractId(batchedTransition.getDataContractId().toBuffer());
documentRequest.setDocumentType(batchedTransition.getType());
documentRequest.setDocumentId(batchedTransition.getId().toBuffer());

const status = batchedTransition.hasPrefundedBalance()
? DocumentRequest.DocumentContestedStatus.CONTESTED
: DocumentRequest.DocumentContestedStatus.NOT_CONTESTED;

documentRequest.setDocumentContestedStatus(status);

documentsList.push(documentRequest);
} else {
throw new Error(`Unsupported batched transition type ${batchedTransition.constructor.name}`);
}
}

if (documentsList.length > 0) {
requestV0.setDocumentsList(documentsList);
}

if (identityTokenBalancesList.length > 0) {
requestV0.setIdentityTokenBalancesList(identityTokenBalancesList);
}

if (identityTokenInfosList.length > 0) {
requestV0.setIdentityTokenInfosList(identityTokenInfosList);
}

if (tokenStatusesList.length > 0) {
requestV0.setTokenStatusesList(tokenStatusesList);
}
} if (stateTransition.isIdentityStateTransition()) {
const { IdentityRequest } = GetProofsRequestV0;

Expand Down
2 changes: 1 addition & 1 deletion packages/rs-dpp/src/data_contract/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ use crate::version::{FeatureVersion, PlatformVersion};
use crate::ProtocolError;
use crate::ProtocolError::{PlatformDeserializationError, PlatformSerializationError};

use crate::data_contract::associated_token::token_configuration::TokenConfiguration;
pub use crate::data_contract::associated_token::token_configuration::TokenConfiguration;
use crate::data_contract::group::Group;
use crate::data_contract::v0::DataContractV0;
use crate::data_contract::v1::DataContractV1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ use platform_value::Identifier;
#[cfg(feature = "state-transition-serde-conversion")]
use serde::{Deserialize, Serialize};

pub type SharedEncryptedNote = (SenderKeyIndex, RecipientKeyIndex, Vec<u8>);
pub type PrivateEncryptedNote = (
RootEncryptionKeyIndex,
DerivationEncryptionKeyIndex,
Vec<u8>,
);

mod property_names {
pub const AMOUNT: &str = "$amount";
pub const RECIPIENT_OWNER_ID: &str = "recipientOwnerId";
Expand Down Expand Up @@ -53,15 +60,11 @@ pub struct TokenTransferTransitionV0 {
feature = "state-transition-serde-conversion",
serde(rename = "sharedEncryptedNote")
)]
pub shared_encrypted_note: Option<(SenderKeyIndex, RecipientKeyIndex, Vec<u8>)>,
pub shared_encrypted_note: Option<SharedEncryptedNote>,
/// An optional private encrypted note
#[cfg_attr(
feature = "state-transition-serde-conversion",
serde(rename = "privateEncryptedNote")
)]
pub private_encrypted_note: Option<(
RootEncryptionKeyIndex,
DerivationEncryptionKeyIndex,
Vec<u8>,
)>,
pub private_encrypted_note: Option<PrivateEncryptedNote>,
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use crate::prelude::{DerivationEncryptionKeyIndex, RecipientKeyIndex, RootEncryp
use crate::state_transition::batch_transition::batched_transition::token_transfer_transition::TokenTransferTransitionV0;
use crate::state_transition::batch_transition::token_base_transition::token_base_transition_accessors::TokenBaseTransitionAccessors;
use crate::state_transition::batch_transition::token_base_transition::TokenBaseTransition;
use crate::state_transition::batch_transition::token_transfer_transition::{PrivateEncryptedNote, SharedEncryptedNote};

impl TokenBaseTransitionAccessors for TokenTransferTransitionV0 {
fn base(&self) -> &TokenBaseTransition {
Expand Down Expand Up @@ -44,16 +45,13 @@ pub trait TokenTransferTransitionV0Methods: TokenBaseTransitionAccessors {
fn set_public_note(&mut self, public_note: Option<String>);

/// Returns the `shared_encrypted_note` field of the `TokenTransferTransitionV0`.
fn shared_encrypted_note(&self) -> Option<&(SenderKeyIndex, RecipientKeyIndex, Vec<u8>)>;
fn shared_encrypted_note(&self) -> Option<&SharedEncryptedNote>;

/// Returns the owned `shared_encrypted_note` field of the `TokenTransferTransitionV0`.
fn shared_encrypted_note_owned(self) -> Option<(SenderKeyIndex, RecipientKeyIndex, Vec<u8>)>;
fn shared_encrypted_note_owned(self) -> Option<SharedEncryptedNote>;

/// Sets the value of the `shared_encrypted_note` field in the `TokenTransferTransitionV0`.
fn set_shared_encrypted_note(
&mut self,
shared_encrypted_note: Option<(SenderKeyIndex, RecipientKeyIndex, Vec<u8>)>,
);
fn set_shared_encrypted_note(&mut self, shared_encrypted_note: Option<SharedEncryptedNote>);

/// Returns the `private_encrypted_note` field of the `TokenTransferTransitionV0`.
fn private_encrypted_note(
Expand All @@ -74,26 +72,15 @@ pub trait TokenTransferTransitionV0Methods: TokenBaseTransitionAccessors {
)>;

/// Sets the value of the `private_encrypted_note` field in the `TokenTransferTransitionV0`.
fn set_private_encrypted_note(
&mut self,
private_encrypted_note: Option<(
RootEncryptionKeyIndex,
DerivationEncryptionKeyIndex,
Vec<u8>,
)>,
);
fn set_private_encrypted_note(&mut self, private_encrypted_note: Option<PrivateEncryptedNote>);

/// Returns all notes (public, shared, and private) as owned values in a tuple.
fn notes_owned(
self,
) -> (
Option<String>,
Option<(SenderKeyIndex, RecipientKeyIndex, Vec<u8>)>,
Option<(
RootEncryptionKeyIndex,
DerivationEncryptionKeyIndex,
Vec<u8>,
)>,
Option<SharedEncryptedNote>,
Option<PrivateEncryptedNote>,
);

/// Returns all notes (public, shared, and private) as cloned values in a tuple.
Expand Down Expand Up @@ -142,18 +129,15 @@ impl TokenTransferTransitionV0Methods for TokenTransferTransitionV0 {
self.public_note = public_note;
}

fn shared_encrypted_note(&self) -> Option<&(SenderKeyIndex, RecipientKeyIndex, Vec<u8>)> {
fn shared_encrypted_note(&self) -> Option<&SharedEncryptedNote> {
self.shared_encrypted_note.as_ref()
}

fn shared_encrypted_note_owned(self) -> Option<(SenderKeyIndex, RecipientKeyIndex, Vec<u8>)> {
fn shared_encrypted_note_owned(self) -> Option<SharedEncryptedNote> {
self.shared_encrypted_note
}

fn set_shared_encrypted_note(
&mut self,
shared_encrypted_note: Option<(SenderKeyIndex, RecipientKeyIndex, Vec<u8>)>,
) {
fn set_shared_encrypted_note(&mut self, shared_encrypted_note: Option<SharedEncryptedNote>) {
self.shared_encrypted_note = shared_encrypted_note;
}

Expand All @@ -177,27 +161,16 @@ impl TokenTransferTransitionV0Methods for TokenTransferTransitionV0 {
self.private_encrypted_note
}

fn set_private_encrypted_note(
&mut self,
private_encrypted_note: Option<(
RootEncryptionKeyIndex,
DerivationEncryptionKeyIndex,
Vec<u8>,
)>,
) {
fn set_private_encrypted_note(&mut self, private_encrypted_note: Option<PrivateEncryptedNote>) {
self.private_encrypted_note = private_encrypted_note;
}

fn notes_owned(
self,
) -> (
Option<String>,
Option<(SenderKeyIndex, RecipientKeyIndex, Vec<u8>)>,
Option<(
RootEncryptionKeyIndex,
DerivationEncryptionKeyIndex,
Vec<u8>,
)>,
Option<SharedEncryptedNote>,
Option<PrivateEncryptedNote>,
) {
(
self.public_note,
Expand Down
Loading