diff --git a/Cargo.lock b/Cargo.lock index 3b2fbead993..aece6af21af 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7578,7 +7578,6 @@ version = "2.2.0-dev.1" dependencies = [ "base64 0.22.1", "bip39", - "bs58", "console_error_panic_hook", "dapi-grpc", "dash-sdk", diff --git a/packages/js-evo-sdk/src/contracts/facade.ts b/packages/js-evo-sdk/src/contracts/facade.ts index 77bcb2b3729..952e3ed19a3 100644 --- a/packages/js-evo-sdk/src/contracts/facade.ts +++ b/packages/js-evo-sdk/src/contracts/facade.ts @@ -1,7 +1,6 @@ import * as wasm from '../wasm.js'; import { asJsonString } from '../util.js'; import type { EvoSDK } from '../sdk.js'; -import type { DataContractHistoryQuery } from '../wasm.js'; export class ContractsFacade { private sdk: EvoSDK; @@ -10,43 +9,43 @@ export class ContractsFacade { this.sdk = sdk; } - async fetch(contractId: string): Promise { + async fetch(contractId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getDataContract(contractId); } - async fetchWithProof(contractId: string): Promise { + async fetchWithProof(contractId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getDataContractWithProofInfo(contractId); } - async getHistory(query: DataContractHistoryQuery): Promise { + async getHistory(query: wasm.DataContractHistoryQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getDataContractHistory(query); } - async getHistoryWithProof(query: DataContractHistoryQuery): Promise { + async getHistoryWithProof(query: wasm.DataContractHistoryQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getDataContractHistoryWithProofInfo(query); } - async getMany(contractIds: string[]): Promise { + async getMany(contractIds: wasm.IdentifierLike[]): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getDataContracts(contractIds); } - async getManyWithProof(contractIds: string[]): Promise { + async getManyWithProof(contractIds: wasm.IdentifierLike[]): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getDataContractsWithProofInfo(contractIds); } - async create(args: { ownerId: string; definition: unknown; privateKeyWif: string; keyId?: number }): Promise { + async create(args: { ownerId: wasm.IdentifierLike; definition: unknown; privateKeyWif: string; keyId?: number }): Promise { const { ownerId, definition, privateKeyWif, keyId } = args; const w = await this.sdk.getWasmSdkConnected(); return w.contractCreate(ownerId, asJsonString(definition)!, privateKeyWif, keyId ?? null); } - async update(args: { contractId: string; ownerId: string; updates: unknown; privateKeyWif: string; keyId?: number }): Promise { + async update(args: { contractId: wasm.IdentifierLike; ownerId: wasm.IdentifierLike; updates: unknown; privateKeyWif: string; keyId?: number }): Promise { const { contractId, ownerId, updates, privateKeyWif, keyId } = args; const w = await this.sdk.getWasmSdkConnected(); return w.contractUpdate(contractId, ownerId, asJsonString(updates)!, privateKeyWif, keyId ?? null); diff --git a/packages/js-evo-sdk/src/documents/facade.ts b/packages/js-evo-sdk/src/documents/facade.ts index 65476b05bc6..64545defa0a 100644 --- a/packages/js-evo-sdk/src/documents/facade.ts +++ b/packages/js-evo-sdk/src/documents/facade.ts @@ -1,6 +1,6 @@ +import * as wasm from '../wasm.js'; import { asJsonString } from '../util.js'; import type { EvoSDK } from '../sdk.js'; -import type { DocumentsQuery } from '../wasm.js'; export class DocumentsFacade { private sdk: EvoSDK; @@ -10,30 +10,30 @@ export class DocumentsFacade { } // Query many documents - async query(query: DocumentsQuery): Promise { + async query(query: wasm.DocumentsQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getDocuments(query); } - async queryWithProof(query: DocumentsQuery): Promise { + async queryWithProof(query: wasm.DocumentsQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getDocumentsWithProofInfo(query); } - async get(contractId: string, type: string, documentId: string): Promise { + async get(contractId: wasm.IdentifierLike, type: string, documentId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getDocument(contractId, type, documentId); } - async getWithProof(contractId: string, type: string, documentId: string): Promise { + async getWithProof(contractId: wasm.IdentifierLike, type: string, documentId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getDocumentWithProofInfo(contractId, type, documentId); } async create(args: { - contractId: string; + contractId: wasm.IdentifierLike; type: string; - ownerId: string; + ownerId: wasm.IdentifierLike; data: unknown; entropyHex: string; privateKeyWif: string; @@ -51,10 +51,10 @@ export class DocumentsFacade { } async replace(args: { - contractId: string; + contractId: wasm.IdentifierLike; type: string; - documentId: string; - ownerId: string; + documentId: wasm.IdentifierLike; + ownerId: wasm.IdentifierLike; data: unknown; revision: number | bigint; privateKeyWif: string; @@ -72,25 +72,25 @@ export class DocumentsFacade { ); } - async delete(args: { contractId: string; type: string; documentId: string; ownerId: string; privateKeyWif: string }): Promise { + async delete(args: { contractId: wasm.IdentifierLike; type: string; documentId: wasm.IdentifierLike; ownerId: wasm.IdentifierLike; privateKeyWif: string }): Promise { const { contractId, type, documentId, ownerId, privateKeyWif } = args; const w = await this.sdk.getWasmSdkConnected(); return w.documentDelete(contractId, type, documentId, ownerId, privateKeyWif); } - async transfer(args: { contractId: string; type: string; documentId: string; ownerId: string; recipientId: string; privateKeyWif: string }): Promise { + async transfer(args: { contractId: wasm.IdentifierLike; type: string; documentId: wasm.IdentifierLike; ownerId: wasm.IdentifierLike; recipientId: wasm.IdentifierLike; privateKeyWif: string }): Promise { const { contractId, type, documentId, ownerId, recipientId, privateKeyWif } = args; const w = await this.sdk.getWasmSdkConnected(); return w.documentTransfer(contractId, type, documentId, ownerId, recipientId, privateKeyWif); } - async purchase(args: { contractId: string; type: string; documentId: string; buyerId: string; price: number | bigint | string; privateKeyWif: string }): Promise { + async purchase(args: { contractId: wasm.IdentifierLike; type: string; documentId: wasm.IdentifierLike; buyerId: wasm.IdentifierLike; price: number | bigint | string; privateKeyWif: string }): Promise { const { contractId, type, documentId, buyerId, price, privateKeyWif } = args; const w = await this.sdk.getWasmSdkConnected(); return w.documentPurchase(contractId, type, documentId, buyerId, BigInt(price), privateKeyWif); } - async setPrice(args: { contractId: string; type: string; documentId: string; ownerId: string; price: number | bigint | string; privateKeyWif: string }): Promise { + async setPrice(args: { contractId: wasm.IdentifierLike; type: string; documentId: wasm.IdentifierLike; ownerId: wasm.IdentifierLike; price: number | bigint | string; privateKeyWif: string }): Promise { const { contractId, type, documentId, ownerId, price, privateKeyWif } = args; const w = await this.sdk.getWasmSdkConnected(); return w.documentSetPrice(contractId, type, documentId, ownerId, BigInt(price), privateKeyWif); diff --git a/packages/js-evo-sdk/src/dpns/facade.ts b/packages/js-evo-sdk/src/dpns/facade.ts index 166efc7d145..3392554df34 100644 --- a/packages/js-evo-sdk/src/dpns/facade.ts +++ b/packages/js-evo-sdk/src/dpns/facade.ts @@ -33,30 +33,28 @@ export class DpnsFacade { return w.dpnsResolveName(name); } - async registerName(args: { label: string; identityId: string; publicKeyId: number; privateKeyWif: string; onPreorder?: Function }): Promise { + async registerName(args: { label: string; identityId: wasm.IdentifierLike; publicKeyId: number; privateKeyWif: string; onPreorder?: Function }): Promise { const { label, identityId, publicKeyId, privateKeyWif, onPreorder } = args; const w = await this.sdk.getWasmSdkConnected(); return w.dpnsRegisterName(label, identityId, publicKeyId, privateKeyWif, onPreorder ?? null); } - async usernames(identityId: string, opts: { limit?: number } = {}): Promise { - const { limit } = opts; + async usernames(query: wasm.DpnsUsernamesQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); - return w.getDpnsUsernames(identityId, limit ?? null); + return w.getDpnsUsernames(query); } - async username(identityId: string): Promise { + async username(identityId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getDpnsUsername(identityId); } - async usernamesWithProof(identityId: string, opts: { limit?: number } = {}): Promise { - const { limit } = opts; + async usernamesWithProof(query: wasm.DpnsUsernamesQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); - return w.getDpnsUsernamesWithProofInfo(identityId, limit ?? null); + return w.getDpnsUsernamesWithProofInfo(query); } - async usernameWithProof(identityId: string): Promise { + async usernameWithProof(identityId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getDpnsUsernameWithProofInfo(identityId); } diff --git a/packages/js-evo-sdk/src/group/facade.ts b/packages/js-evo-sdk/src/group/facade.ts index 11d22ec8a94..cae5291b4a3 100644 --- a/packages/js-evo-sdk/src/group/facade.ts +++ b/packages/js-evo-sdk/src/group/facade.ts @@ -1,103 +1,96 @@ -import type { - ContestedResourceVotersForIdentityQuery, - GroupActionsQuery, - GroupInfosQuery, - GroupMembersQuery, - IdentityGroupsQuery, - VotePollsByDocumentTypeQuery, -} from '../wasm.js'; +import * as wasm from '../wasm.js'; import type { EvoSDK } from '../sdk.js'; export class GroupFacade { private sdk: EvoSDK; constructor(sdk: EvoSDK) { this.sdk = sdk; } - async info(contractId: string, groupContractPosition: number): Promise { + async info(contractId: wasm.IdentifierLike, groupContractPosition: number): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getGroupInfo(contractId, groupContractPosition); } - async infoWithProof(contractId: string, groupContractPosition: number): Promise { + async infoWithProof(contractId: wasm.IdentifierLike, groupContractPosition: number): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getGroupInfoWithProofInfo(contractId, groupContractPosition); } - async infos(query: GroupInfosQuery): Promise { + async infos(query: wasm.GroupInfosQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getGroupInfos(query); } - async infosWithProof(query: GroupInfosQuery): Promise { + async infosWithProof(query: wasm.GroupInfosQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getGroupInfosWithProofInfo(query); } - async members(query: GroupMembersQuery): Promise { + async members(query: wasm.GroupMembersQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getGroupMembers(query); } - async membersWithProof(query: GroupMembersQuery): Promise { + async membersWithProof(query: wasm.GroupMembersQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getGroupMembersWithProofInfo(query); } - async identityGroups(query: IdentityGroupsQuery): Promise { + async identityGroups(query: wasm.IdentityGroupsQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityGroups(query); } - async identityGroupsWithProof(query: IdentityGroupsQuery): Promise { + async identityGroupsWithProof(query: wasm.IdentityGroupsQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityGroupsWithProofInfo(query); } - async actions(query: GroupActionsQuery): Promise { + async actions(query: wasm.GroupActionsQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getGroupActions(query); } - async actionsWithProof(query: GroupActionsQuery): Promise { + async actionsWithProof(query: wasm.GroupActionsQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getGroupActionsWithProofInfo(query); } - async actionSigners(contractId: string, groupContractPosition: number, status: string, actionId: string): Promise { + async actionSigners(query: wasm.GroupActionSignersQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); - return w.getGroupActionSigners(contractId, groupContractPosition, status, actionId); + return w.getGroupActionSigners(query); } - async actionSignersWithProof(contractId: string, groupContractPosition: number, status: string, actionId: string): Promise { + async actionSignersWithProof(query: wasm.GroupActionSignersQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); - return w.getGroupActionSignersWithProofInfo(contractId, groupContractPosition, status, actionId); + return w.getGroupActionSignersWithProofInfo(query); } - async groupsDataContracts(dataContractIds: string[]): Promise { + async groupsDataContracts(dataContractIds: wasm.IdentifierLike[]): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getGroupsDataContracts(dataContractIds); } - async groupsDataContractsWithProof(dataContractIds: string[]): Promise { + async groupsDataContractsWithProof(dataContractIds: wasm.IdentifierLike[]): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getGroupsDataContractsWithProofInfo(dataContractIds); } - async contestedResources(query: VotePollsByDocumentTypeQuery): Promise { + async contestedResources(query: wasm.VotePollsByDocumentTypeQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getContestedResources(query); } - async contestedResourcesWithProof(query: VotePollsByDocumentTypeQuery): Promise { + async contestedResourcesWithProof(query: wasm.VotePollsByDocumentTypeQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getContestedResourcesWithProofInfo(query); } - async contestedResourceVotersForIdentity(query: ContestedResourceVotersForIdentityQuery): Promise { + async contestedResourceVotersForIdentity(query: wasm.ContestedResourceVotersForIdentityQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getContestedResourceVotersForIdentity(query); } - async contestedResourceVotersForIdentityWithProof(query: ContestedResourceVotersForIdentityQuery): Promise { + async contestedResourceVotersForIdentityWithProof(query: wasm.ContestedResourceVotersForIdentityQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getContestedResourceVotersForIdentityWithProofInfo(query); } diff --git a/packages/js-evo-sdk/src/identities/facade.ts b/packages/js-evo-sdk/src/identities/facade.ts index 2abdf66ba16..6a356ef36ef 100644 --- a/packages/js-evo-sdk/src/identities/facade.ts +++ b/packages/js-evo-sdk/src/identities/facade.ts @@ -1,7 +1,6 @@ import * as wasm from '../wasm.js'; import { asJsonString } from '../util.js'; import type { EvoSDK } from '../sdk.js'; -import type { IdentityKeysQuery } from '../wasm.js'; export class IdentitiesFacade { private sdk: EvoSDK; @@ -10,121 +9,117 @@ export class IdentitiesFacade { this.sdk = sdk; } - async fetch(identityId: string): Promise { + async fetch(identityId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentity(identityId); } - async fetchWithProof(identityId: string): Promise { + async fetchWithProof(identityId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityWithProofInfo(identityId); } - async fetchUnproved(identityId: string): Promise { + async fetchUnproved(identityId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityUnproved(identityId); } - async getKeys(query: IdentityKeysQuery): Promise { + async getKeys(query: wasm.IdentityKeysQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityKeys(query); } - async getKeysWithProof(query: IdentityKeysQuery): Promise { + async getKeysWithProof(query: wasm.IdentityKeysQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityKeysWithProofInfo(query); } - async nonce(identityId: string): Promise { + async nonce(identityId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityNonce(identityId); } - async nonceWithProof(identityId: string): Promise { + async nonceWithProof(identityId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityNonceWithProofInfo(identityId); } - async contractNonce(identityId: string, contractId: string): Promise { + async contractNonce(identityId: wasm.IdentifierLike, contractId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityContractNonce(identityId, contractId); } - async contractNonceWithProof(identityId: string, contractId: string): Promise { + async contractNonceWithProof(identityId: wasm.IdentifierLike, contractId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityContractNonceWithProofInfo(identityId, contractId); } - async balance(identityId: string): Promise { + async balance(identityId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityBalance(identityId); } - async balanceWithProof(identityId: string): Promise { + async balanceWithProof(identityId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityBalanceWithProofInfo(identityId); } - async balances(identityIds: string[]): Promise { + async balances(identityIds: wasm.IdentifierLike[]): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentitiesBalances(identityIds); } - async balancesWithProof(identityIds: string[]): Promise { + async balancesWithProof(identityIds: wasm.IdentifierLike[]): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentitiesBalancesWithProofInfo(identityIds); } - async balanceAndRevision(identityId: string): Promise { + async balanceAndRevision(identityId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityBalanceAndRevision(identityId); } - async balanceAndRevisionWithProof(identityId: string): Promise { + async balanceAndRevisionWithProof(identityId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityBalanceAndRevisionWithProofInfo(identityId); } - async byPublicKeyHash(publicKeyHash: string): Promise { + async byPublicKeyHash(publicKeyHash: string | Uint8Array): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityByPublicKeyHash(publicKeyHash); } - async byPublicKeyHashWithProof(publicKeyHash: string): Promise { + async byPublicKeyHashWithProof(publicKeyHash: string | Uint8Array): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityByPublicKeyHashWithProofInfo(publicKeyHash); } - async byNonUniquePublicKeyHash(publicKeyHash: string, startAfter?: string): Promise { + async byNonUniquePublicKeyHash(publicKeyHash: string | Uint8Array, startAfter?: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityByNonUniquePublicKeyHash(publicKeyHash, startAfter); } - async byNonUniquePublicKeyHashWithProof(publicKeyHash: string, startAfter?: string): Promise { + async byNonUniquePublicKeyHashWithProof(publicKeyHash: string | Uint8Array, startAfter?: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityByNonUniquePublicKeyHashWithProofInfo(publicKeyHash, startAfter || undefined); } - async contractKeys(args: { identityIds: string[]; contractId: string; purposes?: number[] }): Promise { - const { identityIds, contractId, purposes } = args; - const purposesArray = purposes && purposes.length > 0 ? Uint32Array.from(purposes) : null; + async contractKeys(query: wasm.IdentitiesContractKeysQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); - return w.getIdentitiesContractKeys(identityIds, contractId, purposesArray); + return w.getIdentitiesContractKeys(query); } - async contractKeysWithProof(args: { identityIds: string[]; contractId: string; purposes?: number[] }): Promise { - const { identityIds, contractId, purposes } = args; - const purposesArray = purposes && purposes.length > 0 ? Uint32Array.from(purposes) : null; + async contractKeysWithProof(query: wasm.IdentitiesContractKeysQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); - return w.getIdentitiesContractKeysWithProofInfo(identityIds, contractId, purposesArray); + return w.getIdentitiesContractKeysWithProofInfo(query); } - async tokenBalances(identityId: string, tokenIds: string[]): Promise { + async tokenBalances(identityId: wasm.IdentifierLike, tokenIds: wasm.IdentifierLike[]): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityTokenBalances(identityId, tokenIds); } - async tokenBalancesWithProof(identityId: string, tokenIds: string[]): Promise { + async tokenBalancesWithProof(identityId: wasm.IdentifierLike, tokenIds: wasm.IdentifierLike[]): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityTokenBalancesWithProofInfo(identityId, tokenIds); } @@ -135,25 +130,25 @@ export class IdentitiesFacade { return w.identityCreate(asJsonString(assetLockProof)!, assetLockPrivateKeyWif, asJsonString(publicKeys)!); } - async topUp(args: { identityId: string; assetLockProof: unknown; assetLockPrivateKeyWif: string }): Promise { + async topUp(args: { identityId: wasm.IdentifierLike; assetLockProof: unknown; assetLockPrivateKeyWif: string }): Promise { const { identityId, assetLockProof, assetLockPrivateKeyWif } = args; const w = await this.sdk.getWasmSdkConnected(); return w.identityTopUp(identityId, asJsonString(assetLockProof)!, assetLockPrivateKeyWif); } - async creditTransfer(args: { senderId: string; recipientId: string; amount: number | bigint | string; privateKeyWif: string; keyId?: number }): Promise { + async creditTransfer(args: { senderId: wasm.IdentifierLike; recipientId: wasm.IdentifierLike; amount: number | bigint | string; privateKeyWif: string; keyId?: number }): Promise { const { senderId, recipientId, amount, privateKeyWif, keyId } = args; const w = await this.sdk.getWasmSdkConnected(); return w.identityCreditTransfer(senderId, recipientId, BigInt(amount), privateKeyWif, keyId ?? null); } - async creditWithdrawal(args: { identityId: string; toAddress: string; amount: number | bigint | string; coreFeePerByte?: number; privateKeyWif: string; keyId?: number }): Promise { + async creditWithdrawal(args: { identityId: wasm.IdentifierLike; toAddress: string; amount: number | bigint | string; coreFeePerByte?: number; privateKeyWif: string; keyId?: number }): Promise { const { identityId, toAddress, amount, coreFeePerByte = 1, privateKeyWif, keyId } = args; const w = await this.sdk.getWasmSdkConnected(); return w.identityCreditWithdrawal(identityId, toAddress, BigInt(amount), coreFeePerByte ?? null, privateKeyWif, keyId ?? null); } - async update(args: { identityId: string; addPublicKeys?: unknown[]; disablePublicKeyIds?: number[]; privateKeyWif: string }): Promise { + async update(args: { identityId: wasm.IdentifierLike; addPublicKeys?: unknown[]; disablePublicKeyIds?: number[]; privateKeyWif: string }): Promise { const { identityId, addPublicKeys, disablePublicKeyIds, privateKeyWif } = args; const w = await this.sdk.getWasmSdkConnected(); return w.identityUpdate( diff --git a/packages/js-evo-sdk/src/protocol/facade.ts b/packages/js-evo-sdk/src/protocol/facade.ts index 1eb9f5dcdac..353a05c289a 100644 --- a/packages/js-evo-sdk/src/protocol/facade.ts +++ b/packages/js-evo-sdk/src/protocol/facade.ts @@ -7,14 +7,12 @@ export class ProtocolFacade { async versionUpgradeState(): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getProtocolVersionUpgradeState(); } async versionUpgradeStateWithProof(): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getProtocolVersionUpgradeStateWithProofInfo(); } - async versionUpgradeVoteStatus(params: { startProTxHash: string; count: number }): Promise { - const { startProTxHash, count } = params; + async versionUpgradeVoteStatus(startProTxHash: string | Uint8Array, count: number): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getProtocolVersionUpgradeVoteStatus(startProTxHash, count); } - async versionUpgradeVoteStatusWithProof(params: { startProTxHash: string; count: number }): Promise { - const { startProTxHash, count } = params; + async versionUpgradeVoteStatusWithProof(startProTxHash: string | Uint8Array, count: number): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getProtocolVersionUpgradeVoteStatusWithProofInfo(startProTxHash, count); } diff --git a/packages/js-evo-sdk/src/system/facade.ts b/packages/js-evo-sdk/src/system/facade.ts index 1c93695bae3..8b82be3d77b 100644 --- a/packages/js-evo-sdk/src/system/facade.ts +++ b/packages/js-evo-sdk/src/system/facade.ts @@ -1,3 +1,4 @@ +import * as wasm from '../wasm.js'; import type { EvoSDK } from '../sdk.js'; export class SystemFacade { @@ -8,8 +9,8 @@ export class SystemFacade { async currentQuorumsInfo(): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getCurrentQuorumsInfo(); } async totalCreditsInPlatform(): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getTotalCreditsInPlatform(); } async totalCreditsInPlatformWithProof(): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getTotalCreditsInPlatformWithProofInfo(); } - async prefundedSpecializedBalance(identityId: string): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getPrefundedSpecializedBalance(identityId); } - async prefundedSpecializedBalanceWithProof(identityId: string): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getPrefundedSpecializedBalanceWithProofInfo(identityId); } + async prefundedSpecializedBalance(identityId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getPrefundedSpecializedBalance(identityId); } + async prefundedSpecializedBalanceWithProof(identityId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getPrefundedSpecializedBalanceWithProofInfo(identityId); } async waitForStateTransitionResult(stateTransitionHash: string): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.waitForStateTransitionResult(stateTransitionHash); } async pathElements(path: string[], keys: string[]): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getPathElements(path, keys); } async pathElementsWithProof(path: string[], keys: string[]): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getPathElementsWithProofInfo(path, keys); } diff --git a/packages/js-evo-sdk/src/tokens/facade.ts b/packages/js-evo-sdk/src/tokens/facade.ts index 6cca1deee57..50e8c9b90b2 100644 --- a/packages/js-evo-sdk/src/tokens/facade.ts +++ b/packages/js-evo-sdk/src/tokens/facade.ts @@ -9,163 +9,163 @@ export class TokensFacade { this.sdk = sdk; } - async calculateId(contractId: string, tokenPosition: number): Promise { + async calculateId(contractId: wasm.IdentifierLike, tokenPosition: number): Promise { await wasm.ensureInitialized(); return wasm.WasmSdk.calculateTokenIdFromContract(contractId, tokenPosition); } // Queries - async priceByContract(contractId: string, tokenPosition: number): Promise { + async priceByContract(contractId: wasm.IdentifierLike, tokenPosition: number): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getTokenPriceByContract(contractId, tokenPosition); } - async totalSupply(tokenId: string): Promise { + async totalSupply(tokenId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getTokenTotalSupply(tokenId); } - async totalSupplyWithProof(tokenId: string): Promise { + async totalSupplyWithProof(tokenId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getTokenTotalSupplyWithProofInfo(tokenId); } - async statuses(tokenIds: string[]): Promise { + async statuses(tokenIds: wasm.IdentifierLike[]): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getTokenStatuses(tokenIds); } - async statusesWithProof(tokenIds: string[]): Promise { + async statusesWithProof(tokenIds: wasm.IdentifierLike[]): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getTokenStatusesWithProofInfo(tokenIds); } - async balances(identityIds: string[], tokenId: string): Promise { + async balances(identityIds: wasm.IdentifierLike[], tokenId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentitiesTokenBalances(identityIds, tokenId); } - async balancesWithProof(identityIds: string[], tokenId: string): Promise { + async balancesWithProof(identityIds: wasm.IdentifierLike[], tokenId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentitiesTokenBalancesWithProofInfo(identityIds, tokenId); } - async identityBalances(identityId: string, tokenIds: string[]): Promise { + async identityBalances(identityId: wasm.IdentifierLike, tokenIds: wasm.IdentifierLike[]): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityTokenBalances(identityId, tokenIds); } - async identityBalancesWithProof(identityId: string, tokenIds: string[]): Promise { + async identityBalancesWithProof(identityId: wasm.IdentifierLike, tokenIds: wasm.IdentifierLike[]): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityTokenBalancesWithProofInfo(identityId, tokenIds); } - async identityTokenInfos(identityId: string, tokenIds: string[], _opts: { limit?: number; offset?: number } = {}): Promise { + async identityTokenInfos(identityId: wasm.IdentifierLike, tokenIds: wasm.IdentifierLike[]): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityTokenInfos(identityId, tokenIds); } - async identitiesTokenInfos(identityIds: string[], tokenId: string): Promise { + async identitiesTokenInfos(identityIds: wasm.IdentifierLike[], tokenId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentitiesTokenInfos(identityIds, tokenId); } - async identityTokenInfosWithProof(identityId: string, tokenIds: string[]): Promise { + async identityTokenInfosWithProof(identityId: wasm.IdentifierLike, tokenIds: wasm.IdentifierLike[]): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentityTokenInfosWithProofInfo(identityId, tokenIds); } - async identitiesTokenInfosWithProof(identityIds: string[], tokenId: string): Promise { + async identitiesTokenInfosWithProof(identityIds: wasm.IdentifierLike[], tokenId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getIdentitiesTokenInfosWithProofInfo(identityIds, tokenId); } - async directPurchasePrices(tokenIds: string[]): Promise { + async directPurchasePrices(tokenIds: wasm.IdentifierLike[]): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getTokenDirectPurchasePrices(tokenIds); } - async directPurchasePricesWithProof(tokenIds: string[]): Promise { + async directPurchasePricesWithProof(tokenIds: wasm.IdentifierLike[]): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getTokenDirectPurchasePricesWithProofInfo(tokenIds); } - async contractInfo(contractId: string): Promise { + async contractInfo(contractId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getTokenContractInfo(contractId); } - async contractInfoWithProof(contractId: string): Promise { + async contractInfoWithProof(contractId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getTokenContractInfoWithProofInfo(contractId); } - async perpetualDistributionLastClaim(identityId: string, tokenId: string): Promise { + async perpetualDistributionLastClaim(identityId: wasm.IdentifierLike, tokenId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getTokenPerpetualDistributionLastClaim(identityId, tokenId); } - async perpetualDistributionLastClaimWithProof(identityId: string, tokenId: string): Promise { + async perpetualDistributionLastClaimWithProof(identityId: wasm.IdentifierLike, tokenId: wasm.IdentifierLike): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getTokenPerpetualDistributionLastClaimWithProofInfo(identityId, tokenId); } // Transitions - async mint(args: { contractId: string; tokenPosition: number; amount: number | string | bigint; identityId: string; privateKeyWif: string; recipientId?: string; publicNote?: string }): Promise { + async mint(args: { contractId: wasm.IdentifierLike; tokenPosition: number; amount: number | string | bigint; identityId: wasm.IdentifierLike; privateKeyWif: string; recipientId?: wasm.IdentifierLike; publicNote?: string }): Promise { const { contractId, tokenPosition, amount, identityId, privateKeyWif, recipientId, publicNote } = args; const w = await this.sdk.getWasmSdkConnected(); return w.tokenMint(contractId, tokenPosition, String(amount), identityId, privateKeyWif, recipientId, publicNote ?? null); } - async burn(args: { contractId: string; tokenPosition: number; amount: number | string | bigint; identityId: string; privateKeyWif: string; publicNote?: string }): Promise { + async burn(args: { contractId: wasm.IdentifierLike; tokenPosition: number; amount: number | string | bigint; identityId: wasm.IdentifierLike; privateKeyWif: string; publicNote?: string }): Promise { const { contractId, tokenPosition, amount, identityId, privateKeyWif, publicNote } = args; const w = await this.sdk.getWasmSdkConnected(); return w.tokenBurn(contractId, tokenPosition, String(amount), identityId, privateKeyWif, publicNote ?? null); } - async transfer(args: { contractId: string; tokenPosition: number; amount: number | string | bigint; senderId: string; recipientId: string; privateKeyWif: string; publicNote?: string }): Promise { + async transfer(args: { contractId: wasm.IdentifierLike; tokenPosition: number; amount: number | string | bigint; senderId: wasm.IdentifierLike; recipientId: wasm.IdentifierLike; privateKeyWif: string; publicNote?: string }): Promise { const { contractId, tokenPosition, amount, senderId, recipientId, privateKeyWif, publicNote } = args; const w = await this.sdk.getWasmSdkConnected(); return w.tokenTransfer(contractId, tokenPosition, String(amount), senderId, recipientId, privateKeyWif, publicNote ?? null); } - async freeze(args: { contractId: string; tokenPosition: number; identityToFreeze: string; freezerId: string; privateKeyWif: string; publicNote?: string }): Promise { + async freeze(args: { contractId: wasm.IdentifierLike; tokenPosition: number; identityToFreeze: wasm.IdentifierLike; freezerId: wasm.IdentifierLike; privateKeyWif: string; publicNote?: string }): Promise { const { contractId, tokenPosition, identityToFreeze, freezerId, privateKeyWif, publicNote } = args; const w = await this.sdk.getWasmSdkConnected(); return w.tokenFreeze(contractId, tokenPosition, identityToFreeze, freezerId, privateKeyWif, publicNote ?? null); } - async unfreeze(args: { contractId: string; tokenPosition: number; identityToUnfreeze: string; unfreezerId: string; privateKeyWif: string; publicNote?: string }): Promise { + async unfreeze(args: { contractId: wasm.IdentifierLike; tokenPosition: number; identityToUnfreeze: wasm.IdentifierLike; unfreezerId: wasm.IdentifierLike; privateKeyWif: string; publicNote?: string }): Promise { const { contractId, tokenPosition, identityToUnfreeze, unfreezerId, privateKeyWif, publicNote } = args; const w = await this.sdk.getWasmSdkConnected(); return w.tokenUnfreeze(contractId, tokenPosition, identityToUnfreeze, unfreezerId, privateKeyWif, publicNote ?? null); } - async destroyFrozen(args: { contractId: string; tokenPosition: number; identityId: string; destroyerId: string; privateKeyWif: string; publicNote?: string }): Promise { + async destroyFrozen(args: { contractId: wasm.IdentifierLike; tokenPosition: number; identityId: wasm.IdentifierLike; destroyerId: wasm.IdentifierLike; privateKeyWif: string; publicNote?: string }): Promise { const { contractId, tokenPosition, identityId, destroyerId, privateKeyWif, publicNote } = args; const w = await this.sdk.getWasmSdkConnected(); return w.tokenDestroyFrozen(contractId, tokenPosition, identityId, destroyerId, privateKeyWif, publicNote ?? null); } - async setPriceForDirectPurchase(args: { contractId: string; tokenPosition: number; identityId: string; priceType: string; priceData: unknown; privateKeyWif: string; publicNote?: string }): Promise { + async setPriceForDirectPurchase(args: { contractId: wasm.IdentifierLike; tokenPosition: number; identityId: wasm.IdentifierLike; priceType: string; priceData: unknown; privateKeyWif: string; publicNote?: string }): Promise { const { contractId, tokenPosition, identityId, priceType, priceData, privateKeyWif, publicNote } = args; const w = await this.sdk.getWasmSdkConnected(); return w.tokenSetPriceForDirectPurchase(contractId, tokenPosition, identityId, priceType, asJsonString(priceData)!, privateKeyWif, publicNote ?? null); } - async directPurchase(args: { contractId: string; tokenPosition: number; amount: number | string | bigint; identityId: string; totalAgreedPrice?: number | string | bigint | null; privateKeyWif: string }): Promise { + async directPurchase(args: { contractId: wasm.IdentifierLike; tokenPosition: number; amount: number | string | bigint; identityId: wasm.IdentifierLike; totalAgreedPrice?: number | string | bigint | null; privateKeyWif: string }): Promise { const { contractId, tokenPosition, amount, identityId, totalAgreedPrice, privateKeyWif } = args; const w = await this.sdk.getWasmSdkConnected(); return w.tokenDirectPurchase(contractId, tokenPosition, String(amount), identityId, totalAgreedPrice != null ? String(totalAgreedPrice) : null, privateKeyWif); } - async claim(args: { contractId: string; tokenPosition: number; distributionType: string; identityId: string; privateKeyWif: string; publicNote?: string }): Promise { + async claim(args: { contractId: wasm.IdentifierLike; tokenPosition: number; distributionType: string; identityId: wasm.IdentifierLike; privateKeyWif: string; publicNote?: string }): Promise { const { contractId, tokenPosition, distributionType, identityId, privateKeyWif, publicNote } = args; const w = await this.sdk.getWasmSdkConnected(); return w.tokenClaim(contractId, tokenPosition, distributionType, identityId, privateKeyWif, publicNote ?? null); } - async configUpdate(args: { contractId: string; tokenPosition: number; configItemType: string; configValue: unknown; identityId: string; privateKeyWif: string; publicNote?: string }): Promise { + async configUpdate(args: { contractId: wasm.IdentifierLike; tokenPosition: number; configItemType: string; configValue: unknown; identityId: wasm.IdentifierLike; privateKeyWif: string; publicNote?: string }): Promise { const { contractId, tokenPosition, configItemType, configValue, identityId, privateKeyWif, publicNote } = args; const w = await this.sdk.getWasmSdkConnected(); return w.tokenConfigUpdate(contractId, tokenPosition, configItemType, asJsonString(configValue)!, identityId, privateKeyWif, publicNote ?? null); diff --git a/packages/js-evo-sdk/src/voting/facade.ts b/packages/js-evo-sdk/src/voting/facade.ts index 1ce9825dc31..63f2aaed89a 100644 --- a/packages/js-evo-sdk/src/voting/facade.ts +++ b/packages/js-evo-sdk/src/voting/facade.ts @@ -1,8 +1,4 @@ -import type { - ContestedResourceIdentityVotesQuery, - ContestedResourceVoteStateQuery, - VotePollsByEndDateQuery, -} from '@dashevo/wasm-sdk'; +import * as wasm from '../wasm.js'; import { asJsonString } from '../util.js'; import type { EvoSDK } from '../sdk.js'; @@ -10,39 +6,39 @@ export class VotingFacade { private sdk: EvoSDK; constructor(sdk: EvoSDK) { this.sdk = sdk; } - async contestedResourceVoteState(query: ContestedResourceVoteStateQuery): Promise { + async contestedResourceVoteState(query: wasm.ContestedResourceVoteStateQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getContestedResourceVoteState(query); } - async contestedResourceVoteStateWithProof(query: ContestedResourceVoteStateQuery): Promise { + async contestedResourceVoteStateWithProof(query: wasm.ContestedResourceVoteStateQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getContestedResourceVoteStateWithProofInfo(query); } - async contestedResourceIdentityVotes(query: ContestedResourceIdentityVotesQuery): Promise { + async contestedResourceIdentityVotes(query: wasm.ContestedResourceIdentityVotesQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getContestedResourceIdentityVotes(query); } - async contestedResourceIdentityVotesWithProof(query: ContestedResourceIdentityVotesQuery): Promise { + async contestedResourceIdentityVotesWithProof(query: wasm.ContestedResourceIdentityVotesQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getContestedResourceIdentityVotesWithProofInfo(query); } - async votePollsByEndDate(query?: VotePollsByEndDateQuery): Promise { + async votePollsByEndDate(query?: wasm.VotePollsByEndDateQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getVotePollsByEndDate(query ?? null); } - async votePollsByEndDateWithProof(query?: VotePollsByEndDateQuery): Promise { + async votePollsByEndDateWithProof(query?: wasm.VotePollsByEndDateQuery): Promise { const w = await this.sdk.getWasmSdkConnected(); return w.getVotePollsByEndDateWithProofInfo(query ?? null); } - async masternodeVote(args: { masternodeProTxHash: string; contractId: string; documentTypeName: string; indexName: string; indexValues: string | any[]; voteChoice: string; votingKeyWif: string }): Promise { + async masternodeVote(args: { masternodeProTxHash: string; contractId: wasm.IdentifierLike; documentTypeName: string; indexName: string; indexValues: string | any[]; voteChoice: string; votingKeyWif: string }): Promise { const { masternodeProTxHash, contractId, documentTypeName, indexName, indexValues, voteChoice, votingKeyWif } = args; const indexValuesStr = typeof indexValues === 'string' ? indexValues : asJsonString(indexValues)!; const w = await this.sdk.getWasmSdkConnected(); diff --git a/packages/js-evo-sdk/src/wallet/functions.ts b/packages/js-evo-sdk/src/wallet/functions.ts index 40359c60a6d..bd9aa0c97eb 100644 --- a/packages/js-evo-sdk/src/wallet/functions.ts +++ b/packages/js-evo-sdk/src/wallet/functions.ts @@ -1,9 +1,9 @@ import * as wasm from '../wasm.js'; export namespace wallet { - export async function generateMnemonic(wordCount?: number, languageCode?: string): Promise { + export async function generateMnemonic(params?: wasm.GenerateMnemonicParams): Promise { await wasm.ensureInitialized(); - return wasm.WasmSdk.generateMnemonic(wordCount ?? null, languageCode ?? null); + return wasm.WasmSdk.generateMnemonic(params ?? null); } export async function validateMnemonic(mnemonic: string, languageCode?: string): Promise { @@ -16,32 +16,24 @@ export namespace wallet { return wasm.WasmSdk.mnemonicToSeed(mnemonic, passphrase ?? null); } - export async function deriveKeyFromSeedPhrase(mnemonic: string, passphrase: string | null | undefined, network: string): Promise { + export async function deriveKeyFromSeedPhrase(params: wasm.DeriveKeyFromSeedPhraseParams): Promise { await wasm.ensureInitialized(); - return wasm.WasmSdk.deriveKeyFromSeedPhrase(mnemonic, passphrase ?? null, network); + return wasm.WasmSdk.deriveKeyFromSeedPhrase(params); } - export async function deriveKeyFromSeedWithPath(mnemonic: string, passphrase: string | null | undefined, path: string, network: string): Promise { + export async function deriveKeyFromSeedWithPath(params: wasm.DeriveKeyFromSeedWithPathParams): Promise { await wasm.ensureInitialized(); - return wasm.WasmSdk.deriveKeyFromSeedWithPath(mnemonic, passphrase ?? null, path, network); + return wasm.WasmSdk.deriveKeyFromSeedWithPath(params); } - export async function deriveKeyFromSeedWithExtendedPath(mnemonic: string, passphrase: string | null | undefined, path: string, network: string): Promise { + export async function deriveKeyFromSeedWithExtendedPath(params: wasm.DeriveKeyFromSeedWithExtendedPathParams): Promise { await wasm.ensureInitialized(); - return wasm.WasmSdk.deriveKeyFromSeedWithExtendedPath(mnemonic, passphrase ?? null, path, network); + return wasm.WasmSdk.deriveKeyFromSeedWithExtendedPath(params); } - export async function deriveDashpayContactKey(mnemonic: string, passphrase: string | null | undefined, senderIdentityId: string, receiverIdentityId: string, account: number, addressIndex: number, network: string): Promise { + export async function deriveDashpayContactKey(params: wasm.DeriveDashpayContactKeyParams): Promise { await wasm.ensureInitialized(); - return wasm.WasmSdk.deriveDashpayContactKey( - mnemonic, - passphrase ?? null, - senderIdentityId, - receiverIdentityId, - account, - addressIndex, - network, - ); + return wasm.WasmSdk.deriveDashpayContactKey(params); } export async function derivationPathBip44Mainnet(account: number, change: number, index: number): Promise { diff --git a/packages/js-evo-sdk/tests/functional/dpns.spec.mjs b/packages/js-evo-sdk/tests/functional/dpns.spec.mjs index cbbdd6bbfc6..8c9200d5c4d 100644 --- a/packages/js-evo-sdk/tests/functional/dpns.spec.mjs +++ b/packages/js-evo-sdk/tests/functional/dpns.spec.mjs @@ -21,7 +21,7 @@ describe('DPNS', function dpnsSuite() { }); it('usernames() returns usernames for identity', async () => { - const res = await sdk.dpns.usernames(TEST_IDS.identityId, { limit: 5 }); + const res = await sdk.dpns.usernames({ identityId: TEST_IDS.identityId, limit: 5 }); expect(res).to.exist(); }); diff --git a/packages/js-evo-sdk/tests/functional/protocol.spec.mjs b/packages/js-evo-sdk/tests/functional/protocol.spec.mjs index 4c48e48f3f9..3db4f508342 100644 --- a/packages/js-evo-sdk/tests/functional/protocol.spec.mjs +++ b/packages/js-evo-sdk/tests/functional/protocol.spec.mjs @@ -16,10 +16,7 @@ describe('Protocol', function protocolSuite() { }); it('versionUpgradeVoteStatus() returns vote window status', async () => { - const res = await sdk.protocol.versionUpgradeVoteStatus({ - startProTxHash: TEST_IDS.proTxHash, - count: 1, - }); + const res = await sdk.protocol.versionUpgradeVoteStatus(TEST_IDS.proTxHash, 1); expect(res).to.exist(); }); }); diff --git a/packages/js-evo-sdk/tests/functional/wallet.spec.mjs b/packages/js-evo-sdk/tests/functional/wallet.spec.mjs index 776b9712ad7..eda5c69fa28 100644 --- a/packages/js-evo-sdk/tests/functional/wallet.spec.mjs +++ b/packages/js-evo-sdk/tests/functional/wallet.spec.mjs @@ -2,7 +2,7 @@ import { wallet } from '../../dist/evo-sdk.module.js'; describe('wallet helpers', () => { it('generateMnemonic() returns phrase and validateMnemonic() succeeds', async () => { - const mnemonic = await wallet.generateMnemonic(12, 'en'); + const mnemonic = await wallet.generateMnemonic({ wordCount: 12, languageCode: 'en' }); expect(mnemonic).to.be.a('string'); expect(await wallet.validateMnemonic(mnemonic, 'en')).to.equal(true); }); @@ -11,9 +11,13 @@ describe('wallet helpers', () => { const mnemonic = await wallet.generateMnemonic(); const seed = await wallet.mnemonicToSeed(mnemonic); expect(seed).to.be.instanceOf(Uint8Array); - expect(await wallet.deriveKeyFromSeedPhrase(mnemonic, null, 'testnet')).to.exist(); - expect(await wallet.deriveKeyFromSeedWithPath(mnemonic, null, "m/44'/5'/0'", 'testnet')).to.exist(); - expect(await wallet.deriveKeyFromSeedWithExtendedPath(mnemonic, null, "m/15'/0'", 'testnet')).to.exist(); + expect(await wallet.deriveKeyFromSeedPhrase({ mnemonic, passphrase: null, network: 'testnet' })).to.exist(); + expect(await wallet.deriveKeyFromSeedWithPath({ + mnemonic, passphrase: null, path: "m/44'/5'/0'", network: 'testnet', + })).to.exist(); + expect(await wallet.deriveKeyFromSeedWithExtendedPath({ + mnemonic, passphrase: null, path: "m/15'/0'", network: 'testnet', + })).to.exist(); }); it('key utilities return expected shapes', async () => { diff --git a/packages/js-evo-sdk/tests/unit/facades/dpns.spec.mjs b/packages/js-evo-sdk/tests/unit/facades/dpns.spec.mjs index a0b2e0da145..d17931a6500 100644 --- a/packages/js-evo-sdk/tests/unit/facades/dpns.spec.mjs +++ b/packages/js-evo-sdk/tests/unit/facades/dpns.spec.mjs @@ -37,9 +37,9 @@ describe('DPNSFacade', () => { await client.dpns.registerName({ label: 'l', identityId: 'i', publicKeyId: 1, privateKeyWif: 'w', }); - await client.dpns.usernames('i', { limit: 2 }); + await client.dpns.usernames({ identityId: 'i', limit: 2 }); await client.dpns.username('i'); - await client.dpns.usernamesWithProof('i', { limit: 3 }); + await client.dpns.usernamesWithProof({ identityId: 'i', limit: 3 }); await client.dpns.usernameWithProof('i'); await client.dpns.getUsernameByName('u'); await client.dpns.getUsernameByNameWithProof('u'); @@ -47,9 +47,9 @@ describe('DPNSFacade', () => { expect(wasmSdk.dpnsIsNameAvailable).to.be.calledOnceWithExactly('label'); expect(wasmSdk.dpnsResolveName).to.be.calledOnceWithExactly('name'); expect(wasmSdk.dpnsRegisterName).to.be.calledOnce(); - expect(wasmSdk.getDpnsUsernames).to.be.calledOnceWithExactly('i', 2); + expect(wasmSdk.getDpnsUsernames).to.be.calledOnceWithExactly({ identityId: 'i', limit: 2 }); expect(wasmSdk.getDpnsUsername).to.be.calledOnceWithExactly('i'); - expect(wasmSdk.getDpnsUsernamesWithProofInfo).to.be.calledOnceWithExactly('i', 3); + expect(wasmSdk.getDpnsUsernamesWithProofInfo).to.be.calledOnceWithExactly({ identityId: 'i', limit: 3 }); expect(wasmSdk.getDpnsUsernameWithProofInfo).to.be.calledOnceWithExactly('i'); expect(wasmSdk.getDpnsUsernameByName).to.be.calledOnceWithExactly('u'); expect(wasmSdk.getDpnsUsernameByNameWithProofInfo).to.be.calledOnceWithExactly('u'); diff --git a/packages/js-evo-sdk/tests/unit/facades/group.spec.mjs b/packages/js-evo-sdk/tests/unit/facades/group.spec.mjs index f1333c0b1ca..3092f17a284 100644 --- a/packages/js-evo-sdk/tests/unit/facades/group.spec.mjs +++ b/packages/js-evo-sdk/tests/unit/facades/group.spec.mjs @@ -91,12 +91,18 @@ describe('GroupFacade', () => { status: 'CLOSED', }; await client.group.actionsWithProof(proofQuery); - await client.group.actionSigners('contract', 1, 'ACTIVE', 'action'); - await client.group.actionSignersWithProof('contract', 1, 'ACTIVE', 'action'); + const signersQuery = { + dataContractId: 'contract', + groupContractPosition: 1, + status: 'ACTIVE', + actionId: 'action', + }; + await client.group.actionSigners(signersQuery); + await client.group.actionSignersWithProof(signersQuery); expect(wasmSdk.getGroupActions).to.be.calledOnceWithExactly(query); expect(wasmSdk.getGroupActionsWithProofInfo).to.be.calledOnceWithExactly(proofQuery); - expect(wasmSdk.getGroupActionSigners).to.be.calledOnceWithExactly('contract', 1, 'ACTIVE', 'action'); - expect(wasmSdk.getGroupActionSignersWithProofInfo).to.be.calledOnceWithExactly('contract', 1, 'ACTIVE', 'action'); + expect(wasmSdk.getGroupActionSigners).to.be.calledOnceWithExactly(signersQuery); + expect(wasmSdk.getGroupActionSignersWithProofInfo).to.be.calledOnceWithExactly(signersQuery); }); it('groupsDataContracts() forwards', async () => { diff --git a/packages/js-evo-sdk/tests/unit/facades/identities.spec.mjs b/packages/js-evo-sdk/tests/unit/facades/identities.spec.mjs index b5592162c7a..d0b39aa8d65 100644 --- a/packages/js-evo-sdk/tests/unit/facades/identities.spec.mjs +++ b/packages/js-evo-sdk/tests/unit/facades/identities.spec.mjs @@ -119,15 +119,13 @@ describe('IdentitiesFacade', () => { expect(wasmSdk.getIdentityByNonUniquePublicKeyHashWithProofInfo).to.be.calledOnceWithExactly('hash', undefined); }); - it('contractKeys helpers convert purposes to Uint32Array and forward', async () => { - await client.identities.contractKeys({ identityIds: ['a'], contractId: 'c', purposes: [1, 2] }); - await client.identities.contractKeysWithProof({ identityIds: ['b'], contractId: 'c' }); - const arrayCall = wasmSdk.getIdentitiesContractKeys.firstCall.args; - expect(arrayCall[0]).to.deep.equal(['a']); - expect(arrayCall[1]).to.equal('c'); - expect(arrayCall[2]).to.be.instanceOf(Uint32Array); - expect(Array.from(arrayCall[2])).to.deep.equal([1, 2]); - expect(wasmSdk.getIdentitiesContractKeysWithProofInfo).to.be.calledOnceWithExactly(['b'], 'c', null); + it('contractKeys helpers forward query object', async () => { + const query = { identityIds: ['a'], contractId: 'c', purposes: [1, 2] }; + await client.identities.contractKeys(query); + const proofQuery = { identityIds: ['b'], contractId: 'c' }; + await client.identities.contractKeysWithProof(proofQuery); + expect(wasmSdk.getIdentitiesContractKeys).to.be.calledOnceWithExactly(query); + expect(wasmSdk.getIdentitiesContractKeysWithProofInfo).to.be.calledOnceWithExactly(proofQuery); }); it('tokenBalances helpers forward to wasm', async () => { diff --git a/packages/js-evo-sdk/tests/unit/facades/protocol.spec.mjs b/packages/js-evo-sdk/tests/unit/facades/protocol.spec.mjs index 8c3eebd1938..bee9c83ed07 100644 --- a/packages/js-evo-sdk/tests/unit/facades/protocol.spec.mjs +++ b/packages/js-evo-sdk/tests/unit/facades/protocol.spec.mjs @@ -24,10 +24,18 @@ describe('ProtocolFacade', () => { expect(wasmSdk.getProtocolVersionUpgradeStateWithProofInfo).to.be.calledOnce(); }); - it('versionUpgradeVoteStatus and withProof forward with args', async () => { - await client.protocol.versionUpgradeVoteStatus({ startProTxHash: 'h', count: 5 }); - await client.protocol.versionUpgradeVoteStatusWithProof({ startProTxHash: 'g', count: 3 }); + it('versionUpgradeVoteStatus and withProof forward with positional args', async () => { + await client.protocol.versionUpgradeVoteStatus('h', 5); + await client.protocol.versionUpgradeVoteStatusWithProof('g', 3); expect(wasmSdk.getProtocolVersionUpgradeVoteStatus).to.be.calledOnceWithExactly('h', 5); expect(wasmSdk.getProtocolVersionUpgradeVoteStatusWithProofInfo).to.be.calledOnceWithExactly('g', 3); }); + + it('versionUpgradeVoteStatus accepts Uint8Array and positional args', async () => { + const bytes = new Uint8Array([0xde, 0xad, 0xbe, 0xef]); + await client.protocol.versionUpgradeVoteStatus(bytes, 2); + await client.protocol.versionUpgradeVoteStatusWithProof(bytes, 4); + expect(wasmSdk.getProtocolVersionUpgradeVoteStatus).to.be.calledWith(bytes, 2); + expect(wasmSdk.getProtocolVersionUpgradeVoteStatusWithProofInfo).to.be.calledWith(bytes, 4); + }); }); diff --git a/packages/wasm-dpp2/src/identifier.rs b/packages/wasm-dpp2/src/identifier.rs index 2f2037aee03..74c3cf579ed 100644 --- a/packages/wasm-dpp2/src/identifier.rs +++ b/packages/wasm-dpp2/src/identifier.rs @@ -14,6 +14,11 @@ use wasm_bindgen::prelude::*; #[wasm_bindgen(js_name = "Identifier")] pub struct IdentifierWasm(Identifier); +#[wasm_bindgen(typescript_custom_section)] +const IDENTIFIER_TS_HELPERS: &'static str = r#" +export type IdentifierLike = Identifier | Uint8Array | string; +"#; + impl From for Identifier { fn from(identifier: IdentifierWasm) -> Self { identifier.0 diff --git a/packages/wasm-sdk/Cargo.toml b/packages/wasm-sdk/Cargo.toml index defe5d10511..9f61fb3b7cb 100644 --- a/packages/wasm-sdk/Cargo.toml +++ b/packages/wasm-sdk/Cargo.toml @@ -10,58 +10,58 @@ crate-type = ["cdylib"] [features] default = [ - "dpns-contract", - "dashpay-contract", - "wallet-utils-contract", - "token-history-contract", - "keywords-contract", - "mocks", + "dpns-contract", + "dashpay-contract", + "wallet-utils-contract", + "token-history-contract", + "keywords-contract", + "mocks", ] mocks = ["dash-sdk/mocks"] # All system contracts all-system-contracts = [ - "dash-sdk/all-system-contracts", - "rs-sdk-trusted-context-provider/all-system-contracts", + "dash-sdk/all-system-contracts", + "rs-sdk-trusted-context-provider/all-system-contracts", ] # Individual contract features withdrawals-contract = [ - "dash-sdk/withdrawals-contract", - "rs-sdk-trusted-context-provider/withdrawals-contract", + "dash-sdk/withdrawals-contract", + "rs-sdk-trusted-context-provider/withdrawals-contract", ] dpns-contract = [ - "dash-sdk/dpns-contract", - "rs-sdk-trusted-context-provider/dpns-contract", + "dash-sdk/dpns-contract", + "rs-sdk-trusted-context-provider/dpns-contract", ] dashpay-contract = [ - "dash-sdk/dashpay-contract", - "rs-sdk-trusted-context-provider/dashpay-contract", + "dash-sdk/dashpay-contract", + "rs-sdk-trusted-context-provider/dashpay-contract", ] wallet-utils-contract = [ - "dash-sdk/wallet-utils-contract", - "rs-sdk-trusted-context-provider/wallet-utils-contract", + "dash-sdk/wallet-utils-contract", + "rs-sdk-trusted-context-provider/wallet-utils-contract", ] token-history-contract = [ - "dash-sdk/token-history-contract", - "rs-sdk-trusted-context-provider/token-history-contract", + "dash-sdk/token-history-contract", + "rs-sdk-trusted-context-provider/token-history-contract", ] keywords-contract = [ - "dash-sdk/keywords-contract", - "rs-sdk-trusted-context-provider/keywords-contract", + "dash-sdk/keywords-contract", + "rs-sdk-trusted-context-provider/keywords-contract", ] token_reward_explanations = ["dash-sdk/token_reward_explanations"] [dependencies] dash-sdk = { path = "../rs-sdk", features = [ - "serde", - "core_key_wallet", + "serde", + "core_key_wallet", ], default-features = false } simple-signer = { path = "../simple-signer", features = ["state-transitions"] } drive = { path = "../rs-drive", default-features = false, features = [ - "verify", + "verify", ] } console_error_panic_hook = { version = "0.1.6" } thiserror = { version = "2.0.12" } @@ -70,8 +70,8 @@ wasm-bindgen-futures = { version = "0.4.49" } drive-proof-verifier = { path = "../rs-drive-proof-verifier", default-features = false } # TODO: I think it's not needed (LKl) tracing = { version = "0.1.41" } tracing-subscriber = { version = "0.3", default-features = false, features = [ - "env-filter", - "registry", + "env-filter", + "registry", ] } tracing-wasm = { version = "0.2.1" } platform-value = { path = "../rs-platform-value", features = ["json"] } @@ -80,7 +80,6 @@ serde-wasm-bindgen = { version = "0.6.5" } serde_json = "1.0" hex = "0.4" base64 = "0.22" -bs58 = "0.5" getrandom = { version = "0.2", features = ["js"] } bip39 = { version = "2.0", features = ["rand", "all-languages"] } rand = { version = "0.8", features = ["std"] } diff --git a/packages/wasm-sdk/src/dpns.rs b/packages/wasm-sdk/src/dpns.rs index 5868de72ffb..7af536d4af4 100644 --- a/packages/wasm-sdk/src/dpns.rs +++ b/packages/wasm-sdk/src/dpns.rs @@ -1,5 +1,5 @@ use crate::error::WasmSdkError; -use crate::queries::utils::identifier_from_js; +use crate::queries::utils::{deserialize_required_query, identifier_from_js}; use crate::queries::{ProofInfoWasm, ProofMetadataResponseWasm, ResponseMetadataWasm}; use crate::sdk::WasmSdk; use dash_sdk::dpp::document::{Document, DocumentV0Getters}; @@ -18,7 +18,7 @@ use serde::{Deserialize, Serialize}; use simple_signer::SingleKeySigner; use wasm_bindgen::prelude::wasm_bindgen; use wasm_bindgen::JsValue; - +use wasm_dpp2::identifier::IdentifierWasm; #[derive(Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RegisterDpnsNameResult { @@ -35,6 +35,83 @@ struct DpnsUsernameInfo { document_id: String, } +const DEFAULT_DPNS_USERNAMES_LIMIT: u32 = 10; + +fn resolve_dpns_usernames_limit(limit: Option) -> u32 { + match limit { + Some(0) | None => DEFAULT_DPNS_USERNAMES_LIMIT, + Some(value) => value, + } +} + +fn usernames_from_documents(documents_result: Documents) -> Array { + let usernames_array = Array::new(); + for (_, doc_opt) in documents_result { + if let Some(doc) = doc_opt { + let properties = doc.properties(); + if let (Some(Value::Text(label)), Some(Value::Text(parent_domain))) = ( + properties.get("label"), + properties.get("normalizedParentDomainName"), + ) { + let username = format!("{}.{}", label, parent_domain); + usernames_array.push(&JsValue::from(username)); + } + } + } + usernames_array +} + +// TS definition for DpnsUsernamesQuery used by getDpnsUsernames* +#[wasm_bindgen(typescript_custom_section)] +const DPNS_USERNAMES_QUERY_TS: &'static str = r#" +/** + * Query parameters for retrieving DPNS usernames. + */ +export interface DpnsUsernamesQuery { + /** + * Identity to fetch usernames for. + */ + identityId: IdentifierLike; + + /** + * Maximum number of usernames to return. Use 0 for default. + * @default 10 + */ + limit?: number; +} +"#; + +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(typescript_type = "DpnsUsernamesQuery")] + pub type DpnsUsernamesQueryJs; +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct DpnsUsernamesQueryInput { + identity_id: IdentifierWasm, + #[serde(default)] + limit: Option, +} + +struct DpnsUsernamesQueryParsed { + identity_id: Identifier, + limit: Option, +} + +fn parse_dpns_usernames_query( + query: DpnsUsernamesQueryJs, +) -> Result { + let input: DpnsUsernamesQueryInput = + deserialize_required_query(query, "Query object is required", "DPNS usernames query")?; + + Ok(DpnsUsernamesQueryParsed { + identity_id: input.identity_id.into(), + limit: input.limit, + }) +} + #[wasm_bindgen(js_name = "DpnsUsernamesProofResponse")] #[derive(Clone)] pub struct DpnsUsernamesProofResponseWasm { @@ -56,6 +133,70 @@ pub struct DpnsUsernameProofResponseWasm { #[wasm_bindgen(getter_with_clone)] pub proof: ProofInfoWasm, } +impl WasmSdk { + async fn prepare_dpns_usernames_query( + &self, + identity_id: Identifier, + limit: Option, + ) -> Result { + const DPNS_CONTRACT_ID: &str = "GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec"; + const DPNS_DOCUMENT_TYPE: &str = "domain"; + + let contract_id = + Identifier::from_string(DPNS_CONTRACT_ID, Encoding::Base58).map_err(|e| { + WasmSdkError::invalid_argument(format!("Invalid DPNS contract ID: {}", e)) + })?; + + let mut query = DocumentQuery::new_with_data_contract_id( + self.as_ref(), + contract_id, + DPNS_DOCUMENT_TYPE, + ) + .await?; + + let where_clause = WhereClause { + field: "records.identity".to_string(), + operator: WhereOperator::Equal, + value: Value::Identifier(identity_id.to_buffer()), + }; + + query = query.with_where(where_clause); + query.limit = resolve_dpns_usernames_limit(limit); + + Ok(query) + } + + async fn fetch_dpns_usernames( + &self, + identity_id: Identifier, + limit: Option, + ) -> Result { + let query = self + .prepare_dpns_usernames_query(identity_id, limit) + .await?; + let documents_result: Documents = Document::fetch_many(self.as_ref(), query).await?; + Ok(usernames_from_documents(documents_result)) + } + + async fn fetch_dpns_usernames_with_proof( + &self, + identity_id: Identifier, + limit: Option, + ) -> Result { + let query = self + .prepare_dpns_usernames_query(identity_id, limit) + .await?; + let (documents_result, metadata, proof) = + Document::fetch_many_with_metadata_and_proof(self.as_ref(), query, None).await?; + let usernames_array = usernames_from_documents(documents_result); + + Ok(DpnsUsernamesProofResponseWasm { + usernames: usernames_array, + metadata: metadata.into(), + proof: proof.into(), + }) + } +} #[wasm_bindgen] impl WasmSdk { @@ -78,11 +219,12 @@ impl WasmSdk { pub async fn dpns_register_name( &self, label: &str, - #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] + #[wasm_bindgen(js_name = "identityId")] + #[wasm_bindgen(unchecked_param_type = "IdentifierLike")] identity_id: JsValue, - public_key_id: u32, - private_key_wif: &str, - preorder_callback: Option, + #[wasm_bindgen(js_name = "publicKeyId")] public_key_id: u32, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: &str, + #[wasm_bindgen(js_name = "preorderCallback")] preorder_callback: Option, ) -> Result { let identity_id_parsed = identifier_from_js(&identity_id, "identity ID")?; @@ -102,7 +244,8 @@ impl WasmSdk { .clone(); thread_local! { - static PREORDER_CALLBACK: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + static PREORDER_CALLBACK : std::cell::RefCell < Option < js_sys::Function >> + = const { std::cell::RefCell::new(None) }; } if let Some(ref js_callback) = preorder_callback { @@ -115,16 +258,15 @@ impl WasmSdk { Some(Box::new(move |doc: &Document| { PREORDER_CALLBACK.with(|cb| { if let Some(js_callback) = cb.borrow().as_ref() { - let preorder_info = serde_json::json!({ - "documentId": doc.id().to_string(Encoding::Base58), - "ownerId": doc.owner_id().to_string(Encoding::Base58), - "revision": doc.revision().unwrap_or(0), - "createdAt": doc.created_at(), - "createdAtBlockHeight": doc.created_at_block_height(), - "createdAtCoreBlockHeight": doc.created_at_core_block_height(), - "message": "Preorder document submitted successfully", - }); - + let preorder_info = serde_json::json!( + { "documentId" : doc.id().to_string(Encoding::Base58), + "ownerId" : doc.owner_id().to_string(Encoding::Base58), + "revision" : doc.revision().unwrap_or(0), "createdAt" : doc + .created_at(), "createdAtBlockHeight" : doc + .created_at_block_height(), "createdAtCoreBlockHeight" : doc + .created_at_core_block_height(), "message" : + "Preorder document submitted successfully", } + ); if let Ok(js_value) = serde_wasm_bindgen::to_value(&preorder_info) { let _ = js_callback.call1(&JsValue::NULL, &js_value); } @@ -307,67 +449,27 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getDpnsUsernames")] pub async fn get_dpns_usernames( &self, - #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] - identity_id: JsValue, - limit: Option, + query: DpnsUsernamesQueryJs, ) -> Result { - const DPNS_CONTRACT_ID: &str = "GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec"; - const DPNS_DOCUMENT_TYPE: &str = "domain"; - - let identity_id_parsed = identifier_from_js(&identity_id, "identity ID")?; - - let contract_id = - Identifier::from_string(DPNS_CONTRACT_ID, Encoding::Base58).map_err(|e| { - WasmSdkError::invalid_argument(format!("Invalid DPNS contract ID: {}", e)) - })?; - - let mut query = DocumentQuery::new_with_data_contract_id( - self.as_ref(), - contract_id, - DPNS_DOCUMENT_TYPE, - ) - .await?; - - let where_clause = WhereClause { - field: "records.identity".to_string(), - operator: WhereOperator::Equal, - value: Value::Identifier(identity_id_parsed.to_buffer()), - }; - - query = query.with_where(where_clause); - query.limit = limit.unwrap_or(10); - - let documents_result: Documents = Document::fetch_many(self.as_ref(), query).await?; - - let usernames_array = Array::new(); - - for (_, doc_opt) in documents_result { - if let Some(doc) = doc_opt { - let properties = doc.properties(); - - if let (Some(Value::Text(label)), Some(Value::Text(parent_domain))) = ( - properties.get("label"), - properties.get("normalizedParentDomainName"), - ) { - let username = format!("{}.{}", label, parent_domain); - usernames_array.push(&JsValue::from(username)); - } - } - } - - Ok(usernames_array.into()) + let params = parse_dpns_usernames_query(query)?; + let usernames = self + .fetch_dpns_usernames(params.identity_id, params.limit) + .await?; + Ok(usernames.into()) } #[wasm_bindgen(js_name = "getDpnsUsername")] pub async fn get_dpns_username( &self, - #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] + #[wasm_bindgen(js_name = "identityId")] + #[wasm_bindgen(unchecked_param_type = "IdentifierLike")] identity_id: JsValue, ) -> Result { - let result = self - .get_dpns_usernames(identity_id.clone(), Some(1)) + let identity_id_parsed = identifier_from_js(&identity_id, "identity ID")?; + + let array = self + .fetch_dpns_usernames(identity_id_parsed, Some(1)) .await?; - let array = Array::from(&result); if array.length() > 0 { Ok(array.get(0)) @@ -375,78 +477,31 @@ impl WasmSdk { Ok(JsValue::NULL) } } - #[wasm_bindgen(js_name = "getDpnsUsernamesWithProofInfo")] pub async fn get_dpns_usernames_with_proof_info( &self, - #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] - identity_id: JsValue, - limit: Option, + query: DpnsUsernamesQueryJs, ) -> Result { - const DPNS_CONTRACT_ID: &str = "GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec"; - const DPNS_DOCUMENT_TYPE: &str = "domain"; - - let identity_id_parsed = identifier_from_js(&identity_id, "identity ID")?; - - let contract_id = - Identifier::from_string(DPNS_CONTRACT_ID, Encoding::Base58).map_err(|e| { - WasmSdkError::invalid_argument(format!("Invalid DPNS contract ID: {}", e)) - })?; - - let mut query = DocumentQuery::new_with_data_contract_id( - self.as_ref(), - contract_id, - DPNS_DOCUMENT_TYPE, - ) - .await?; - - let where_clause = WhereClause { - field: "records.identity".to_string(), - operator: WhereOperator::Equal, - value: Value::Identifier(identity_id_parsed.to_buffer()), - }; - - query = query.with_where(where_clause); - query.limit = limit.unwrap_or(10); - - let (documents_result, metadata, proof) = - Document::fetch_many_with_metadata_and_proof(self.as_ref(), query, None).await?; - - let usernames_array = Array::new(); - - for (_, doc_opt) in documents_result { - if let Some(doc) = doc_opt { - let properties = doc.properties(); - - if let (Some(Value::Text(label)), Some(Value::Text(parent_domain))) = ( - properties.get("label"), - properties.get("normalizedParentDomainName"), - ) { - let username = format!("{}.{}", label, parent_domain); - usernames_array.push(&JsValue::from(username)); - } - } - } - - Ok(DpnsUsernamesProofResponseWasm { - usernames: usernames_array, - metadata: metadata.into(), - proof: proof.into(), - }) + let params = parse_dpns_usernames_query(query)?; + self.fetch_dpns_usernames_with_proof(params.identity_id, params.limit) + .await } #[wasm_bindgen(js_name = "getDpnsUsernameWithProofInfo")] pub async fn get_dpns_username_with_proof_info( &self, - #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] + #[wasm_bindgen(js_name = "identityId")] + #[wasm_bindgen(unchecked_param_type = "IdentifierLike")] identity_id: JsValue, ) -> Result { + let identity_id_parsed = identifier_from_js(&identity_id, "identity ID")?; + let DpnsUsernamesProofResponseWasm { usernames, metadata, proof, } = self - .get_dpns_usernames_with_proof_info(identity_id.clone(), Some(1)) + .fetch_dpns_usernames_with_proof(identity_id_parsed, Some(1)) .await?; let username = if usernames.length() > 0 { diff --git a/packages/wasm-sdk/src/queries/data_contract.rs b/packages/wasm-sdk/src/queries/data_contract.rs index c366f5d5b03..cc144cb31e3 100644 --- a/packages/wasm-sdk/src/queries/data_contract.rs +++ b/packages/wasm-sdk/src/queries/data_contract.rs @@ -54,7 +54,7 @@ export interface DataContractHistoryQuery { /** * Data contract identifier. */ - dataContractId: Identifier | Uint8Array | string; + dataContractId: IdentifierLike /** * Maximum number of entries to return. @@ -128,6 +128,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getDataContract")] pub async fn get_data_contract( &self, + #[wasm_bindgen(js_name = "contractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] contract_id: JsValue, ) -> Result, WasmSdkError> { @@ -147,6 +148,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getDataContractWithProofInfo")] pub async fn get_data_contract_with_proof_info( &self, + #[wasm_bindgen(js_name = "contractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] contract_id: JsValue, ) -> Result { diff --git a/packages/wasm-sdk/src/queries/document.rs b/packages/wasm-sdk/src/queries/document.rs index f07542d5adf..aa61b74505d 100644 --- a/packages/wasm-sdk/src/queries/document.rs +++ b/packages/wasm-sdk/src/queries/document.rs @@ -17,6 +17,7 @@ use wasm_bindgen::prelude::wasm_bindgen; use wasm_bindgen::JsValue; use wasm_dpp2::data_contract::document::DocumentWasm; use wasm_dpp2::identifier::IdentifierWasm; + #[wasm_bindgen(js_name = "DocumentProofResponse")] #[derive(Clone)] pub struct DocumentProofResponseWasm { @@ -78,7 +79,7 @@ export interface DocumentsQuery { /** * Data contract identifier. */ - dataContractId: Identifier | Uint8Array | string; + dataContractId: IdentifierLike /** * Document type name. @@ -107,13 +108,13 @@ export interface DocumentsQuery { * Exclusive document ID to resume from. * @default undefined */ - startAfter?: Identifier | Uint8Array | string; + startAfter?: IdentifierLike /** * Inclusive document ID to start from. * @default undefined */ - startAt?: Identifier | Uint8Array | string; + startAt?: IdentifierLike } "#; @@ -242,7 +243,7 @@ fn parse_where_clause(json_clause: &JsonValue) -> Result Result { return Err(WasmSdkError::invalid_argument( "order by direction must be 'asc' or 'desc'", - )) + )); } }; @@ -307,6 +308,7 @@ fn json_to_platform_value(json_val: &JsonValue) -> Result { } } JsonValue::String(s) => { + // TODO: Should use Identifier::try_from and return text if failed // Check if it's an identifier (base58 encoded) if s.len() == 44 && s.chars().all(|c| c.is_alphanumeric()) { // Try to parse as identifier @@ -410,9 +412,11 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getDocument")] pub async fn get_document( &self, + #[wasm_bindgen(js_name = "dataContractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] data_contract_id: JsValue, - document_type: &str, + #[wasm_bindgen(js_name = "documentType")] document_type: &str, + #[wasm_bindgen(js_name = "documentId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] document_id: JsValue, ) -> Result, WasmSdkError> { @@ -455,9 +459,11 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getDocumentWithProofInfo")] pub async fn get_document_with_proof_info( &self, + #[wasm_bindgen(js_name = "dataContractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] data_contract_id: JsValue, - document_type: &str, + #[wasm_bindgen(js_name = "documentType")] document_type: &str, + #[wasm_bindgen(js_name = "documentId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] document_id: JsValue, ) -> Result { diff --git a/packages/wasm-sdk/src/queries/epoch.rs b/packages/wasm-sdk/src/queries/epoch.rs index 2319f6bdfe2..451fae37aff 100644 --- a/packages/wasm-sdk/src/queries/epoch.rs +++ b/packages/wasm-sdk/src/queries/epoch.rs @@ -537,7 +537,7 @@ impl WasmSdk { pub async fn get_evonodes_proposed_epoch_blocks_by_ids_with_proof_info( &self, epoch: u16, - pro_tx_hashes: Vec, + #[wasm_bindgen(js_name = "proTxHashes")] pro_tx_hashes: Vec, ) -> Result { // TODO: Implement once SDK Query trait is implemented for ProposerBlockCountById // Currently not supported due to query format issues diff --git a/packages/wasm-sdk/src/queries/group.rs b/packages/wasm-sdk/src/queries/group.rs index e073e73f789..dc69541b7ed 100644 --- a/packages/wasm-sdk/src/queries/group.rs +++ b/packages/wasm-sdk/src/queries/group.rs @@ -85,7 +85,7 @@ export interface GroupActionsStartAt { /** * Group action identifier. */ - actionId: Identifier | Uint8Array | string; + actionId: IdentifierLike /** * Include the `actionId` entry in the result set. @@ -101,7 +101,7 @@ export interface GroupActionsQuery { /** * Data contract identifier. */ - dataContractId: Identifier | Uint8Array | string; + dataContractId: IdentifierLike /** * Position of the group within the contract. @@ -133,6 +133,40 @@ extern "C" { pub type GroupActionsQueryJs; } +#[wasm_bindgen(typescript_custom_section)] +const GROUP_ACTION_SIGNERS_QUERY_TS: &'static str = r#" +/** + * Query parameters for retrieving signers of a group action. + */ +export interface GroupActionSignersQuery { + /** + * Data contract identifier. + */ + dataContractId: IdentifierLike + + /** + * Position of the group within the contract. + */ + groupContractPosition: number; + + /** + * Action status filter. + */ + status: GroupActionStatusFilter; + + /** + * Group action identifier. + */ + actionId: IdentifierLike +} +"#; + +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(typescript_type = "GroupActionSignersQuery")] + pub type GroupActionSignersQueryJs; +} + #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct GroupActionsQueryInput { @@ -218,6 +252,55 @@ fn parse_group_actions_query( }) } +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct GroupActionSignersQueryInput { + data_contract_id: IdentifierWasm, + group_contract_position: u32, + status: String, + action_id: IdentifierWasm, +} + +struct GroupActionSignersQueryParsed { + contract_id: Identifier, + group_contract_position: GroupContractPosition, + status: GroupActionStatus, + action_id: Identifier, +} + +fn parse_group_action_signers_query( + query: GroupActionSignersQueryJs, +) -> Result { + let input: GroupActionSignersQueryInput = deserialize_required_query( + query, + "Query object is required", + "group action signers query", + )?; + let GroupActionSignersQueryInput { + data_contract_id, + group_contract_position, + status, + action_id, + } = input; + let contract_id: Identifier = data_contract_id.into(); + let group_contract_position: GroupContractPosition = + group_contract_position.try_into().map_err(|_| { + WasmSdkError::invalid_argument(format!( + "groupContractPosition {} exceeds maximum of {}", + group_contract_position, + u16::MAX, + )) + })?; + let status = parse_group_action_status(&status)?; + let action_id: Identifier = action_id.into(); + Ok(GroupActionSignersQueryParsed { + contract_id, + group_contract_position, + status, + action_id, + }) +} + #[wasm_bindgen(typescript_custom_section)] const GROUP_INFOS_QUERY_TS: &'static str = r#" /** @@ -243,7 +326,7 @@ export interface GroupInfosQuery { /** * Data contract identifier. */ - dataContractId: Identifier | Uint8Array | string; + dataContractId: IdentifierLike /** * Cursor describing where to resume from. @@ -329,7 +412,7 @@ export interface GroupMembersQuery { /** * Data contract identifier. */ - dataContractId: Identifier | Uint8Array | string; + dataContractId: IdentifierLike /** * Group position inside the contract. @@ -346,7 +429,7 @@ export interface GroupMembersQuery { * Member identifier to resume from. * @default undefined */ - startAtMemberId?: Identifier | Uint8Array | string; + startAtMemberId?: IdentifierLike /** * Maximum number of members to return when not requesting specific IDs. @@ -371,7 +454,7 @@ export interface IdentityGroupsQuery { /** * Identity identifier. */ - identityId: Identifier | Uint8Array | string; + identityId: IdentifierLike /** * Data contracts where the identity participates as a member. @@ -509,9 +592,10 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getGroupInfo")] pub async fn get_group_info( &self, + #[wasm_bindgen(js_name = "dataContractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] data_contract_id: JsValue, - group_contract_position: u32, + #[wasm_bindgen(js_name = "groupContractPosition")] group_contract_position: u32, ) -> Result, WasmSdkError> { // Parse data contract ID let contract_id: Identifier = IdentifierWasm::try_from(&data_contract_id) @@ -554,7 +638,7 @@ impl WasmSdk { let members = collect_group_members_map(&group, &member_ids, &start_at_member_id, limit)?; return Ok(members); - }; + } Ok(Map::new()) } @@ -669,27 +753,16 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getGroupActionSigners")] pub async fn get_group_action_signers( &self, - #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] - contract_id: JsValue, - group_contract_position: u32, - status: &str, - #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] - action_id: JsValue, + query: GroupActionSignersQueryJs, ) -> Result { - let contract_id: Identifier = IdentifierWasm::try_from(&contract_id) - .map_err(|err| WasmSdkError::invalid_argument(format!("Invalid contract ID: {}", err)))? - .into(); - let action_id: Identifier = IdentifierWasm::try_from(&action_id) - .map_err(|err| WasmSdkError::invalid_argument(format!("Invalid action ID: {}", err)))? - .into(); - let status = parse_group_action_status(status)?; + let params = parse_group_action_signers_query(query)?; // Create query let query = GroupActionSignersQuery { - contract_id, - group_contract_position: group_contract_position as GroupContractPosition, - status, - action_id, + contract_id: params.contract_id, + group_contract_position: params.group_contract_position, + status: params.status, + action_id: params.action_id, }; // Fetch signers @@ -710,6 +783,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getGroupsDataContracts")] pub async fn get_groups_data_contracts( &self, + #[wasm_bindgen(js_name = "dataContractIds")] #[wasm_bindgen(unchecked_param_type = "Array")] data_contract_ids: Vec, ) -> Result { @@ -752,9 +826,10 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getGroupInfoWithProofInfo")] pub async fn get_group_info_with_proof_info( &self, + #[wasm_bindgen(js_name = "dataContractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] data_contract_id: JsValue, - group_contract_position: u32, + #[wasm_bindgen(js_name = "groupContractPosition")] group_contract_position: u32, ) -> Result { // Parse data contract ID let contract_id: Identifier = IdentifierWasm::try_from(&data_contract_id) @@ -952,27 +1027,14 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getGroupActionSignersWithProofInfo")] pub async fn get_group_action_signers_with_proof_info( &self, - #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] - contract_id: JsValue, - group_contract_position: u32, - status: &str, - #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] - action_id: JsValue, + query: GroupActionSignersQueryJs, ) -> Result { - let contract_id: Identifier = IdentifierWasm::try_from(&contract_id) - .map_err(|err| WasmSdkError::invalid_argument(format!("Invalid contract ID: {}", err)))? - .into(); - let action_id: Identifier = IdentifierWasm::try_from(&action_id) - .map_err(|err| WasmSdkError::invalid_argument(format!("Invalid action ID: {}", err)))? - .into(); - let status = parse_group_action_status(status)?; - - // Create query + let params = parse_group_action_signers_query(query)?; let query = GroupActionSignersQuery { - contract_id, - group_contract_position: group_contract_position as GroupContractPosition, - status, - action_id, + contract_id: params.contract_id, + group_contract_position: params.group_contract_position, + status: params.status, + action_id: params.action_id, }; // Fetch signers with proof @@ -997,6 +1059,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getGroupsDataContractsWithProofInfo")] pub async fn get_groups_data_contracts_with_proof_info( &self, + #[wasm_bindgen(js_name = "dataContractIds")] #[wasm_bindgen(unchecked_param_type = "Array")] data_contract_ids: Vec, ) -> Result { diff --git a/packages/wasm-sdk/src/queries/identity.rs b/packages/wasm-sdk/src/queries/identity.rs index 9e78ffbc718..31d5b014f41 100644 --- a/packages/wasm-sdk/src/queries/identity.rs +++ b/packages/wasm-sdk/src/queries/identity.rs @@ -6,7 +6,7 @@ use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicK use dash_sdk::dpp::identity::identity_public_key::IdentityPublicKey; use dash_sdk::platform::{Fetch, FetchMany, Identifier, Identity, IdentityKeysQuery}; use drive_proof_verifier::types::{IdentityPublicKeys, IndexMap}; -use js_sys::{Array, BigInt, Map}; +use js_sys::{Array, BigInt, Map, Uint8Array}; use rs_dapi_client::IntoInner; use serde::Deserialize; use std::collections::{BTreeMap, HashMap}; @@ -216,7 +216,67 @@ pub struct IdentityKeysProofResponseWasm { #[wasm_bindgen(getter_with_clone)] pub proof: ProofInfoWasm, } +#[wasm_bindgen(typescript_custom_section)] +const IDENTITIES_CONTRACT_KEYS_QUERY_TS: &'static str = r#" +/** + * Query parameters for fetching identities' public keys for a contract. + */ +export interface IdentitiesContractKeysQuery { + /** + * Identity identifiers to fetch keys for. + */ + identityIds: Array; + /** + * Data contract identifier (reserved for future filtering). + */ + contractId: IdentifierLike; + + /** + * Optional list of purposes to include. + * @default undefined + */ + purposes?: number[]; +} +"#; +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(typescript_type = "IdentitiesContractKeysQuery")] + pub type IdentitiesContractKeysQueryJs; +} +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct IdentitiesContractKeysQueryInput { + #[serde(rename = "identityIds")] + identity_ids: Vec, + #[serde(rename = "contractId")] + contract_id: IdentifierWasm, + #[serde(default)] + purposes: Option>, +} +struct IdentitiesContractKeysQueryParsed { + identity_ids: Vec, + contract_id: Identifier, + purposes: Option>, +} +fn parse_identities_contract_keys_query( + query: IdentitiesContractKeysQueryJs, +) -> Result { + let input: IdentitiesContractKeysQueryInput = deserialize_required_query( + query, + "Query object is required", + "identities contract keys query", + )?; + Ok(IdentitiesContractKeysQueryParsed { + identity_ids: input + .identity_ids + .into_iter() + .map(Identifier::from) + .collect(), + contract_id: input.contract_id.into(), + purposes: input.purposes, + }) +} #[wasm_bindgen(typescript_custom_section)] const IDENTITY_KEYS_QUERY_TS: &'static str = r#" /** @@ -273,7 +333,7 @@ export interface IdentityKeysQuery { /** * Identity identifier. */ - identityId: Identifier | Uint8Array | string; + identityId: IdentifierLike /** * Requested key selection strategy. @@ -372,6 +432,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentity")] pub async fn get_identity( &self, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, ) -> Result, WasmSdkError> { @@ -387,6 +448,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentityWithProofInfo")] pub async fn get_identity_with_proof_info( &self, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, ) -> Result { @@ -410,6 +472,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentityUnproved")] pub async fn get_identity_unproved( &self, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, ) -> Result { @@ -550,17 +613,27 @@ impl WasmSdk { Some(ResponseVersion::V0(response_v0)) => { if let Some(result) = response_v0.result { match result { - dash_sdk::platform::proto::get_identity_keys_response::get_identity_keys_response_v0::Result::Keys(keys_response) => { + dash_sdk::platform::proto::get_identity_keys_response::get_identity_keys_response_v0::Result::Keys( + keys_response, + ) => { let mut key_map: IdentityPublicKeys = IndexMap::new(); for key_bytes in keys_response.keys_bytes { use dash_sdk::dpp::serialization::PlatformDeserializable; - let key = dash_sdk::dpp::identity::identity_public_key::IdentityPublicKey::deserialize_from_bytes(key_bytes.as_slice()) - .map_err(|e| WasmSdkError::serialization(format!("Failed to deserialize identity public key: {}", e)))?; + let key = dash_sdk::dpp::identity::identity_public_key::IdentityPublicKey::deserialize_from_bytes( + key_bytes.as_slice(), + ) + .map_err(|e| WasmSdkError::serialization( + format!("Failed to deserialize identity public key: {}", e), + ))?; key_map.insert(key.id(), Some(key)); } key_map } - _ => return Err(WasmSdkError::generic("Unexpected response format")), + _ => { + return Err( + WasmSdkError::generic("Unexpected response format"), + ); + } } } else { return Err(WasmSdkError::not_found("No keys found in response")); @@ -586,6 +659,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentityNonce")] pub async fn get_identity_nonce( &self, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, ) -> Result { @@ -608,6 +682,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentityNonceWithProofInfo")] pub async fn get_identity_nonce_with_proof_info( &self, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, ) -> Result { @@ -636,8 +711,10 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentityContractNonce")] pub async fn get_identity_contract_nonce( &self, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, + #[wasm_bindgen(js_name = "contractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] contract_id: JsValue, ) -> Result { @@ -664,8 +741,10 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentityContractNonceWithProofInfo")] pub async fn get_identity_contract_nonce_with_proof_info( &self, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, + #[wasm_bindgen(js_name = "contractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] contract_id: JsValue, ) -> Result { @@ -702,6 +781,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentityBalance")] pub async fn get_identity_balance( &self, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, ) -> Result { @@ -722,6 +802,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentitiesBalances")] pub async fn get_identities_balances( &self, + #[wasm_bindgen(js_name = "identityIds")] #[wasm_bindgen(unchecked_param_type = "Array")] identity_ids: Vec, ) -> Result { @@ -760,6 +841,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentityBalanceAndRevision")] pub async fn get_identity_balance_and_revision( &self, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, ) -> Result { @@ -780,15 +862,19 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentityByPublicKeyHash")] pub async fn get_identity_by_public_key_hash( &self, - public_key_hash: &str, + #[wasm_bindgen(js_name = "publicKeyHash")] + #[wasm_bindgen(unchecked_param_type = "string | Uint8Array")] + public_key_hash: JsValue, ) -> Result { use dash_sdk::platform::types::identity::PublicKeyHash; - - // Parse the hex-encoded public key hash - let hash_bytes = hex::decode(public_key_hash).map_err(|e| { - WasmSdkError::invalid_argument(format!("Invalid public key hash hex: {}", e)) - })?; - + let hash_bytes: Vec = if let Some(hex_str) = public_key_hash.as_string() { + hex::decode(&hex_str).map_err(|e| { + WasmSdkError::invalid_argument(format!("Invalid public key hash hex: {}", e)) + })? + } else { + let arr = Uint8Array::new(&public_key_hash); + arr.to_vec() + }; if hash_bytes.len() != 20 { return Err(WasmSdkError::invalid_argument( "Public key hash must be 20 bytes (40 hex characters)", @@ -808,33 +894,15 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentitiesContractKeys")] pub async fn get_identities_contract_keys( &self, - #[wasm_bindgen(unchecked_param_type = "Array")] - identities_ids: Vec, - #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] - contract_id: JsValue, - purposes: Option>, + query: IdentitiesContractKeysQueryJs, ) -> Result { use dash_sdk::dpp::identity::Purpose; - - // Convert JS identity values to Identifiers - let identity_identifiers: Vec = identities_ids - .into_iter() - .map(|value| { - IdentifierWasm::try_from(&value) - .map(Identifier::from) - .map_err(|err| { - WasmSdkError::invalid_argument(format!("Invalid identity ID: {}", err)) - }) - }) - .collect::, _>>()?; - - // Contract ID is not used in the individual key queries, but we validate it - let _contract_identifier: Identifier = IdentifierWasm::try_from(&contract_id) - .map_err(|err| WasmSdkError::invalid_argument(format!("Invalid contract ID: {}", err)))? - .into(); + let params = parse_identities_contract_keys_query(query)?; + let identity_identifiers = params.identity_ids; + let _contract_identifier = params.contract_id; // Convert purposes if provided - let purposes_opt = purposes.map(|p| { + let purposes_opt = params.purposes.map(|p| { p.into_iter() .filter_map(|purpose_int| match purpose_int { 0 => Some(Purpose::AUTHENTICATION as u32), @@ -893,15 +961,21 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentityByNonUniquePublicKeyHash")] pub async fn get_identity_by_non_unique_public_key_hash( &self, - public_key_hash: &str, + #[wasm_bindgen(js_name = "publicKeyHash")] + #[wasm_bindgen(unchecked_param_type = "string | Uint8Array")] + public_key_hash: JsValue, + #[wasm_bindgen(js_name = "startAfterId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string | undefined")] start_after_id: JsValue, ) -> Result { - // Parse the hex-encoded public key hash - let hash_bytes = hex::decode(public_key_hash).map_err(|e| { - WasmSdkError::invalid_argument(format!("Invalid public key hash hex: {}", e)) - })?; - + let hash_bytes: Vec = if let Some(hex_str) = public_key_hash.as_string() { + hex::decode(&hex_str).map_err(|e| { + WasmSdkError::invalid_argument(format!("Invalid public key hash hex: {}", e)) + })? + } else { + let arr = Uint8Array::new(&public_key_hash); + arr.to_vec() + }; if hash_bytes.len() != 20 { return Err(WasmSdkError::invalid_argument( "Public key hash must be 20 bytes (40 hex characters)", @@ -946,8 +1020,10 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentityTokenBalances")] pub async fn get_identity_token_balances( &self, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, + #[wasm_bindgen(js_name = "tokenIds")] #[wasm_bindgen(unchecked_param_type = "Array")] token_ids: Vec, ) -> Result { @@ -1033,7 +1109,7 @@ impl WasmSdk { IdentityKeysRequestInput::Search { .. } => { return Err(WasmSdkError::invalid_argument( "Search key requests are not supported with proof", - )) + )); } }; @@ -1056,6 +1132,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentityBalanceWithProofInfo")] pub async fn get_identity_balance_with_proof_info( &self, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, ) -> Result { @@ -1084,6 +1161,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentitiesBalancesWithProofInfo")] pub async fn get_identities_balances_with_proof_info( &self, + #[wasm_bindgen(js_name = "identityIds")] #[wasm_bindgen(unchecked_param_type = "Array")] identity_ids: Vec, ) -> Result { @@ -1132,6 +1210,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentityBalanceAndRevisionWithProofInfo")] pub async fn get_identity_balance_and_revision_with_proof_info( &self, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, ) -> Result { @@ -1160,15 +1239,19 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentityByPublicKeyHashWithProofInfo")] pub async fn get_identity_by_public_key_hash_with_proof_info( &self, - public_key_hash: &str, + #[wasm_bindgen(js_name = "publicKeyHash")] + #[wasm_bindgen(unchecked_param_type = "string | Uint8Array")] + public_key_hash: JsValue, ) -> Result { use dash_sdk::platform::types::identity::PublicKeyHash; - - // Parse the hex-encoded public key hash - let hash_bytes = hex::decode(public_key_hash).map_err(|e| { - WasmSdkError::invalid_argument(format!("Invalid public key hash hex: {}", e)) - })?; - + let hash_bytes: Vec = if let Some(hex_str) = public_key_hash.as_string() { + hex::decode(&hex_str).map_err(|e| { + WasmSdkError::invalid_argument(format!("Invalid public key hash hex: {}", e)) + })? + } else { + let arr = Uint8Array::new(&public_key_hash); + arr.to_vec() + }; if hash_bytes.len() != 20 { return Err(WasmSdkError::invalid_argument( "Public key hash must be 20 bytes (40 hex characters)", @@ -1197,15 +1280,21 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentityByNonUniquePublicKeyHashWithProofInfo")] pub async fn get_identity_by_non_unique_public_key_hash_with_proof_info( &self, - public_key_hash: &str, + #[wasm_bindgen(js_name = "publicKeyHash")] + #[wasm_bindgen(unchecked_param_type = "string | Uint8Array")] + public_key_hash: JsValue, + #[wasm_bindgen(js_name = "startAfterId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string | undefined")] start_after_id: JsValue, ) -> Result { - // Parse the hex-encoded public key hash - let hash_bytes = hex::decode(public_key_hash).map_err(|e| { - WasmSdkError::invalid_argument(format!("Invalid public key hash hex: {}", e)) - })?; - + let hash_bytes: Vec = if let Some(hex_str) = public_key_hash.as_string() { + hex::decode(&hex_str).map_err(|e| { + WasmSdkError::invalid_argument(format!("Invalid public key hash hex: {}", e)) + })? + } else { + let arr = Uint8Array::new(&public_key_hash); + arr.to_vec() + }; if hash_bytes.len() != 20 { return Err(WasmSdkError::invalid_argument( "Public key hash must be 20 bytes (40 hex characters)", @@ -1254,36 +1343,19 @@ impl WasmSdk { )) } + // TODO: This method returns proof only for first identity #[wasm_bindgen(js_name = "getIdentitiesContractKeysWithProofInfo")] pub async fn get_identities_contract_keys_with_proof_info( &self, - #[wasm_bindgen(unchecked_param_type = "Array")] - identities_ids: Vec, - #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] - contract_id: JsValue, - purposes: Option>, + query: IdentitiesContractKeysQueryJs, ) -> Result { use dash_sdk::dpp::identity::Purpose; - - // Convert JS identity values to Identifiers - let identity_ids: Vec = identities_ids - .into_iter() - .map(|value| { - IdentifierWasm::try_from(&value) - .map(Identifier::from) - .map_err(|err| { - WasmSdkError::invalid_argument(format!("Invalid identity ID: {}", err)) - }) - }) - .collect::, _>>()?; - - // Contract ID is not used in the individual key queries, but we validate it - let _contract_identifier: Identifier = IdentifierWasm::try_from(&contract_id) - .map_err(|err| WasmSdkError::invalid_argument(format!("Invalid contract ID: {}", err)))? - .into(); + let params = parse_identities_contract_keys_query(query)?; + let identity_ids = params.identity_ids; + let _contract_identifier = params.contract_id; // Convert purposes if provided - let purposes_opt = purposes.map(|p| { + let purposes_opt = params.purposes.map(|p| { p.into_iter() .filter_map(|purpose_int| match purpose_int { 0 => Some(Purpose::AUTHENTICATION as u32), @@ -1359,8 +1431,10 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentityTokenBalancesWithProofInfo")] pub async fn get_identity_token_balances_with_proof_info( &self, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, + #[wasm_bindgen(js_name = "tokenIds")] #[wasm_bindgen(unchecked_param_type = "Array")] token_ids: Vec, ) -> Result { diff --git a/packages/wasm-sdk/src/queries/mod.rs b/packages/wasm-sdk/src/queries/mod.rs index 0c4c462807b..38aa9a77ca2 100644 --- a/packages/wasm-sdk/src/queries/mod.rs +++ b/packages/wasm-sdk/src/queries/mod.rs @@ -32,11 +32,11 @@ impl ResponseMetadataWasm { #[wasm_bindgen(constructor)] pub fn new( height: u64, - core_chain_locked_height: u32, + #[wasm_bindgen(js_name = "coreChainLockedHeight")] core_chain_locked_height: u32, epoch: u32, - time_ms: u64, - protocol_version: u32, - chain_id: Uint8Array, + #[wasm_bindgen(js_name = "timeMs")] time_ms: u64, + #[wasm_bindgen(js_name = "protocolVersion")] protocol_version: u32, + #[wasm_bindgen(js_name = "chainId")] chain_id: Uint8Array, ) -> Self { ResponseMetadataWasm { height, @@ -79,7 +79,7 @@ impl ResponseMetadataWasm { } #[wasm_bindgen(js_name = "setChainId")] - pub fn set_chain_id(&mut self, chain_id: Uint8Array) { + pub fn set_chain_id(&mut self, #[wasm_bindgen(js_name = "chainId")] chain_id: Uint8Array) { self.chain_id = chain_id.to_vec(); } } @@ -113,12 +113,12 @@ pub struct ProofInfoWasm { impl ProofInfoWasm { #[wasm_bindgen(constructor)] pub fn new( - grovedb_proof: Uint8Array, - quorum_hash: Uint8Array, + #[wasm_bindgen(js_name = "grovedbProof")] grovedb_proof: Uint8Array, + #[wasm_bindgen(js_name = "quorumHash")] quorum_hash: Uint8Array, signature: Uint8Array, round: u32, - block_id_hash: Uint8Array, - quorum_type: u32, + #[wasm_bindgen(js_name = "blockIdHash")] block_id_hash: Uint8Array, + #[wasm_bindgen(js_name = "quorumType")] quorum_type: u32, ) -> Self { ProofInfoWasm { grovedb_proof: grovedb_proof.to_vec(), @@ -161,12 +161,18 @@ impl ProofInfoWasm { } #[wasm_bindgen(js_name = "setGrovedbProof")] - pub fn set_grovedb_proof(&mut self, grovedb_proof: Uint8Array) { + pub fn set_grovedb_proof( + &mut self, + #[wasm_bindgen(js_name = "grovedbProof")] grovedb_proof: Uint8Array, + ) { self.grovedb_proof = grovedb_proof.to_vec(); } #[wasm_bindgen(js_name = "setQuorumHash")] - pub fn set_quorum_hash(&mut self, quorum_hash: Uint8Array) { + pub fn set_quorum_hash( + &mut self, + #[wasm_bindgen(js_name = "quorumHash")] quorum_hash: Uint8Array, + ) { self.quorum_hash = quorum_hash.to_vec(); } @@ -176,7 +182,10 @@ impl ProofInfoWasm { } #[wasm_bindgen(js_name = "setBlockIdHash")] - pub fn set_block_id_hash(&mut self, block_id_hash: Uint8Array) { + pub fn set_block_id_hash( + &mut self, + #[wasm_bindgen(js_name = "blockIdHash")] block_id_hash: Uint8Array, + ) { self.block_id_hash = block_id_hash.to_vec(); } } diff --git a/packages/wasm-sdk/src/queries/protocol.rs b/packages/wasm-sdk/src/queries/protocol.rs index 5184418a176..402ac87abae 100644 --- a/packages/wasm-sdk/src/queries/protocol.rs +++ b/packages/wasm-sdk/src/queries/protocol.rs @@ -1,6 +1,7 @@ use crate::error::WasmSdkError; use crate::queries::ProofMetadataResponseWasm; use crate::sdk::WasmSdk; +use dash_sdk::dpp::dashcore::hashes::{sha256d, Hash as _}; use js_sys::Map; use wasm_bindgen::prelude::wasm_bindgen; use wasm_bindgen::JsValue; @@ -135,7 +136,9 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getProtocolVersionUpgradeVoteStatus")] pub async fn get_protocol_version_upgrade_vote_status( &self, - start_pro_tx_hash: &str, + #[wasm_bindgen(js_name = "startProTxHash")] + #[wasm_bindgen(unchecked_param_type = "string | Uint8Array")] + start_pro_tx_hash: JsValue, count: u32, ) -> Result { use dash_sdk::dpp::dashcore::ProTxHash; @@ -144,15 +147,30 @@ impl WasmSdk { use std::str::FromStr; // Parse the ProTxHash - let start_hash = - if start_pro_tx_hash.is_empty() { + let start_hash = if let Some(s) = start_pro_tx_hash.as_string() { + if s.is_empty() { None } else { - Some(ProTxHash::from_str(start_pro_tx_hash).map_err(|e| { + Some(ProTxHash::from_str(&s).map_err(|e| { WasmSdkError::invalid_argument(format!("Invalid ProTxHash: {}", e)) })?) - }; - + } + } else { + let bytes = js_sys::Uint8Array::new(&start_pro_tx_hash).to_vec(); + if bytes.is_empty() { + None + } else { + if bytes.len() != 32 { + return Err(WasmSdkError::invalid_argument( + "ProTxHash must be 32 bytes or an empty value", + )); + } + let mut arr = [0u8; 32]; + arr.copy_from_slice(&bytes); + let raw = sha256d::Hash::from_byte_array(arr); + Some(ProTxHash::from_raw_hash(raw)) + } + }; let votes_result = MasternodeProtocolVote::fetch_votes(self.as_ref(), start_hash, Some(count)).await?; @@ -223,7 +241,9 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getProtocolVersionUpgradeVoteStatusWithProofInfo")] pub async fn get_protocol_version_upgrade_vote_status_with_proof_info( &self, - start_pro_tx_hash: &str, + #[wasm_bindgen(js_name = "startProTxHash")] + #[wasm_bindgen(unchecked_param_type = "string | Uint8Array")] + start_pro_tx_hash: JsValue, count: u32, ) -> Result { // TODO: Implement once a proper fetch_many_with_metadata_and_proof method is available for MasternodeProtocolVote diff --git a/packages/wasm-sdk/src/queries/system.rs b/packages/wasm-sdk/src/queries/system.rs index c19fc32417d..075324f8905 100644 --- a/packages/wasm-sdk/src/queries/system.rs +++ b/packages/wasm-sdk/src/queries/system.rs @@ -757,6 +757,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getPrefundedSpecializedBalance")] pub async fn get_prefunded_specialized_balance( &self, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, ) -> Result { @@ -780,7 +781,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "waitForStateTransitionResult")] pub async fn wait_for_state_transition_result( &self, - state_transition_hash: &str, + #[wasm_bindgen(js_name = "stateTransitionHash")] state_transition_hash: &str, ) -> Result { use dapi_grpc::platform::v0::wait_for_state_transition_result_request::{ Version, WaitForStateTransitionResultRequestV0, @@ -929,6 +930,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getPrefundedSpecializedBalanceWithProofInfo")] pub async fn get_prefunded_specialized_balance_with_proof_info( &self, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, ) -> Result { diff --git a/packages/wasm-sdk/src/queries/token.rs b/packages/wasm-sdk/src/queries/token.rs index f374b9a0973..78901e4703b 100644 --- a/packages/wasm-sdk/src/queries/token.rs +++ b/packages/wasm-sdk/src/queries/token.rs @@ -119,9 +119,10 @@ impl WasmSdk { /// ``` #[wasm_bindgen(js_name = "calculateTokenIdFromContract")] pub fn calculate_token_id_from_contract( + #[wasm_bindgen(js_name = "contractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] contract_id: JsValue, - token_position: u16, + #[wasm_bindgen(js_name = "tokenPosition")] token_position: u16, ) -> Result { // Parse contract ID let contract_identifier = identifier_from_js(&contract_id, "contract ID")?; @@ -164,9 +165,10 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getTokenPriceByContract")] pub async fn get_token_price_by_contract( &self, + #[wasm_bindgen(js_name = "contractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] contract_id: JsValue, - token_position: u16, + #[wasm_bindgen(js_name = "tokenPosition")] token_position: u16, ) -> Result { // Parse contract ID let contract_identifier = identifier_from_js(&contract_id, "contract ID")?; @@ -186,19 +188,23 @@ impl WasmSdk { if let Some(price_opt) = prices_result.get(&token_identifier) { if let Some(schedule) = price_opt.as_ref() { let (base_price, current_price) = match &schedule { - dash_sdk::dpp::tokens::token_pricing_schedule::TokenPricingSchedule::SinglePrice(price) => { - (price.to_string(), price.to_string()) - }, - dash_sdk::dpp::tokens::token_pricing_schedule::TokenPricingSchedule::SetPrices(prices) => { + dash_sdk::dpp::tokens::token_pricing_schedule::TokenPricingSchedule::SinglePrice( + price, + ) => (price.to_string(), price.to_string()), + dash_sdk::dpp::tokens::token_pricing_schedule::TokenPricingSchedule::SetPrices( + prices, + ) => { // Use first price as base, last as current - let base = prices.first_key_value() + let base = prices + .first_key_value() .map(|(_, p)| p.to_string()) .unwrap_or_else(|| "0".to_string()); - let current = prices.last_key_value() + let current = prices + .last_key_value() .map(|(_, p)| p.to_string()) .unwrap_or_else(|| "0".to_string()); (base, current) - }, + } }; Ok(TokenPriceInfoWasm::new( @@ -225,8 +231,10 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentitiesTokenBalances")] pub async fn get_identities_token_balances( &self, + #[wasm_bindgen(js_name = "identityIds")] #[wasm_bindgen(unchecked_param_type = "Array")] identity_ids: Vec, + #[wasm_bindgen(js_name = "tokenId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] token_id: JsValue, ) -> Result { @@ -264,8 +272,10 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentityTokenInfos")] pub async fn get_identity_token_infos( &self, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, + #[wasm_bindgen(js_name = "tokenIds")] #[wasm_bindgen(unchecked_param_type = "Array")] token_ids: Vec, ) -> Result { @@ -304,8 +314,10 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentitiesTokenInfos")] pub async fn get_identities_token_infos( &self, + #[wasm_bindgen(js_name = "identityIds")] #[wasm_bindgen(unchecked_param_type = "Array")] identity_ids: Vec, + #[wasm_bindgen(js_name = "tokenId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] token_id: JsValue, ) -> Result { @@ -344,6 +356,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getTokenStatuses")] pub async fn get_token_statuses( &self, + #[wasm_bindgen(js_name = "tokenIds")] #[wasm_bindgen(unchecked_param_type = "Array")] token_ids: Vec, ) -> Result { @@ -371,6 +384,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getTokenDirectPurchasePrices")] pub async fn get_token_direct_purchase_prices( &self, + #[wasm_bindgen(js_name = "tokenIds")] #[wasm_bindgen(unchecked_param_type = "Array")] token_ids: Vec, ) -> Result { @@ -389,10 +403,12 @@ impl WasmSdk { if let Some(Some(schedule)) = prices_result.get(&token) { let token_id_wasm = IdentifierWasm::from(token); let (base_price, current_price) = match schedule { - dash_sdk::dpp::tokens::token_pricing_schedule::TokenPricingSchedule::SinglePrice(price) => { - (price.to_string(), price.to_string()) - } - dash_sdk::dpp::tokens::token_pricing_schedule::TokenPricingSchedule::SetPrices(prices) => { + dash_sdk::dpp::tokens::token_pricing_schedule::TokenPricingSchedule::SinglePrice( + price, + ) => (price.to_string(), price.to_string()), + dash_sdk::dpp::tokens::token_pricing_schedule::TokenPricingSchedule::SetPrices( + prices, + ) => { let base = prices .first_key_value() .map(|(_, p)| p.to_string()) @@ -419,6 +435,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getTokenContractInfo")] pub async fn get_token_contract_info( &self, + #[wasm_bindgen(js_name = "dataContractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] data_contract_id: JsValue, ) -> Result, WasmSdkError> { @@ -437,8 +454,10 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getTokenPerpetualDistributionLastClaim")] pub async fn get_token_perpetual_distribution_last_claim( &self, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, + #[wasm_bindgen(js_name = "tokenId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] token_id: JsValue, ) -> Result, WasmSdkError> { @@ -481,21 +500,38 @@ impl WasmSdk { // Extract result from response and convert to our expected format let claim_result = match response.inner.version { - Some(dapi_grpc::platform::v0::get_token_perpetual_distribution_last_claim_response::Version::V0(v0)) => { + Some( + dapi_grpc::platform::v0::get_token_perpetual_distribution_last_claim_response::Version::V0( + v0, + ), + ) => { match v0.result { - Some(dapi_grpc::platform::v0::get_token_perpetual_distribution_last_claim_response::get_token_perpetual_distribution_last_claim_response_v0::Result::LastClaim(claim)) => { - // Convert gRPC response to RewardDistributionMoment equivalent + Some( + dapi_grpc::platform::v0::get_token_perpetual_distribution_last_claim_response::get_token_perpetual_distribution_last_claim_response_v0::Result::LastClaim( + claim, + ), + ) => { match claim.paid_at { - Some(dapi_grpc::platform::v0::get_token_perpetual_distribution_last_claim_response::get_token_perpetual_distribution_last_claim_response_v0::last_claim_info::PaidAt::TimestampMs(timestamp)) => { - Some((timestamp, 0)) // (timestamp_ms, block_height) - }, - Some(dapi_grpc::platform::v0::get_token_perpetual_distribution_last_claim_response::get_token_perpetual_distribution_last_claim_response_v0::last_claim_info::PaidAt::BlockHeight(height)) => { - Some((0, height)) // (timestamp_ms, block_height) - }, - Some(dapi_grpc::platform::v0::get_token_perpetual_distribution_last_claim_response::get_token_perpetual_distribution_last_claim_response_v0::last_claim_info::PaidAt::Epoch(epoch)) => { - Some((0, epoch as u64)) // (timestamp_ms, block_height) - }, - Some(dapi_grpc::platform::v0::get_token_perpetual_distribution_last_claim_response::get_token_perpetual_distribution_last_claim_response_v0::last_claim_info::PaidAt::RawBytes(bytes)) => { + Some( + dapi_grpc::platform::v0::get_token_perpetual_distribution_last_claim_response::get_token_perpetual_distribution_last_claim_response_v0::last_claim_info::PaidAt::TimestampMs( + timestamp, + ), + ) => Some((timestamp, 0)), + Some( + dapi_grpc::platform::v0::get_token_perpetual_distribution_last_claim_response::get_token_perpetual_distribution_last_claim_response_v0::last_claim_info::PaidAt::BlockHeight( + height, + ), + ) => Some((0, height)), + Some( + dapi_grpc::platform::v0::get_token_perpetual_distribution_last_claim_response::get_token_perpetual_distribution_last_claim_response_v0::last_claim_info::PaidAt::Epoch( + epoch, + ), + ) => Some((0, epoch as u64)), + Some( + dapi_grpc::platform::v0::get_token_perpetual_distribution_last_claim_response::get_token_perpetual_distribution_last_claim_response_v0::last_claim_info::PaidAt::RawBytes( + bytes, + ), + ) => { // Raw bytes format specification (confirmed via server trace logs): // - Total length: 8 bytes (big-endian encoding) // - Bytes 0-3: Timestamp as u32 (seconds since Unix epoch, 0 = no timestamp recorded) @@ -505,12 +541,27 @@ impl WasmSdk { // - Timestamp: 0 (unset) or >= 1609459200 (Jan 1, 2021 00:00:00 UTC, before Dash Platform mainnet) // - Block height: 0 (invalid) or >= 1 (valid blockchain height) if bytes.len() >= 8 { - let timestamp = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as u64; - let block_height = u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) as u64; + let timestamp = u32::from_be_bytes([ + bytes[0], + bytes[1], + bytes[2], + bytes[3], + ]) as u64; + let block_height = u32::from_be_bytes([ + bytes[4], + bytes[5], + bytes[6], + bytes[7], + ]) as u64; // Validate timestamp: must be 0 (unset) or a reasonable Unix timestamp - let validated_timestamp = if timestamp != 0 && timestamp < 1609459200 { - tracing::warn!(target = "wasm_sdk", timestamp, "Invalid timestamp in raw bytes (too early)"); + let validated_timestamp = if timestamp != 0 + && timestamp < 1609459200 + { + tracing::warn!( + target = "wasm_sdk", timestamp, + "Invalid timestamp in raw bytes (too early)" + ); 0 // Use 0 for invalid timestamps } else { timestamp @@ -518,23 +569,31 @@ impl WasmSdk { // Validate block height: must be a positive value let validated_block_height = if block_height == 0 { - tracing::warn!(target = "wasm_sdk", "Invalid block height in raw bytes: 0 (genesis block not expected)"); + tracing::warn!( + target = "wasm_sdk", + "Invalid block height in raw bytes: 0 (genesis block not expected)" + ); 1 // Use minimum valid block height } else { block_height }; - Some((validated_timestamp * 1000, validated_block_height)) // Convert timestamp to milliseconds + Some((validated_timestamp * 1000, validated_block_height)) } else if bytes.len() >= 4 { // Fallback: decode only the last 4 bytes as block height let block_height = u32::from_be_bytes([ - bytes[bytes.len() - 4], bytes[bytes.len() - 3], - bytes[bytes.len() - 2], bytes[bytes.len() - 1] + bytes[bytes.len() - 4], + bytes[bytes.len() - 3], + bytes[bytes.len() - 2], + bytes[bytes.len() - 1], ]) as u64; // Validate block height let validated_block_height = if block_height == 0 { - tracing::warn!(target = "wasm_sdk", "Invalid block height in fallback parsing: 0"); + tracing::warn!( + target = "wasm_sdk", + "Invalid block height in fallback parsing: 0" + ); 1 // Use minimum valid block height } else { block_height @@ -542,24 +601,31 @@ impl WasmSdk { Some((0, validated_block_height)) } else { - tracing::warn!(target = "wasm_sdk", len = bytes.len(), "Insufficient raw bytes length (expected 8 or 4)"); + tracing::warn!( + target = "wasm_sdk", len = bytes.len(), + "Insufficient raw bytes length (expected 8 or 4)" + ); Some((0, 0)) } - }, - None => { - None // No paid_at info } + None => None, // No paid_at info } - }, - Some(dapi_grpc::platform::v0::get_token_perpetual_distribution_last_claim_response::get_token_perpetual_distribution_last_claim_response_v0::Result::Proof(_)) => { - return Err(WasmSdkError::generic("Received proof instead of data - this should not happen with prove: false")) - }, + } + Some( + dapi_grpc::platform::v0::get_token_perpetual_distribution_last_claim_response::get_token_perpetual_distribution_last_claim_response_v0::Result::Proof( + _, + ), + ) => { + return Err( + WasmSdkError::generic( + "Received proof instead of data - this should not happen with prove: false", + ), + ); + } None => None, // No claim found } - }, - None => { - return Err(WasmSdkError::generic("Invalid response version")) } + None => return Err(WasmSdkError::generic("Invalid response version")), }; Ok(claim_result.map(|(timestamp_ms, block_height)| { @@ -570,6 +636,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getTokenTotalSupply")] pub async fn get_token_total_supply( &self, + #[wasm_bindgen(js_name = "tokenId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] token_id: JsValue, ) -> Result, WasmSdkError> { @@ -590,8 +657,10 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentitiesTokenBalancesWithProofInfo")] pub async fn get_identities_token_balances_with_proof_info( &self, + #[wasm_bindgen(js_name = "identityIds")] #[wasm_bindgen(unchecked_param_type = "Array")] identity_ids: Vec, + #[wasm_bindgen(js_name = "tokenId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] token_id: JsValue, ) -> Result { @@ -635,6 +704,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getTokenStatusesWithProofInfo")] pub async fn get_token_statuses_with_proof_info( &self, + #[wasm_bindgen(js_name = "tokenIds")] #[wasm_bindgen(unchecked_param_type = "Array")] token_ids: Vec, ) -> Result { @@ -665,6 +735,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getTokenTotalSupplyWithProofInfo")] pub async fn get_token_total_supply_with_proof_info( &self, + #[wasm_bindgen(js_name = "tokenId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] token_id: JsValue, ) -> Result { @@ -697,8 +768,10 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentityTokenInfosWithProofInfo")] pub async fn get_identity_token_infos_with_proof_info( &self, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, + #[wasm_bindgen(js_name = "tokenIds")] #[wasm_bindgen(unchecked_param_type = "Array")] token_ids: Vec, ) -> Result { @@ -740,8 +813,10 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getIdentitiesTokenInfosWithProofInfo")] pub async fn get_identities_token_infos_with_proof_info( &self, + #[wasm_bindgen(js_name = "identityIds")] #[wasm_bindgen(unchecked_param_type = "Array")] identity_ids: Vec, + #[wasm_bindgen(js_name = "tokenId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] token_id: JsValue, ) -> Result { @@ -783,6 +858,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getTokenDirectPurchasePricesWithProofInfo")] pub async fn get_token_direct_purchase_prices_with_proof_info( &self, + #[wasm_bindgen(js_name = "tokenIds")] #[wasm_bindgen(unchecked_param_type = "Array")] token_ids: Vec, ) -> Result { @@ -805,10 +881,12 @@ impl WasmSdk { if let Some(Some(schedule)) = prices_result.get(&token) { let token_id_wasm = IdentifierWasm::from(token); let (base_price, current_price) = match schedule { - dash_sdk::dpp::tokens::token_pricing_schedule::TokenPricingSchedule::SinglePrice(price) => { - (price.to_string(), price.to_string()) - } - dash_sdk::dpp::tokens::token_pricing_schedule::TokenPricingSchedule::SetPrices(prices) => { + dash_sdk::dpp::tokens::token_pricing_schedule::TokenPricingSchedule::SinglePrice( + price, + ) => (price.to_string(), price.to_string()), + dash_sdk::dpp::tokens::token_pricing_schedule::TokenPricingSchedule::SetPrices( + prices, + ) => { let base = prices .first_key_value() .map(|(_, p)| p.to_string()) @@ -837,6 +915,7 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getTokenContractInfoWithProofInfo")] pub async fn get_token_contract_info_with_proof_info( &self, + #[wasm_bindgen(js_name = "dataContractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] data_contract_id: JsValue, ) -> Result { @@ -863,8 +942,10 @@ impl WasmSdk { #[wasm_bindgen(js_name = "getTokenPerpetualDistributionLastClaimWithProofInfo")] pub async fn get_token_perpetual_distribution_last_claim_with_proof_info( &self, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, + #[wasm_bindgen(js_name = "tokenId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] token_id: JsValue, ) -> Result { @@ -892,15 +973,15 @@ impl WasmSdk { // Since we need both timestamp and block height in the response, // we'll return the moment value and type let (last_claim_timestamp_ms, last_claim_block_height) = match moment { - dash_sdk::dpp::data_contract::associated_token::token_perpetual_distribution::reward_distribution_moment::RewardDistributionMoment::BlockBasedMoment(height) => { - (0, height) // No timestamp available for block-based - }, - dash_sdk::dpp::data_contract::associated_token::token_perpetual_distribution::reward_distribution_moment::RewardDistributionMoment::TimeBasedMoment(timestamp) => { - (timestamp, 0) // No block height available for time-based - }, - dash_sdk::dpp::data_contract::associated_token::token_perpetual_distribution::reward_distribution_moment::RewardDistributionMoment::EpochBasedMoment(epoch) => { - (0, epoch as u64) // Convert epoch to u64, no timestamp available - }, + dash_sdk::dpp::data_contract::associated_token::token_perpetual_distribution::reward_distribution_moment::RewardDistributionMoment::BlockBasedMoment( + height, + ) => (0, height), // No timestamp available for block-based + dash_sdk::dpp::data_contract::associated_token::token_perpetual_distribution::reward_distribution_moment::RewardDistributionMoment::TimeBasedMoment( + timestamp, + ) => (timestamp, 0), // No block height available for time-based + dash_sdk::dpp::data_contract::associated_token::token_perpetual_distribution::reward_distribution_moment::RewardDistributionMoment::EpochBasedMoment( + epoch, + ) => (0, epoch as u64), // Convert epoch to u64, no timestamp available }; Some(TokenLastClaimWasm::new( diff --git a/packages/wasm-sdk/src/queries/voting/resources.rs b/packages/wasm-sdk/src/queries/voting/resources.rs index bec481fa83a..85bef7a2dfa 100644 --- a/packages/wasm-sdk/src/queries/voting/resources.rs +++ b/packages/wasm-sdk/src/queries/voting/resources.rs @@ -24,7 +24,7 @@ export interface VotePollsByDocumentTypeQuery { /** * Data contract identifier. */ - dataContractId: Identifier | Uint8Array | string; + dataContractId: IdentifierLike /** * Document type to query. diff --git a/packages/wasm-sdk/src/queries/voting/state.rs b/packages/wasm-sdk/src/queries/voting/state.rs index 299886bc20e..9f26d517645 100644 --- a/packages/wasm-sdk/src/queries/voting/state.rs +++ b/packages/wasm-sdk/src/queries/voting/state.rs @@ -31,7 +31,7 @@ export interface ContestedResourceVoteStateQuery { /** * Data contract identifier. */ - dataContractId: Identifier | Uint8Array | string; + dataContractId: IdentifierLike /** * Contested document type name. @@ -65,7 +65,7 @@ export interface ContestedResourceVoteStateQuery { * Contender identifier to resume from (exclusive by default). * @default undefined */ - startAtContenderId?: Identifier | Uint8Array | string; + startAtContenderId?: IdentifierLike /** * Include the start contender when true. diff --git a/packages/wasm-sdk/src/queries/voting/voters.rs b/packages/wasm-sdk/src/queries/voting/voters.rs index 3ba7912bea7..f250cb9de0d 100644 --- a/packages/wasm-sdk/src/queries/voting/voters.rs +++ b/packages/wasm-sdk/src/queries/voting/voters.rs @@ -25,7 +25,7 @@ export interface ContestedResourceVotersForIdentityQuery { /** * Data contract identifier. */ - dataContractId: Identifier | Uint8Array | string; + dataContractId: IdentifierLike /** * Contested document type name. @@ -46,7 +46,7 @@ export interface ContestedResourceVotersForIdentityQuery { /** * Contested identity identifier. */ - contestantId: Identifier | Uint8Array | string; + contestantId: IdentifierLike /** * Maximum number of voters to return. @@ -58,7 +58,7 @@ export interface ContestedResourceVotersForIdentityQuery { * Voter identifier to resume from (exclusive by default). * @default undefined */ - startAtVoterId?: Identifier | Uint8Array | string; + startAtVoterId?: IdentifierLike /** * Include the `startAtVoterId` when true. diff --git a/packages/wasm-sdk/src/queries/voting/votes.rs b/packages/wasm-sdk/src/queries/voting/votes.rs index 5ab3ba103e0..9abe448064e 100644 --- a/packages/wasm-sdk/src/queries/voting/votes.rs +++ b/packages/wasm-sdk/src/queries/voting/votes.rs @@ -25,7 +25,7 @@ export interface ContestedResourceIdentityVotesQuery { /** * Identity identifier. */ - identityId: Identifier | Uint8Array | string; + identityId: IdentifierLike /** * Maximum number of votes to return. @@ -37,7 +37,7 @@ export interface ContestedResourceIdentityVotesQuery { * Vote identifier to resume from (exclusive by default). * @default undefined */ - startAtVoteId?: Identifier | Uint8Array | string; + startAtVoteId?: IdentifierLike /** * Include the `startAtVoteId` when true. diff --git a/packages/wasm-sdk/src/sdk.rs b/packages/wasm-sdk/src/sdk.rs index 7d452cf8e7b..867c708848a 100644 --- a/packages/wasm-sdk/src/sdk.rs +++ b/packages/wasm-sdk/src/sdk.rs @@ -2,15 +2,12 @@ use crate::context_provider::WasmContext; use crate::error::WasmSdkError; use dash_sdk::dpp::version::PlatformVersion; use dash_sdk::{Sdk, SdkBuilder}; +use once_cell::sync::Lazy; use rs_dapi_client::RequestSettings; use std::ops::{Deref, DerefMut}; +use std::sync::Mutex; use std::time::Duration; use wasm_bindgen::prelude::wasm_bindgen; - -// Store shared trusted contexts -use once_cell::sync::Lazy; -use std::sync::Mutex; - pub(crate) static MAINNET_TRUSTED_CONTEXT: Lazy< Mutex>, > = Lazy::new(|| Mutex::new(None)); @@ -175,7 +172,7 @@ impl WasmSdkBuilder { return Err(WasmSdkError::invalid_argument(format!( "Invalid network '{}'. Expected: mainnet or testnet", network - ))) + ))); } }; @@ -736,7 +733,10 @@ impl WasmSdkBuilder { } #[wasm_bindgen(js_name = "withContextProvider")] - pub fn with_context_provider(self, context_provider: WasmContext) -> Self { + pub fn with_context_provider( + self, + #[wasm_bindgen(js_name = "contextProvider")] context_provider: WasmContext, + ) -> Self { WasmSdkBuilder(self.0.with_context_provider(context_provider)) } @@ -749,7 +749,10 @@ impl WasmSdkBuilder { /// /// Defaults to latest version if not specified. #[wasm_bindgen(js_name = "withVersion")] - pub fn with_version(self, version_number: u32) -> Result { + pub fn with_version( + self, + #[wasm_bindgen(js_name = "versionNumber")] version_number: u32, + ) -> Result { let version = PlatformVersion::get(version_number).map_err(|e| { WasmSdkError::invalid_argument(format!( "Invalid platform version {}: {}", @@ -770,10 +773,10 @@ impl WasmSdkBuilder { #[wasm_bindgen(js_name = "withSettings")] pub fn with_settings( self, - connect_timeout_ms: Option, - timeout_ms: Option, + #[wasm_bindgen(js_name = "connectTimeoutMs")] connect_timeout_ms: Option, + #[wasm_bindgen(js_name = "timeoutMs")] timeout_ms: Option, retries: Option, - ban_failed_address: Option, + #[wasm_bindgen(js_name = "banFailedAddress")] ban_failed_address: Option, ) -> Self { let mut settings = RequestSettings::default(); @@ -797,7 +800,10 @@ impl WasmSdkBuilder { } #[wasm_bindgen(js_name = "withProofs")] - pub fn with_proofs(self, enable_proofs: bool) -> Self { + pub fn with_proofs( + self, + #[wasm_bindgen(js_name = "enableProofs")] enable_proofs: bool, + ) -> Self { WasmSdkBuilder(self.0.with_proofs(enable_proofs)) } } @@ -809,7 +815,9 @@ impl WasmSdk { /// Accepts simple levels: "off", "error", "warn", "info", "debug", "trace" /// or a full EnvFilter string like: "wasm_sdk=debug,rs_dapi_client=warn" #[wasm_bindgen(js_name = "setLogLevel")] - pub fn set_log_level(level_or_filter: &str) -> Result<(), WasmSdkError> { + pub fn set_log_level( + #[wasm_bindgen(js_name = "levelOrFilter")] level_or_filter: &str, + ) -> Result<(), WasmSdkError> { crate::logging::set_log_level(level_or_filter) } } @@ -819,7 +827,10 @@ impl WasmSdkBuilder { /// Configure tracing/logging via the builder /// Returns a new builder with logging configured #[wasm_bindgen(js_name = "withLogs")] - pub fn with_logs(self, level_or_filter: &str) -> Result { + pub fn with_logs( + self, + #[wasm_bindgen(js_name = "levelOrFilter")] level_or_filter: &str, + ) -> Result { crate::logging::set_log_level(level_or_filter)?; Ok(self) } diff --git a/packages/wasm-sdk/src/state_transitions/contracts/mod.rs b/packages/wasm-sdk/src/state_transitions/contracts/mod.rs index 2f9302e62c2..176d8298782 100644 --- a/packages/wasm-sdk/src/state_transitions/contracts/mod.rs +++ b/packages/wasm-sdk/src/state_transitions/contracts/mod.rs @@ -36,11 +36,12 @@ impl WasmSdk { #[wasm_bindgen(js_name = contractCreate)] pub async fn contract_create( &self, + #[wasm_bindgen(js_name = "ownerId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] owner_id: JsValue, - contract_definition: String, - private_key_wif: String, - key_id: Option, + #[wasm_bindgen(js_name = "contractDefinition")] contract_definition: String, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: String, + #[wasm_bindgen(js_name = "keyId")] key_id: Option, ) -> Result { let sdk = self.inner_clone(); @@ -116,19 +117,13 @@ impl WasmSdk { ) })? }; - - // Create the data contract from JSON definition - let data_contract = DataContract::from_json( - contract_json, - true, // validate - sdk.version(), - ) - .map_err(|e| { - WasmSdkError::invalid_argument(format!( - "Failed to create data contract from JSON: {}", - e - )) - })?; + let data_contract = + DataContract::from_json(contract_json, true, sdk.version()).map_err(|e| { + WasmSdkError::invalid_argument(format!( + "Failed to create data contract from JSON: {}", + e + )) + })?; // Create signer let signer = SingleKeySigner::from_string(&private_key_wif, self.network()) @@ -211,13 +206,15 @@ impl WasmSdk { #[wasm_bindgen(js_name = contractUpdate)] pub async fn contract_update( &self, + #[wasm_bindgen(js_name = "contractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] contract_id: JsValue, + #[wasm_bindgen(js_name = "ownerId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] owner_id: JsValue, - contract_updates: String, - private_key_wif: String, - key_id: Option, + #[wasm_bindgen(js_name = "contractUpdates")] contract_updates: String, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: String, + #[wasm_bindgen(js_name = "keyId")] key_id: Option, ) -> Result { let sdk = self.inner_clone(); @@ -310,19 +307,13 @@ impl WasmSdk { // Create updated contract from JSON definition // Note: The updates should be a complete contract definition with incremented version - let updated_contract = DataContract::from_json( - updates_json, - true, // validate - sdk.version(), - ) - .map_err(|e| { - WasmSdkError::invalid_argument(format!( - "Failed to create updated contract from JSON: {}", - e - )) - })?; - - // Verify the version was incremented + let updated_contract = + DataContract::from_json(updates_json, true, sdk.version()).map_err(|e| { + WasmSdkError::invalid_argument(format!( + "Failed to create updated contract from JSON: {}", + e + )) + })?; if updated_contract.version() <= existing_contract.version() { return Err(WasmSdkError::invalid_argument(format!( "Contract version must be incremented. Current: {}, Provided: {}", diff --git a/packages/wasm-sdk/src/state_transitions/documents/mod.rs b/packages/wasm-sdk/src/state_transitions/documents/mod.rs index 83441a79e8a..e502e409fb5 100644 --- a/packages/wasm-sdk/src/state_transitions/documents/mod.rs +++ b/packages/wasm-sdk/src/state_transitions/documents/mod.rs @@ -108,10 +108,8 @@ impl WasmSdk { // Log debug information tracing::debug!( - target = "wasm_sdk", - pubkey = %hex::encode(&public_key_bytes), - hash160 = %hex::encode(&public_key_hash160), - "Looking for authentication key" + target = "wasm_sdk", pubkey = % hex::encode(& public_key_bytes), hash160 = % + hex::encode(& public_key_hash160), "Looking for authentication key" ); // Find matching authentication key @@ -135,9 +133,7 @@ impl WasmSdk { if matches { tracing::debug!( - target = "wasm_sdk", - id = key.id(), - key_type = ?key.key_type(), + target = "wasm_sdk", id = key.id(), key_type = ? key.key_type(), "Found matching key" ); } @@ -226,14 +222,16 @@ impl WasmSdk { #[wasm_bindgen(js_name = documentCreate)] pub async fn document_create( &self, + #[wasm_bindgen(js_name = "dataContractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] data_contract_id: JsValue, - document_type: String, + #[wasm_bindgen(js_name = "documentType")] document_type: String, + #[wasm_bindgen(js_name = "ownerId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] owner_id: JsValue, - document_data: String, + #[wasm_bindgen(js_name = "documentData")] document_data: String, entropy: String, - private_key_wif: String, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: String, ) -> Result { let sdk = self.inner_clone(); @@ -345,10 +343,8 @@ impl WasmSdk { // Try to find the created document for (doc_id, maybe_doc) in documents.iter() { tracing::debug!( - target = "wasm_sdk", - id = %doc_id.to_string(Encoding::Base58), - present = maybe_doc.is_some(), - "Document entry" + target = "wasm_sdk", id = % doc_id.to_string(Encoding::Base58), + present = maybe_doc.is_some(), "Document entry" ); } @@ -564,16 +560,19 @@ impl WasmSdk { #[wasm_bindgen(js_name = documentReplace)] pub async fn document_replace( &self, + #[wasm_bindgen(js_name = "dataContractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] data_contract_id: JsValue, - document_type: String, + #[wasm_bindgen(js_name = "documentType")] document_type: String, + #[wasm_bindgen(js_name = "documentId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] document_id: JsValue, + #[wasm_bindgen(js_name = "ownerId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] owner_id: JsValue, - document_data: String, + #[wasm_bindgen(js_name = "documentData")] document_data: String, revision: u64, - private_key_wif: String, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: String, ) -> Result { let sdk = self.inner_clone(); @@ -880,14 +879,17 @@ impl WasmSdk { #[wasm_bindgen(js_name = documentDelete)] pub async fn document_delete( &self, + #[wasm_bindgen(js_name = "dataContractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] data_contract_id: JsValue, - document_type: String, + #[wasm_bindgen(js_name = "documentType")] document_type: String, + #[wasm_bindgen(js_name = "documentId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] document_id: JsValue, + #[wasm_bindgen(js_name = "ownerId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] owner_id: JsValue, - private_key_wif: String, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: String, ) -> Result { let sdk = self.inner_clone(); @@ -1005,16 +1007,20 @@ impl WasmSdk { #[wasm_bindgen(js_name = documentTransfer)] pub async fn document_transfer( &self, + #[wasm_bindgen(js_name = "dataContractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] data_contract_id: JsValue, - document_type: String, + #[wasm_bindgen(js_name = "documentType")] document_type: String, + #[wasm_bindgen(js_name = "documentId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] document_id: JsValue, + #[wasm_bindgen(js_name = "ownerId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] owner_id: JsValue, + #[wasm_bindgen(js_name = "recipientId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] recipient_id: JsValue, - private_key_wif: String, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: String, ) -> Result { let sdk = self.inner_clone(); @@ -1135,15 +1141,18 @@ impl WasmSdk { #[wasm_bindgen(js_name = documentPurchase)] pub async fn document_purchase( &self, + #[wasm_bindgen(js_name = "dataContractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] data_contract_id: JsValue, - document_type: String, + #[wasm_bindgen(js_name = "documentType")] document_type: String, + #[wasm_bindgen(js_name = "documentId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] document_id: JsValue, + #[wasm_bindgen(js_name = "buyerId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] buyer_id: JsValue, price: u64, - private_key_wif: String, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: String, ) -> Result { let sdk = self.inner_clone(); @@ -1164,14 +1173,15 @@ impl WasmSdk { // Fetch the document to purchase let query = dash_sdk::platform::documents::document_query::DocumentQuery::new_with_data_contract_id( - &sdk, - contract_id, - &document_type, - ) - .await - .map_err(|e| WasmSdkError::generic(format!("Failed to create document query: {}", e)))? - .with_document_id(&doc_id); - + &sdk, + contract_id, + &document_type, + ) + .await + .map_err(|e| WasmSdkError::generic( + format!("Failed to create document query: {}", e), + ))? + .with_document_id(&doc_id); let document = dash_sdk::platform::Document::fetch(&sdk, query) .await? .ok_or_else(|| WasmSdkError::not_found("Document not found"))?; @@ -1278,17 +1288,14 @@ impl WasmSdk { additional_fields, ) } - _ => { - // Purchase was processed but document not returned - Self::build_js_result_object( - "DocumentPurchased", - &document_id_base58, - vec![ - ("status", JsValue::from_str("success")), - ("message", JsValue::from_str("Document purchase processed")), - ], - ) - } + _ => Self::build_js_result_object( + "DocumentPurchased", + &document_id_base58, + vec![ + ("status", JsValue::from_str("success")), + ("message", JsValue::from_str("Document purchase processed")), + ], + ), // Purchase was processed but document not returned } } @@ -1309,15 +1316,18 @@ impl WasmSdk { #[wasm_bindgen(js_name = documentSetPrice)] pub async fn document_set_price( &self, + #[wasm_bindgen(js_name = "dataContractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] data_contract_id: JsValue, - document_type: String, + #[wasm_bindgen(js_name = "documentType")] document_type: String, + #[wasm_bindgen(js_name = "documentId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] document_id: JsValue, + #[wasm_bindgen(js_name = "ownerId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] owner_id: JsValue, price: u64, - private_key_wif: String, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: String, ) -> Result { let sdk = self.inner_clone(); @@ -1337,14 +1347,15 @@ impl WasmSdk { // Fetch the existing document to update its price let query = dash_sdk::platform::documents::document_query::DocumentQuery::new_with_data_contract_id( - &sdk, - contract_id, - &document_type, - ) - .await - .map_err(|e| WasmSdkError::generic(format!("Failed to create document query: {}", e)))? - .with_document_id(&doc_id); - + &sdk, + contract_id, + &document_type, + ) + .await + .map_err(|e| WasmSdkError::generic( + format!("Failed to create document query: {}", e), + ))? + .with_document_id(&doc_id); let existing_doc = Document::fetch(&sdk, query) .await? .ok_or_else(|| WasmSdkError::not_found("Document not found"))?; diff --git a/packages/wasm-sdk/src/state_transitions/identity/mod.rs b/packages/wasm-sdk/src/state_transitions/identity/mod.rs index a71f1c266c4..4a3172b200b 100644 --- a/packages/wasm-sdk/src/state_transitions/identity/mod.rs +++ b/packages/wasm-sdk/src/state_transitions/identity/mod.rs @@ -46,21 +46,26 @@ impl WasmSdk { #[wasm_bindgen(js_name = identityCreate)] pub async fn identity_create( &self, - asset_lock_proof: String, - asset_lock_proof_private_key: String, - public_keys: String, + #[wasm_bindgen(js_name = "assetLockProof")] asset_lock_proof: String, + #[wasm_bindgen(js_name = "assetLockProofPrivateKey")] asset_lock_proof_private_key: String, + #[wasm_bindgen(js_name = "publicKeys")] public_keys: String, ) -> Result { let sdk = self.inner_clone(); // Debug log parameters (truncated/sanitized) debug!( - target: "wasm_sdk", - len = asset_lock_proof.len(), - preview = %if asset_lock_proof.len() > 100 { format!("{}...", &asset_lock_proof[..100]) } else { asset_lock_proof.clone() }, - "identityCreate called" + target : "wasm_sdk", len = asset_lock_proof.len(), preview = % if + asset_lock_proof.len() > 100 { format!("{}...", & asset_lock_proof[..100]) } + else { asset_lock_proof.clone() }, "identityCreate called" + ); + debug!( + target : "wasm_sdk", pk_len = asset_lock_proof_private_key.len(), + "identityCreate private key length" + ); + debug!( + target : "wasm_sdk", public_keys = % public_keys, + "identityCreate public keys JSON" ); - debug!(target: "wasm_sdk", pk_len = asset_lock_proof_private_key.len(), "identityCreate private key length"); - debug!(target: "wasm_sdk", public_keys = %public_keys, "identityCreate public keys JSON"); // Parse asset lock proof - try hex first, then JSON let asset_lock_proof: AssetLockProof = if asset_lock_proof @@ -91,8 +96,10 @@ impl WasmSdk { }; // Parse private key - WIF format - debug!(target: "wasm_sdk", pk_len = asset_lock_proof_private_key.len(), "Private key format validation"); - + debug!( + target : "wasm_sdk", pk_len = asset_lock_proof_private_key.len(), + "Private key format validation" + ); let private_key = PrivateKey::from_wif(&asset_lock_proof_private_key) .map_err(|e| WasmSdkError::invalid_argument(format!("Invalid private key: {}", e)))?; @@ -133,7 +140,7 @@ impl WasmSdk { return Err(WasmSdkError::invalid_argument(format!( "Unknown key type: {}", key_type_str - ))) + ))); } }; @@ -149,7 +156,7 @@ impl WasmSdk { return Err(WasmSdkError::invalid_argument(format!( "Unknown purpose: {}", purpose_str - ))) + ))); } }; @@ -219,9 +226,11 @@ impl WasmSdk { (key_data_bytes, [0u8; 32]) } else { - return Err(WasmSdkError::invalid_argument( - "ECDSA_HASH160 requires either 'privateKeyHex' to derive from or 'data' (base64-encoded 20-byte hash)", - )); + return Err( + WasmSdkError::invalid_argument( + "ECDSA_HASH160 requires either 'privateKeyHex' to derive from or 'data' (base64-encoded 20-byte hash)", + ), + ); } } KeyType::ECDSA_SECP256K1 => { @@ -376,8 +385,9 @@ impl WasmSdk { Err(e) => { // Extract more detailed error information let error_msg = format!("Failed to create identity: {}", e); - - error!(target: "wasm_sdk", msg = %error_msg, "Identity creation failed"); + error!( + target : "wasm_sdk", msg = % error_msg, "Identity creation failed" + ); return Err(WasmSdkError::generic(error_msg)); } }; @@ -439,10 +449,11 @@ impl WasmSdk { #[wasm_bindgen(js_name = identityTopUp)] pub async fn identity_top_up( &self, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, - asset_lock_proof: String, - asset_lock_proof_private_key: String, + #[wasm_bindgen(js_name = "assetLockProof")] asset_lock_proof: String, + #[wasm_bindgen(js_name = "assetLockProofPrivateKey")] asset_lock_proof_private_key: String, ) -> Result { let sdk = self.inner_clone(); @@ -477,10 +488,10 @@ impl WasmSdk { WasmSdkError::invalid_argument(format!("Invalid asset lock proof JSON: {}", e)) })? }; - - // Parse private key - WIF format - debug!(target: "wasm_sdk", pk_len = asset_lock_proof_private_key.len(), "Private key format validation"); - + debug!( + target : "wasm_sdk", pk_len = asset_lock_proof_private_key.len(), + "Private key format validation" + ); let private_key = PrivateKey::from_wif(&asset_lock_proof_private_key) .map_err(|e| WasmSdkError::invalid_argument(format!("Invalid private key: {}", e)))?; @@ -489,12 +500,12 @@ impl WasmSdk { Ok(Some(identity)) => identity, Ok(None) => { let error_msg = format!("Identity not found: {}", identifier); - error!(target: "wasm_sdk", %error_msg); + error!(target : "wasm_sdk", % error_msg); return Err(WasmSdkError::not_found(error_msg)); } Err(e) => { let error_msg = format!("Failed to fetch identity: {}", e); - error!(target: "wasm_sdk", %error_msg); + error!(target : "wasm_sdk", % error_msg); return Err(WasmSdkError::from(e)); } }; @@ -510,7 +521,7 @@ impl WasmSdk { Ok(balance) => balance, Err(e) => { let error_msg = format!("Failed to top up identity: {}", e); - error!(target: "wasm_sdk", %error_msg); + error!(target : "wasm_sdk", % error_msg); return Err(WasmSdkError::from(e)); } }; @@ -570,13 +581,15 @@ impl WasmSdk { #[wasm_bindgen(js_name = identityCreditTransfer)] pub async fn identity_credit_transfer( &self, + #[wasm_bindgen(js_name = "senderId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] sender_id: JsValue, + #[wasm_bindgen(js_name = "recipientId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] recipient_id: JsValue, amount: u64, - private_key_wif: String, - key_id: Option, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: String, + #[wasm_bindgen(js_name = "keyId")] key_id: Option, ) -> Result { let sdk = self.inner_clone(); @@ -685,7 +698,7 @@ impl WasmSdk { Some(matching_key), identity_nonce, sdk.version(), - None, // No version override + None, ) .map_err(|e| { WasmSdkError::generic(format!("Failed to create transfer transition: {}", e)) @@ -752,13 +765,14 @@ impl WasmSdk { #[wasm_bindgen(js_name = identityCreditWithdrawal)] pub async fn identity_credit_withdrawal( &self, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, - to_address: String, + #[wasm_bindgen(js_name = "toAddress")] to_address: String, amount: u64, - core_fee_per_byte: Option, - private_key_wif: String, - key_id: Option, + #[wasm_bindgen(js_name = "coreFeePerByte")] core_fee_per_byte: Option, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: String, + #[wasm_bindgen(js_name = "keyId")] key_id: Option, ) -> Result { let sdk = self.inner_clone(); @@ -867,7 +881,7 @@ impl WasmSdk { core_fee_per_byte, Some(matching_key), signer, - None, // No special settings + None, ) .await .map_err(|e| WasmSdkError::generic(format!("Withdrawal failed: {}", e)))?; @@ -930,11 +944,12 @@ impl WasmSdk { #[wasm_bindgen(js_name = identityUpdate)] pub async fn identity_update( &self, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, - add_public_keys: Option, - disable_public_keys: Option>, - private_key_wif: String, + #[wasm_bindgen(js_name = "addPublicKeys")] add_public_keys: Option, + #[wasm_bindgen(js_name = "disablePublicKeys")] disable_public_keys: Option>, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: String, ) -> Result { let sdk = self.inner_clone(); @@ -1144,7 +1159,7 @@ impl WasmSdk { UserFeeIncrease::default(), &signer, sdk.version(), - None, // No version override + None, ) .map_err(|e| WasmSdkError::generic(format!("Failed to create update transition: {}", e)))?; @@ -1228,15 +1243,17 @@ impl WasmSdk { #[wasm_bindgen(js_name = masternodeVote)] pub async fn masternode_vote( &self, + #[wasm_bindgen(js_name = "masternodeProTxHash")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] masternode_pro_tx_hash: JsValue, + #[wasm_bindgen(js_name = "contractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] contract_id: JsValue, - document_type_name: String, - index_name: String, - index_values: String, - vote_choice: String, - voting_key_wif: String, + #[wasm_bindgen(js_name = "documentTypeName")] document_type_name: String, + #[wasm_bindgen(js_name = "indexName")] index_name: String, + #[wasm_bindgen(js_name = "indexValues")] index_values: String, + #[wasm_bindgen(js_name = "voteChoice")] vote_choice: String, + #[wasm_bindgen(js_name = "votingKeyWif")] voting_key_wif: String, ) -> Result { let sdk = self.inner_clone(); @@ -1301,7 +1318,11 @@ impl WasmSdk { })?; ResourceVoteChoice::TowardsIdentity(identity_id) } else { - return Err(WasmSdkError::invalid_argument("Invalid vote choice. Must be 'abstain', 'lock', or 'towardsIdentity:'")); + return Err( + WasmSdkError::invalid_argument( + "Invalid vote choice. Must be 'abstain', 'lock', or 'towardsIdentity:'", + ), + ); }; // Parse private key (try WIF first, then hex) @@ -1352,10 +1373,10 @@ impl WasmSdk { // Create the voting identity public key use dash_sdk::dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; let voting_public_key = IdentityPublicKey::V0(IdentityPublicKeyV0 { - id: 0, // The ID doesn't matter for voting keys + id: 0, key_type: KeyType::ECDSA_HASH160, purpose: Purpose::VOTING, - security_level: SecurityLevel::HIGH, // Voting keys should be HIGH, not MASTER + security_level: SecurityLevel::HIGH, contract_bounds: None, read_only: false, data: BinaryData::new(voting_key_hash), diff --git a/packages/wasm-sdk/src/state_transitions/tokens/mod.rs b/packages/wasm-sdk/src/state_transitions/tokens/mod.rs index 463e105223f..55778fe300f 100644 --- a/packages/wasm-sdk/src/state_transitions/tokens/mod.rs +++ b/packages/wasm-sdk/src/state_transitions/tokens/mod.rs @@ -157,16 +157,19 @@ impl WasmSdk { #[wasm_bindgen(js_name = tokenMint)] pub async fn token_mint( &self, + #[wasm_bindgen(js_name = "dataContractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] data_contract_id: JsValue, - token_position: u16, + #[wasm_bindgen(js_name = "tokenPosition")] token_position: u16, amount: String, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, - private_key_wif: String, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: String, + #[wasm_bindgen(js_name = "recipientId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string | undefined")] recipient_id: JsValue, - public_note: Option, + #[wasm_bindgen(js_name = "publicNote")] public_note: Option, ) -> Result { let sdk = self.inner_clone(); @@ -249,14 +252,16 @@ impl WasmSdk { #[wasm_bindgen(js_name = tokenBurn)] pub async fn token_burn( &self, + #[wasm_bindgen(js_name = "dataContractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] data_contract_id: JsValue, - token_position: u16, + #[wasm_bindgen(js_name = "tokenPosition")] token_position: u16, amount: String, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, - private_key_wif: String, - public_note: Option, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: String, + #[wasm_bindgen(js_name = "publicNote")] public_note: Option, ) -> Result { let sdk = self.inner_clone(); @@ -334,16 +339,19 @@ impl WasmSdk { #[wasm_bindgen(js_name = tokenTransfer)] pub async fn token_transfer( &self, + #[wasm_bindgen(js_name = "dataContractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] data_contract_id: JsValue, - token_position: u16, + #[wasm_bindgen(js_name = "tokenPosition")] token_position: u16, amount: String, + #[wasm_bindgen(js_name = "senderId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] sender_id: JsValue, + #[wasm_bindgen(js_name = "recipientId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] recipient_id: JsValue, - private_key_wif: String, - public_note: Option, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: String, + #[wasm_bindgen(js_name = "publicNote")] public_note: Option, ) -> Result { let sdk = self.inner_clone(); @@ -426,15 +434,18 @@ impl WasmSdk { #[wasm_bindgen(js_name = tokenFreeze)] pub async fn token_freeze( &self, + #[wasm_bindgen(js_name = "dataContractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] data_contract_id: JsValue, - token_position: u16, + #[wasm_bindgen(js_name = "tokenPosition")] token_position: u16, + #[wasm_bindgen(js_name = "identityToFreezeId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_to_freeze_id: JsValue, + #[wasm_bindgen(js_name = "freezerId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] freezer_id: JsValue, - private_key_wif: String, - public_note: Option, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: String, + #[wasm_bindgen(js_name = "publicNote")] public_note: Option, ) -> Result { let sdk = self.inner_clone(); @@ -518,15 +529,18 @@ impl WasmSdk { #[wasm_bindgen(js_name = tokenUnfreeze)] pub async fn token_unfreeze( &self, + #[wasm_bindgen(js_name = "dataContractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] data_contract_id: JsValue, - token_position: u16, + #[wasm_bindgen(js_name = "tokenPosition")] token_position: u16, + #[wasm_bindgen(js_name = "identityToUnfreezeId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_to_unfreeze_id: JsValue, + #[wasm_bindgen(js_name = "unfreezerId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] unfreezer_id: JsValue, - private_key_wif: String, - public_note: Option, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: String, + #[wasm_bindgen(js_name = "publicNote")] public_note: Option, ) -> Result { let sdk = self.inner_clone(); @@ -613,15 +627,18 @@ impl WasmSdk { #[wasm_bindgen(js_name = tokenDestroyFrozen)] pub async fn token_destroy_frozen( &self, + #[wasm_bindgen(js_name = "dataContractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] data_contract_id: JsValue, - token_position: u16, + #[wasm_bindgen(js_name = "tokenPosition")] token_position: u16, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, + #[wasm_bindgen(js_name = "destroyerId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] destroyer_id: JsValue, - private_key_wif: String, - public_note: Option, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: String, + #[wasm_bindgen(js_name = "publicNote")] public_note: Option, ) -> Result { let sdk = self.inner_clone(); @@ -711,15 +728,17 @@ impl WasmSdk { #[wasm_bindgen(js_name = tokenSetPriceForDirectPurchase)] pub async fn token_set_price_for_direct_purchase( &self, + #[wasm_bindgen(js_name = "dataContractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] data_contract_id: JsValue, - token_position: u16, + #[wasm_bindgen(js_name = "tokenPosition")] token_position: u16, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, - price_type: String, - price_data: String, - private_key_wif: String, - public_note: Option, + #[wasm_bindgen(js_name = "priceType")] price_type: String, + #[wasm_bindgen(js_name = "priceData")] price_data: String, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: String, + #[wasm_bindgen(js_name = "publicNote")] public_note: Option, ) -> Result { use dash_sdk::dpp::fee::Credits; use dash_sdk::dpp::tokens::token_pricing_schedule::TokenPricingSchedule; @@ -786,7 +805,7 @@ impl WasmSdk { _ => { return Err(WasmSdkError::invalid_argument( "Invalid price type. Use 'single' or 'tiered'", - )) + )); } } }; @@ -910,14 +929,16 @@ impl WasmSdk { #[wasm_bindgen(js_name = tokenDirectPurchase)] pub async fn token_direct_purchase( &self, + #[wasm_bindgen(js_name = "dataContractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] data_contract_id: JsValue, - token_position: u16, + #[wasm_bindgen(js_name = "tokenPosition")] token_position: u16, amount: String, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, - total_agreed_price: Option, - private_key_wif: String, + #[wasm_bindgen(js_name = "totalAgreedPrice")] total_agreed_price: Option, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: String, ) -> Result { use dash_sdk::dpp::fee::Credits; @@ -1053,14 +1074,16 @@ impl WasmSdk { #[wasm_bindgen(js_name = tokenClaim)] pub async fn token_claim( &self, + #[wasm_bindgen(js_name = "dataContractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] data_contract_id: JsValue, - token_position: u16, - distribution_type: String, + #[wasm_bindgen(js_name = "tokenPosition")] token_position: u16, + #[wasm_bindgen(js_name = "distributionType")] distribution_type: String, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, - private_key_wif: String, - public_note: Option, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: String, + #[wasm_bindgen(js_name = "publicNote")] public_note: Option, ) -> Result { use dash_sdk::dpp::data_contract::associated_token::token_distribution_key::TokenDistributionType; @@ -1088,7 +1111,7 @@ impl WasmSdk { _ => { return Err(WasmSdkError::invalid_argument( "Invalid distribution type. Use 'perpetual' or 'preprogrammed'", - )) + )); } }; @@ -1158,15 +1181,17 @@ impl WasmSdk { #[wasm_bindgen(js_name = tokenConfigUpdate)] pub async fn token_config_update( &self, + #[wasm_bindgen(js_name = "dataContractId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] data_contract_id: JsValue, - token_position: u16, - config_item_type: String, - config_value: String, + #[wasm_bindgen(js_name = "tokenPosition")] token_position: u16, + #[wasm_bindgen(js_name = "configItemType")] config_item_type: String, + #[wasm_bindgen(js_name = "configValue")] config_value: String, + #[wasm_bindgen(js_name = "identityId")] #[wasm_bindgen(unchecked_param_type = "Identifier | Uint8Array | string")] identity_id: JsValue, - private_key_wif: String, - public_note: Option, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: String, + #[wasm_bindgen(js_name = "publicNote")] public_note: Option, ) -> Result { use dash_sdk::dpp::data_contract::associated_token::token_configuration_convention::TokenConfigurationConvention; use dash_sdk::dpp::data_contract::associated_token::token_configuration_item::TokenConfigurationChangeItem; @@ -1322,7 +1347,7 @@ impl WasmSdk { return Err(WasmSdkError::invalid_argument(format!( "Invalid config item type: {}", config_item_type - ))) + ))); } }; diff --git a/packages/wasm-sdk/src/wallet/extended_derivation.rs b/packages/wasm-sdk/src/wallet/extended_derivation.rs index dc42d6ed22d..8d1ac323fc7 100644 --- a/packages/wasm-sdk/src/wallet/extended_derivation.rs +++ b/packages/wasm-sdk/src/wallet/extended_derivation.rs @@ -3,6 +3,7 @@ //! Implements 256-bit derivation paths for DashPay contact keys use crate::error::WasmSdkError; +use crate::queries::utils::deserialize_required_query; use crate::sdk::WasmSdk; use dash_sdk::dpp::dashcore; use dash_sdk::dpp::dashcore::secp256k1::Secp256k1; @@ -10,221 +11,301 @@ use dash_sdk::dpp::key_wallet::{bip32, DerivationPath, ExtendedPrivKey}; use std::str::FromStr; use tracing::debug; use wasm_bindgen::prelude::*; +use wasm_dpp2::identifier::IdentifierWasm; + +// TypeScript option bags (module scope) for extended derivation helpers +#[wasm_bindgen(typescript_custom_section)] +const DERIVE_FROM_EXTENDED_PATH_OPTS_TS: &'static str = r#" +export interface DeriveKeyFromSeedWithExtendedPathParams { + mnemonic: string; + passphrase?: string; + path: string; + network: string; +} +"#; +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(typescript_type = "DeriveKeyFromSeedWithExtendedPathParams")] + pub type DeriveKeyFromSeedWithExtendedPathParamsJs; +} +// Inputs parsed from options (module scope) +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase")] +struct DeriveFromExtendedPathInput { + mnemonic: String, + #[serde(default)] + passphrase: Option, + path: String, + network: String, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase")] +struct DeriveDashpayContactKeyInput { + mnemonic: String, + #[serde(default)] + passphrase: Option, + #[serde(rename = "senderIdentityId")] + sender_identity_id: IdentifierWasm, + #[serde(rename = "receiverIdentityId")] + receiver_identity_id: IdentifierWasm, + account: u32, + #[serde(rename = "addressIndex")] + address_index: u32, + network: String, +} + +#[wasm_bindgen(typescript_custom_section)] +const DERIVE_DASHPAY_CONTACT_KEY_OPTS_TS: &'static str = r#" +export interface DeriveDashpayContactKeyParams { + mnemonic: string; + passphrase?: string; + senderIdentityId: IdentifierLike; + receiverIdentityId: IdentifierLike; + account: number; + addressIndex: number; + network: string; +} +"#; +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(typescript_type = "DeriveDashpayContactKeyParams")] + pub type DeriveDashpayContactKeyParamsJs; +} + +// Common internal result to avoid duplicating derivation logic/output wiring +struct CommonDerivation { + path: String, + private_key_wif: String, + private_key_hex: String, + public_key_hex: String, + address: String, + network: String, + xprv: String, + xpub: String, +} + +fn derive_common_from_mnemonic( + mnemonic: &str, + passphrase: Option, + network: &str, + path: &str, +) -> Result { + // Get seed from mnemonic + let seed = WasmSdk::mnemonic_to_seed(mnemonic, passphrase)?; + + let net = match network { + "mainnet" => dashcore::Network::Dash, + "testnet" => dashcore::Network::Testnet, + _ => return Err(WasmSdkError::invalid_argument("Invalid network")), + }; + + // Create master extended private key from seed + let master_key = ExtendedPrivKey::new_master(net, &seed) + .map_err(|e| WasmSdkError::generic(format!("Failed to create master key: {}", e)))?; + + // Parse path and derive + let derivation_path = DerivationPath::from_str(path) + .map_err(|e| WasmSdkError::invalid_argument(format!("Invalid derivation path: {}", e)))?; + + let secp = Secp256k1::new(); + let derived_key = master_key + .derive_priv(&secp, &derivation_path) + .map_err(|e| WasmSdkError::generic(format!("Failed to derive key: {}", e)))?; + + let xpub = bip32::ExtendedPubKey::from_priv(&secp, &derived_key); + let private_key = dashcore::PrivateKey::new(derived_key.private_key, net); + let public_key = private_key.public_key(&secp); + let address = dashcore::Address::p2pkh(&public_key, net); + + Ok(CommonDerivation { + path: path.to_string(), + private_key_wif: private_key.to_wif(), + private_key_hex: hex::encode(private_key.inner.secret_bytes()), + public_key_hex: hex::encode(public_key.to_bytes()), + address: address.to_string(), + network: network.to_string(), + xprv: derived_key.to_string(), + xpub: xpub.to_string(), + }) +} + +#[wasm_bindgen(js_name = "DerivedKeyInfo")] +#[derive(Clone)] +pub struct DerivedKeyInfoWasm { + #[wasm_bindgen(getter_with_clone)] + pub path: String, + #[wasm_bindgen(getter_with_clone, js_name = "privateKeyWif")] + pub private_key_wif: String, + #[wasm_bindgen(getter_with_clone, js_name = "privateKeyHex")] + pub private_key_hex: String, + #[wasm_bindgen(getter_with_clone, js_name = "publicKey")] + pub public_key: String, + #[wasm_bindgen(getter_with_clone)] + pub address: String, + #[wasm_bindgen(getter_with_clone)] + pub network: String, + #[wasm_bindgen(getter_with_clone)] + pub xprv: String, + #[wasm_bindgen(getter_with_clone)] + pub xpub: String, +} + +impl From for DerivedKeyInfoWasm { + fn from(c: CommonDerivation) -> Self { + Self { + path: c.path, + private_key_wif: c.private_key_wif, + private_key_hex: c.private_key_hex, + public_key: c.public_key_hex, + address: c.address, + network: c.network, + xprv: c.xprv, + xpub: c.xpub, + } + } +} + +// Field getters are generated via getter_with_clone annotations above + +#[wasm_bindgen(js_name = "DashpayContactKeyInfo")] +#[derive(Clone)] +pub struct DashpayContactKeyInfoWasm { + // common + #[wasm_bindgen(getter_with_clone)] + pub path: String, + #[wasm_bindgen(getter_with_clone, js_name = "privateKeyWif")] + pub private_key_wif: String, + #[wasm_bindgen(getter_with_clone, js_name = "privateKeyHex")] + pub private_key_hex: String, + #[wasm_bindgen(getter_with_clone, js_name = "publicKey")] + pub public_key: String, + #[wasm_bindgen(getter_with_clone)] + pub address: String, + #[wasm_bindgen(getter_with_clone)] + pub network: String, + #[wasm_bindgen(getter_with_clone)] + pub xprv: String, + #[wasm_bindgen(getter_with_clone)] + pub xpub: String, + // extras + #[wasm_bindgen(getter_with_clone, js_name = "dipStandard")] + pub dip_standard: String, + #[wasm_bindgen(getter_with_clone)] + pub purpose: String, + #[wasm_bindgen(getter_with_clone, js_name = "senderIdentity")] + pub sender_identity: String, + #[wasm_bindgen(getter_with_clone, js_name = "receiverIdentity")] + pub receiver_identity: String, + #[wasm_bindgen(getter_with_clone)] + pub account: u32, + #[wasm_bindgen(getter_with_clone, js_name = "addressIndex")] + pub address_index: u32, +} + +impl DashpayContactKeyInfoWasm { + fn from_common( + c: CommonDerivation, + sender_identity: String, + receiver_identity: String, + account: u32, + address_index: u32, + ) -> Self { + Self { + path: c.path, + private_key_wif: c.private_key_wif, + private_key_hex: c.private_key_hex, + public_key: c.public_key_hex, + address: c.address, + network: c.network, + xprv: c.xprv, + xpub: c.xpub, + dip_standard: "DIP15".to_string(), + purpose: "DashPay Contact Payment".to_string(), + sender_identity, + receiver_identity, + account, + address_index, + } + } +} + +// Field getters are generated via getter_with_clone annotations above #[wasm_bindgen] impl WasmSdk { /// Derive a key from seed phrase with extended path supporting 256-bit indices /// This supports DIP14/DIP15 paths with identity IDs #[wasm_bindgen(js_name = "deriveKeyFromSeedWithExtendedPath")] pub fn derive_key_from_seed_with_extended_path( - mnemonic: &str, - passphrase: Option, - path: &str, - network: &str, - ) -> Result { + params: DeriveKeyFromSeedWithExtendedPathParamsJs, + ) -> Result { + let DeriveFromExtendedPathInput { + mnemonic, + passphrase, + path, + network, + } = deserialize_required_query( + params, + "Options object is required", + "deriveKeyFromSeedWithExtendedPath options", + )?; // Debug: Log the path being processed debug!(target: "wasm_sdk", path, "Processing extended path"); - - // Get seed from mnemonic - let seed = Self::mnemonic_to_seed(mnemonic, passphrase)?; - - let net = match network { - "mainnet" => dashcore::Network::Dash, - "testnet" => dashcore::Network::Testnet, - _ => return Err(WasmSdkError::invalid_argument("Invalid network")), - }; - - // Create master extended private key from seed - let master_key = ExtendedPrivKey::new_master(net, &seed) - .map_err(|e| WasmSdkError::generic(format!("Failed to create master key: {}", e)))?; - - // Parse the derivation path using dashcore's built-in parser - // This already supports 256-bit hex values like 0x775d3854... - let derivation_path = DerivationPath::from_str(path).map_err(|e| { - WasmSdkError::invalid_argument(format!("Invalid derivation path: {}", e)) - })?; - - // Use dashcore's built-in derive_priv method which handles DIP14 - let secp = Secp256k1::new(); - let derived_key = master_key - .derive_priv(&secp, &derivation_path) - .map_err(|e| WasmSdkError::generic(format!("Failed to derive key: {}", e)))?; - - // Get the extended public key - let xpub = bip32::ExtendedPubKey::from_priv(&secp, &derived_key); - - // Get the private key - let private_key = dashcore::PrivateKey::new(derived_key.private_key, net); - - // Get public key - let public_key = private_key.public_key(&secp); - - // Get address - let address = dashcore::Address::p2pkh(&public_key, net); - - // Create result object - let obj = js_sys::Object::new(); - - js_sys::Reflect::set(&obj, &JsValue::from_str("path"), &JsValue::from_str(path)) - .map_err(|_| WasmSdkError::generic("Failed to set path property"))?; - - js_sys::Reflect::set( - &obj, - &JsValue::from_str("private_key_wif"), - &JsValue::from_str(&private_key.to_wif()), - ) - .map_err(|_| WasmSdkError::generic("Failed to set private_key_wif property"))?; - - js_sys::Reflect::set( - &obj, - &JsValue::from_str("private_key_hex"), - &JsValue::from_str(&hex::encode(private_key.inner.secret_bytes())), - ) - .map_err(|_| WasmSdkError::generic("Failed to set private_key_hex property"))?; - - js_sys::Reflect::set( - &obj, - &JsValue::from_str("public_key"), - &JsValue::from_str(&hex::encode(public_key.to_bytes())), - ) - .map_err(|_| WasmSdkError::generic("Failed to set public_key property"))?; - - js_sys::Reflect::set( - &obj, - &JsValue::from_str("address"), - &JsValue::from_str(&address.to_string()), - ) - .map_err(|_| WasmSdkError::generic("Failed to set address property"))?; - - js_sys::Reflect::set( - &obj, - &JsValue::from_str("network"), - &JsValue::from_str(network), - ) - .map_err(|_| WasmSdkError::generic("Failed to set network property"))?; - - js_sys::Reflect::set( - &obj, - &JsValue::from_str("xprv"), - &JsValue::from_str(&derived_key.to_string()), - ) - .map_err(|_| WasmSdkError::generic("Failed to set xprv property"))?; - - js_sys::Reflect::set( - &obj, - &JsValue::from_str("xpub"), - &JsValue::from_str(&xpub.to_string()), - ) - .map_err(|_| WasmSdkError::generic("Failed to set xpub property"))?; - - Ok(obj.into()) + let common = derive_common_from_mnemonic(&mnemonic, passphrase, &network, &path)?; + Ok(DerivedKeyInfoWasm::from(common)) } /// Derive a DashPay contact key using DIP15 with full identity IDs #[wasm_bindgen(js_name = "deriveDashpayContactKey")] pub fn derive_dashpay_contact_key( - mnemonic: &str, - passphrase: Option, - sender_identity_id: &str, - receiver_identity_id: &str, - account: u32, - address_index: u32, - network: &str, - ) -> Result { - use bs58; - - // Convert base58 identity IDs to hex format if needed - let sender_id_formatted = if sender_identity_id.starts_with("0x") { - sender_identity_id.to_string() - } else { - // Decode base58 to bytes, then convert to hex - let bytes = bs58::decode(sender_identity_id).into_vec().map_err(|e| { - WasmSdkError::invalid_argument(format!("Invalid sender identity ID: {}", e)) - })?; - format!("0x{}", hex::encode(bytes)) + params: DeriveDashpayContactKeyParamsJs, + ) -> Result { + let DeriveDashpayContactKeyInput { + mnemonic, + passphrase, + sender_identity_id, + receiver_identity_id, + account, + address_index, + network, + } = deserialize_required_query( + params, + "Options object is required", + "deriveDashpayContactKey options", + )?; + let sender_id_hex = { + let id: dash_sdk::dpp::prelude::Identifier = sender_identity_id.into(); + hex::encode(id.as_bytes()) }; - - let receiver_id_formatted = if receiver_identity_id.starts_with("0x") { - receiver_identity_id.to_string() - } else { - // Decode base58 to bytes, then convert to hex - let bytes = bs58::decode(receiver_identity_id).into_vec().map_err(|e| { - WasmSdkError::invalid_argument(format!("Invalid receiver identity ID: {}", e)) - })?; - format!("0x{}", hex::encode(bytes)) + let receiver_id_hex = { + let id: dash_sdk::dpp::prelude::Identifier = receiver_identity_id.into(); + hex::encode(id.as_bytes()) }; // Build the DIP15 path // m / 9' / coin_type' / 15' / account' / sender_id / receiver_id / index - let coin_type = match network { + let coin_type = match network.as_str() { "mainnet" => 5, "testnet" => 1, _ => return Err(WasmSdkError::invalid_argument("Invalid network")), }; - + // Build the DIP15 path + // m / 9' / coin_type' / 15' / account' / sender_id / receiver_id / index let path = format!( - "m/9'/{}'/{}'/{}'/{}/{}/{}", - coin_type, - 15, // DIP15 feature - account, - sender_id_formatted, - receiver_id_formatted, - address_index + "m/9'/{}'/{}'/{}'/0x{}/0x{}/{}", + coin_type, 15, account, sender_id_hex, receiver_id_hex, address_index ); - - debug!(target: "wasm_sdk", path = %path, "DashPay contact path"); - - // Use the extended derivation function - let result = - Self::derive_key_from_seed_with_extended_path(mnemonic, passphrase, &path, network)?; - - // Add DIP15-specific metadata - let obj = result - .dyn_into::() - .map_err(|_| WasmSdkError::generic("Failed to cast result to object"))?; - - js_sys::Reflect::set( - &obj, - &JsValue::from_str("dipStandard"), - &JsValue::from_str("DIP15"), - ) - .map_err(|_| WasmSdkError::generic("Failed to set dipStandard property"))?; - - js_sys::Reflect::set( - &obj, - &JsValue::from_str("purpose"), - &JsValue::from_str("DashPay Contact Payment"), - ) - .map_err(|_| WasmSdkError::generic("Failed to set purpose property"))?; - - js_sys::Reflect::set( - &obj, - &JsValue::from_str("senderIdentity"), - &JsValue::from_str(sender_identity_id), - ) - .map_err(|_| WasmSdkError::generic("Failed to set senderIdentity property"))?; - - js_sys::Reflect::set( - &obj, - &JsValue::from_str("receiverIdentity"), - &JsValue::from_str(receiver_identity_id), - ) - .map_err(|_| WasmSdkError::generic("Failed to set receiverIdentity property"))?; - - js_sys::Reflect::set( - &obj, - &JsValue::from_str("account"), - &JsValue::from_f64(account as f64), - ) - .map_err(|_| WasmSdkError::generic("Failed to set account property"))?; - - js_sys::Reflect::set( - &obj, - &JsValue::from_str("addressIndex"), - &JsValue::from_f64(address_index as f64), - ) - .map_err(|_| WasmSdkError::generic("Failed to set addressIndex property"))?; - - Ok(obj.into()) + debug!(target : "wasm_sdk", path = % path, "DashPay contact path"); + + // Reuse common derivation logic + let common = derive_common_from_mnemonic(&mnemonic, passphrase, &network, &path)?; + Ok(DashpayContactKeyInfoWasm::from_common( + common, + sender_id_hex, + receiver_id_hex, + account, + address_index, + )) } } diff --git a/packages/wasm-sdk/src/wallet/key_derivation.rs b/packages/wasm-sdk/src/wallet/key_derivation.rs index c1c03086bd1..0e9f0a5f9c0 100644 --- a/packages/wasm-sdk/src/wallet/key_derivation.rs +++ b/packages/wasm-sdk/src/wallet/key_derivation.rs @@ -3,6 +3,7 @@ //! Implements BIP32, BIP39, and BIP44 standards for hierarchical deterministic key derivation use crate::error::WasmSdkError; +use crate::queries::utils::{deserialize_query_with_default, deserialize_required_query}; use crate::sdk::WasmSdk; use bip39::{Language, Mnemonic}; use dash_sdk::dpp::dashcore; @@ -16,6 +17,77 @@ use serde::{Deserialize, Serialize}; use std::str::FromStr; use wasm_bindgen::prelude::*; +// TypeScript option bags (module scope) for wallet derivation helpers +#[wasm_bindgen(typescript_custom_section)] +const GENERATE_MNEMONIC_PARAMS_TS: &'static str = r#" +export interface GenerateMnemonicParams { + wordCount?: number; + languageCode?: string; +} +"#; +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(typescript_type = "GenerateMnemonicParams")] + pub type GenerateMnemonicParamsJs; +} + +#[wasm_bindgen(typescript_custom_section)] +const DERIVE_FROM_SEED_PHRASE_OPTS_TS: &'static str = r#" +export interface DeriveKeyFromSeedPhraseParams { + mnemonic: string; + passphrase?: string; + network: string; +} +"#; +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(typescript_type = "DeriveKeyFromSeedPhraseParams")] + pub type DeriveKeyFromSeedPhraseParamsJs; +} + +#[wasm_bindgen(typescript_custom_section)] +const DERIVE_FROM_SEED_WITH_PATH_OPTS_TS: &'static str = r#" +export interface DeriveKeyFromSeedWithPathParams { + mnemonic: string; + passphrase?: string; + path: string; + network: string; +} +"#; +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(typescript_type = "DeriveKeyFromSeedWithPathParams")] + pub type DeriveKeyFromSeedWithPathParamsJs; +} + +// Inputs parsed from options (module scope) +#[derive(Default, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +struct GenerateMnemonicInput { + #[serde(default)] + word_count: Option, + #[serde(default)] + language_code: Option, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase")] +struct DeriveFromSeedPhraseInput { + mnemonic: String, + #[serde(default)] + passphrase: Option, + network: String, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase")] +struct DeriveFromSeedWithPathInput { + mnemonic: String, + #[serde(default)] + passphrase: Option, + path: String, + network: String, +} /// Dash coin type for BIP44 (mainnet) pub const DASH_COIN_TYPE: u32 = 5; /// Testnet coin type for BIP44 @@ -147,9 +219,13 @@ impl WasmSdk { /// Generate a new mnemonic phrase #[wasm_bindgen(js_name = "generateMnemonic")] pub fn generate_mnemonic( - word_count: Option, - language_code: Option, + params: Option, ) -> Result { + let GenerateMnemonicInput { + word_count, + language_code, + } = deserialize_query_with_default(params, "generateMnemonic options")?; + let words = word_count.unwrap_or(12); // Validate word count and calculate entropy bytes @@ -199,7 +275,10 @@ impl WasmSdk { /// Validate a mnemonic phrase #[wasm_bindgen(js_name = "validateMnemonic")] - pub fn validate_mnemonic(mnemonic: &str, language_code: Option) -> bool { + pub fn validate_mnemonic( + mnemonic: &str, + #[wasm_bindgen(js_name = "languageCode")] language_code: Option, + ) -> bool { // If language is specified, validate in that language if let Some(code) = language_code { let language = match code.as_str() { @@ -242,14 +321,21 @@ impl WasmSdk { /// Derive a key from mnemonic phrase using BIP39/BIP44 #[wasm_bindgen(js_name = "deriveKeyFromSeedPhrase")] pub fn derive_key_from_seed_phrase( - mnemonic: &str, - passphrase: Option, - network: &str, + params: DeriveKeyFromSeedPhraseParamsJs, ) -> Result { + let DeriveFromSeedPhraseInput { + mnemonic, + passphrase, + network, + } = deserialize_required_query( + params, + "Options object is required", + "deriveKeyFromSeedPhrase options", + )?; use crate::wallet::key_generation::KeyPair; // Get seed from mnemonic - let seed = Self::mnemonic_to_seed(mnemonic, passphrase)?; + let seed = Self::mnemonic_to_seed(&mnemonic, passphrase)?; // For now, we'll use the first 32 bytes of the seed as the private key // Note: This is a simplified approach. Proper BIP32/BIP44 would use HD derivation @@ -261,7 +347,7 @@ impl WasmSdk { return Err(WasmSdkError::generic("Seed too short")); }; - let net = match network { + let net = match network.as_str() { "mainnet" => dashcore::Network::Dash, "testnet" => dashcore::Network::Testnet, _ => return Err(WasmSdkError::invalid_argument("Invalid network")), @@ -288,7 +374,7 @@ impl WasmSdk { private_key_hex: hex::encode(key_bytes), public_key: hex::encode(public_key_bytes), address: address.to_string(), - network: network.to_string(), + network, }; serde_wasm_bindgen::to_value(&key_pair).map_err(|e| { @@ -299,24 +385,33 @@ impl WasmSdk { /// Derive a key from seed phrase with arbitrary path #[wasm_bindgen(js_name = "deriveKeyFromSeedWithPath")] pub fn derive_key_from_seed_with_path( - mnemonic: &str, - passphrase: Option, - path: &str, - network: &str, + params: DeriveKeyFromSeedWithPathParamsJs, ) -> Result { use dash_sdk::dpp::key_wallet::{DerivationPath, ExtendedPrivKey}; + // Types decoded in parse step are defined at module scope + let DeriveFromSeedWithPathInput { + mnemonic, + passphrase, + path, + network, + } = deserialize_required_query( + params, + "Options object is required", + "deriveKeyFromSeedWithPath options", + )?; + // Get seed from mnemonic - let seed = Self::mnemonic_to_seed(mnemonic, passphrase)?; + let seed = Self::mnemonic_to_seed(&mnemonic, passphrase)?; - let net = match network { + let net = match network.as_str() { "mainnet" => dashcore::Network::Dash, "testnet" => dashcore::Network::Testnet, _ => return Err(WasmSdkError::invalid_argument("Invalid network")), }; // Parse derivation path - let derivation_path = DerivationPath::from_str(path).map_err(|e| { + let derivation_path = DerivationPath::from_str(&path).map_err(|e| { WasmSdkError::invalid_argument(format!("Invalid derivation path: {}", e)) })?; @@ -343,7 +438,7 @@ impl WasmSdk { // Create a JavaScript object directly let obj = js_sys::Object::new(); - js_sys::Reflect::set(&obj, &JsValue::from_str("path"), &JsValue::from_str(path)) + js_sys::Reflect::set(&obj, &JsValue::from_str("path"), &JsValue::from_str(&path)) .map_err(|_| WasmSdkError::generic("Failed to set path property"))?; js_sys::Reflect::set( @@ -377,7 +472,7 @@ impl WasmSdk { js_sys::Reflect::set( &obj, &JsValue::from_str("network"), - &JsValue::from_str(network), + &JsValue::from_str(&network), ) .map_err(|_| WasmSdkError::generic("Failed to set network property"))?; @@ -400,14 +495,22 @@ impl WasmSdk { /// Create a DIP9 mainnet derivation path #[wasm_bindgen(js_name = "derivationPathDip9Mainnet")] - pub fn derivation_path_dip9_mainnet(feature_type: u32, account: u32, index: u32) -> JsValue { + pub fn derivation_path_dip9_mainnet( + #[wasm_bindgen(js_name = "featureType")] feature_type: u32, + account: u32, + index: u32, + ) -> JsValue { let path = DerivationPath::new_dip9_mainnet(feature_type, account, index); serde_wasm_bindgen::to_value(&path).unwrap_or(JsValue::NULL) } /// Create a DIP9 testnet derivation path #[wasm_bindgen(js_name = "derivationPathDip9Testnet")] - pub fn derivation_path_dip9_testnet(feature_type: u32, account: u32, index: u32) -> JsValue { + pub fn derivation_path_dip9_testnet( + #[wasm_bindgen(js_name = "featureType")] feature_type: u32, + account: u32, + index: u32, + ) -> JsValue { let path = DerivationPath::new_dip9_testnet(feature_type, account, index); serde_wasm_bindgen::to_value(&path).unwrap_or(JsValue::NULL) } diff --git a/packages/wasm-sdk/src/wallet/key_generation.rs b/packages/wasm-sdk/src/wallet/key_generation.rs index 676a4ac98a5..248565dfdaf 100644 --- a/packages/wasm-sdk/src/wallet/key_generation.rs +++ b/packages/wasm-sdk/src/wallet/key_generation.rs @@ -37,7 +37,7 @@ impl WasmSdk { _ => { return Err(WasmSdkError::invalid_argument( "Invalid network. Use 'mainnet' or 'testnet'", - )) + )); } }; @@ -98,7 +98,9 @@ impl WasmSdk { /// Create key pair from private key WIF #[wasm_bindgen(js_name = "keyPairFromWif")] - pub fn key_pair_from_wif(private_key_wif: &str) -> Result { + pub fn key_pair_from_wif( + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: &str, + ) -> Result { let private_key = PrivateKey::from_wif(private_key_wif) .map_err(|e| WasmSdkError::invalid_argument(format!("Invalid WIF: {}", e)))?; @@ -140,7 +142,7 @@ impl WasmSdk { /// Create key pair from private key hex #[wasm_bindgen(js_name = "keyPairFromHex")] pub fn key_pair_from_hex( - private_key_hex: &str, + #[wasm_bindgen(js_name = "privateKeyHex")] private_key_hex: &str, network: &str, ) -> Result { if private_key_hex.len() != 64 { @@ -155,7 +157,7 @@ impl WasmSdk { _ => { return Err(WasmSdkError::invalid_argument( "Invalid network. Use 'mainnet' or 'testnet'", - )) + )); } }; @@ -173,14 +175,17 @@ impl WasmSdk { /// Get address from public key #[wasm_bindgen(js_name = "pubkeyToAddress")] - pub fn pubkey_to_address(pubkey_hex: &str, network: &str) -> Result { + pub fn pubkey_to_address( + #[wasm_bindgen(js_name = "pubkeyHex")] pubkey_hex: &str, + network: &str, + ) -> Result { let net = match network { "mainnet" => Network::Dash, "testnet" => Network::Testnet, _ => { return Err(WasmSdkError::invalid_argument( "Invalid network. Use 'mainnet' or 'testnet'", - )) + )); } }; @@ -210,7 +215,10 @@ impl WasmSdk { /// Sign a message with a private key #[wasm_bindgen(js_name = "signMessage")] - pub fn sign_message(message: &str, private_key_wif: &str) -> Result { + pub fn sign_message( + message: &str, + #[wasm_bindgen(js_name = "privateKeyWif")] private_key_wif: &str, + ) -> Result { let private_key = PrivateKey::from_wif(private_key_wif) .map_err(|e| WasmSdkError::invalid_argument(format!("Invalid WIF: {}", e)))?; diff --git a/packages/wasm-sdk/tests/functional/dpns.spec.mjs b/packages/wasm-sdk/tests/functional/dpns.spec.mjs index e1c881a7e47..48a228600da 100644 --- a/packages/wasm-sdk/tests/functional/dpns.spec.mjs +++ b/packages/wasm-sdk/tests/functional/dpns.spec.mjs @@ -77,7 +77,7 @@ describe('Document queries', function describeDocumentQueries() { it('fetches usernames for a known identity and verifies fields', async () => { const TEST_IDENTITY = '5DbLwAxGBzUzo81VewMUwn4b5P4bpv9FNFybi25XB5Bk'; - const list = await client.getDpnsUsernames(TEST_IDENTITY, 10); + const list = await client.getDpnsUsernames({ identityId: TEST_IDENTITY, limit: 10 }); expect(list).to.be.an('array'); }); }); diff --git a/packages/wasm-sdk/tests/functional/identities.spec.mjs b/packages/wasm-sdk/tests/functional/identities.spec.mjs index dffd8eb2b47..6f9acf0f2a6 100644 --- a/packages/wasm-sdk/tests/functional/identities.spec.mjs +++ b/packages/wasm-sdk/tests/functional/identities.spec.mjs @@ -52,7 +52,10 @@ describe('Identity queries', function describeBlock() { }); it('contract keys for identity', async () => { - const r = await client.getIdentitiesContractKeys([TEST_IDENTITY], DPNS_CONTRACT); + const r = await client.getIdentitiesContractKeys({ + identityIds: [TEST_IDENTITY], + contractId: DPNS_CONTRACT, + }); expect(r).to.be.an('array'); }); diff --git a/packages/wasm-sdk/tests/unit/address-validation.spec.mjs b/packages/wasm-sdk/tests/unit/address-validation.spec.mjs index 566b662ed35..93ff6f3bc7a 100644 --- a/packages/wasm-sdk/tests/unit/address-validation.spec.mjs +++ b/packages/wasm-sdk/tests/unit/address-validation.spec.mjs @@ -14,8 +14,12 @@ describe('Address validation', () => { it('validates generated addresses for each network', () => { const mnemonic = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'; - const kM = sdk.WasmSdk.deriveKeyFromSeedWithPath(mnemonic, undefined, "m/44'/5'/0'/0/0", 'mainnet'); - const kT = sdk.WasmSdk.deriveKeyFromSeedWithPath(mnemonic, undefined, "m/44'/1'/0'/0/0", 'testnet'); + const kM = sdk.WasmSdk.deriveKeyFromSeedWithPath({ + mnemonic, passphrase: null, path: "m/44'/5'/0'/0/0", network: 'mainnet', + }); + const kT = sdk.WasmSdk.deriveKeyFromSeedWithPath({ + mnemonic, passphrase: null, path: "m/44'/1'/0'/0/0", network: 'testnet', + }); expect(sdk.WasmSdk.validateAddress(kM.address, 'mainnet')).to.equal(true); expect(sdk.WasmSdk.validateAddress(kT.address, 'testnet')).to.equal(true); }); diff --git a/packages/wasm-sdk/tests/unit/derivation.spec.mjs b/packages/wasm-sdk/tests/unit/derivation.spec.mjs index 4185f842c04..698ccf87254 100644 --- a/packages/wasm-sdk/tests/unit/derivation.spec.mjs +++ b/packages/wasm-sdk/tests/unit/derivation.spec.mjs @@ -52,7 +52,9 @@ describe('Key derivation', () => { it('BIP44 mainnet key', () => { const path = "m/44'/5'/0'/0/0"; - const r = sdk.WasmSdk.deriveKeyFromSeedWithPath(seed, undefined, path, 'mainnet'); + const r = sdk.WasmSdk.deriveKeyFromSeedWithPath({ + mnemonic: seed, passphrase: null, path, network: 'mainnet', + }); expect(r).to.exist(); expect(r.path).to.equal(path); expect(r.address.startsWith('X')).to.equal(true); @@ -61,7 +63,9 @@ describe('Key derivation', () => { it('DIP13 authentication key', () => { const path = "m/9'/5'/5'/0'/0'/0'/0'"; - const r = sdk.WasmSdk.deriveKeyFromSeedWithPath(seed, undefined, path, 'mainnet'); + const r = sdk.WasmSdk.deriveKeyFromSeedWithPath({ + mnemonic: seed, passphrase: null, path, network: 'mainnet', + }); expect(r).to.exist(); expect(r.path).to.equal(path); expect(r.private_key_wif).to.be.a('string'); @@ -70,21 +74,31 @@ describe('Key derivation', () => { it('with passphrase produces different address', () => { const path = "m/44'/5'/0'/0/0"; - const withPass = sdk.WasmSdk.deriveKeyFromSeedWithPath(seed, 'test passphrase', path, 'mainnet'); - const withoutPass = sdk.WasmSdk.deriveKeyFromSeedWithPath(seed, undefined, path, 'mainnet'); + const withPass = sdk.WasmSdk.deriveKeyFromSeedWithPath({ + mnemonic: seed, passphrase: 'test passphrase', path, network: 'mainnet', + }); + const withoutPass = sdk.WasmSdk.deriveKeyFromSeedWithPath({ + mnemonic: seed, passphrase: null, path, network: 'mainnet', + }); expect(withPass.address).to.not.equal(withoutPass.address); }); it('testnet address prefix', () => { const path = "m/44'/1'/0'/0/0"; - const r = sdk.WasmSdk.deriveKeyFromSeedWithPath(seed, undefined, path, 'testnet'); + const r = sdk.WasmSdk.deriveKeyFromSeedWithPath({ + mnemonic: seed, passphrase: null, path, network: 'testnet', + }); expect(r.network).to.equal('testnet'); expect(r.address.startsWith('y')).to.equal(true); }); it('DIP9 hardened vs non-hardened differ', () => { - const hardened = sdk.WasmSdk.deriveKeyFromSeedWithPath(seed, null, "m/9'/5'/5'/0/0", 'mainnet'); - const nonHardened = sdk.WasmSdk.deriveKeyFromSeedWithPath(seed, null, 'm/9/5/5/0/0', 'mainnet'); + const hardened = sdk.WasmSdk.deriveKeyFromSeedWithPath({ + mnemonic: seed, passphrase: null, path: "m/9'/5'/5'/0/0", network: 'mainnet', + }); + const nonHardened = sdk.WasmSdk.deriveKeyFromSeedWithPath({ + mnemonic: seed, passphrase: null, path: 'm/9/5/5/0/0', network: 'mainnet', + }); expect(hardened.address).to.not.equal(nonHardened.address); }); }); @@ -94,14 +108,18 @@ describe('Key derivation', () => { it('Vector 1: mixed hardened/non-hardened', () => { const path = "m/0x775d3854c910b7dee436869c4724bed2fe0784e198b8a39f02bbb49d8ebcfc3b/0xf537439f36d04a15474ff7423e4b904a14373fafb37a41db74c84f1dbb5c89a6'/0x4c4592ca670c983fc43397dfd21a6f427fac9b4ac53cb4dcdc6522ec51e81e79/0"; - const r = sdk.WasmSdk.deriveKeyFromSeedWithExtendedPath(mnemonic, null, path, 'testnet'); + const r = sdk.WasmSdk.deriveKeyFromSeedWithExtendedPath({ + mnemonic, passphrase: null, path, network: 'testnet', + }); expect(r.xprv).to.be.a('string'); expect(r.xpub).to.be.a('string'); }); it('Vector 2: multiple hardened with final non-hardened', () => { const path = "m/9'/5'/15'/0'/0x555d3854c910b7dee436869c4724bed2fe0784e198b8a39f02bbb49d8ebcfc3a'/0xa137439f36d04a15474ff7423e4b904a14373fafb37a41db74c84f1dbb5c89b5'/0"; - const r = sdk.WasmSdk.deriveKeyFromSeedWithExtendedPath(mnemonic, null, path, 'testnet'); + const r = sdk.WasmSdk.deriveKeyFromSeedWithExtendedPath({ + mnemonic, passphrase: null, path, network: 'testnet', + }); expect(r.xprv).to.be.a('string'); expect(r.xpub).to.be.a('string'); }); @@ -109,21 +127,26 @@ describe('Key derivation', () => { describe('DIP15 DashPay contact keys', () => { const mnemonic = 'birth kingdom trash renew flavor utility donkey gasp regular alert pave layer'; - const sender = '0x555d3854c910b7dee436869c4724bed2fe0784e198b8a39f02bbb49d8ebcfc3a'; - const receiver = '0xa137439f36d04a15474ff7423e4b904a14373fafb37a41db74c84f1dbb5c89b5'; + // Hex without 0x prefix (we don't use 0x) + const sender = '555d3854c910b7dee436869c4724bed2fe0784e198b8a39f02bbb49d8ebcfc3a'; + const receiver = 'a137439f36d04a15474ff7423e4b904a14373fafb37a41db74c84f1dbb5c89b5'; it('deterministic contact key for testnet', () => { - const r1 = sdk.WasmSdk.deriveDashpayContactKey(mnemonic, null, sender, receiver, 0, 0, 'testnet'); - const r2 = sdk.WasmSdk.deriveDashpayContactKey(mnemonic, null, sender, receiver, 0, 0, 'testnet'); + const r1 = sdk.WasmSdk.deriveDashpayContactKey({ + mnemonic, passphrase: null, senderIdentityId: sender, receiverIdentityId: receiver, account: 0, addressIndex: 0, network: 'testnet', + }); + const r2 = sdk.WasmSdk.deriveDashpayContactKey({ + mnemonic, passphrase: null, senderIdentityId: sender, receiverIdentityId: receiver, account: 0, addressIndex: 0, network: 'testnet', + }); expect(r1).to.be.ok(); expect(r1).to.have.property('path'); expect(r1).to.have.property('xprv'); expect(r1).to.have.property('xpub'); - expect(r1).to.have.property('private_key_hex'); - expect(r1.private_key_hex).to.have.length(64); + expect(r1).to.have.property('privateKeyHex'); + expect(r1.privateKeyHex).to.have.length(64); - expect(r2.private_key_hex).to.equal(r1.private_key_hex); + expect(r2.privateKeyHex).to.equal(r1.privateKeyHex); expect(r2.xprv).to.equal(r1.xprv); expect(r2.xpub).to.equal(r1.xpub); @@ -136,17 +159,25 @@ describe('Key derivation', () => { }); it('changes when sender/receiver are swapped', () => { - const a = sdk.WasmSdk.deriveDashpayContactKey(mnemonic, null, sender, receiver, 0, 0, 'testnet'); - const b = sdk.WasmSdk.deriveDashpayContactKey(mnemonic, null, receiver, sender, 0, 0, 'testnet'); - expect(a.private_key_hex).to.not.equal(b.private_key_hex); + const a = sdk.WasmSdk.deriveDashpayContactKey({ + mnemonic, passphrase: null, senderIdentityId: sender, receiverIdentityId: receiver, account: 0, addressIndex: 0, network: 'testnet', + }); + const b = sdk.WasmSdk.deriveDashpayContactKey({ + mnemonic, passphrase: null, senderIdentityId: receiver, receiverIdentityId: sender, account: 0, addressIndex: 0, network: 'testnet', + }); + expect(a.privateKeyHex).to.not.equal(b.privateKeyHex); }); it('differs between networks (testnet vs mainnet)', () => { - const t = sdk.WasmSdk.deriveDashpayContactKey(mnemonic, null, sender, receiver, 0, 0, 'testnet'); - const m = sdk.WasmSdk.deriveDashpayContactKey(mnemonic, null, sender, receiver, 0, 0, 'mainnet'); + const t = sdk.WasmSdk.deriveDashpayContactKey({ + mnemonic, passphrase: null, senderIdentityId: sender, receiverIdentityId: receiver, account: 0, addressIndex: 0, network: 'testnet', + }); + const m = sdk.WasmSdk.deriveDashpayContactKey({ + mnemonic, passphrase: null, senderIdentityId: sender, receiverIdentityId: receiver, account: 0, addressIndex: 0, network: 'mainnet', + }); expect(m.xprv.startsWith('xprv')).to.equal(true); expect(m.xpub.startsWith('xpub')).to.equal(true); - expect(m.private_key_hex).to.not.equal(t.private_key_hex); + expect(m.privateKeyHex).to.not.equal(t.privateKeyHex); }); }); }); diff --git a/packages/wasm-sdk/tests/unit/errors.spec.mjs b/packages/wasm-sdk/tests/unit/errors.spec.mjs index a4bd96b8e0a..c35e5f3983e 100644 --- a/packages/wasm-sdk/tests/unit/errors.spec.mjs +++ b/packages/wasm-sdk/tests/unit/errors.spec.mjs @@ -36,7 +36,9 @@ describe('WasmSdkError shape (unit)', () => { const seed = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'; const path = "m/44'/5'/0'/0/0"; try { - sdk.WasmSdk.deriveKeyFromSeedWithPath(seed, undefined, path, 'bogus'); + sdk.WasmSdk.deriveKeyFromSeedWithPath({ + mnemonic: seed, passphrase: null, path, network: 'bogus', + }); expect.fail('expected to throw'); } catch (e) { expect(e).to.be.instanceOf(sdk.WasmSdkError); diff --git a/packages/wasm-sdk/tests/unit/extended-keys.spec.mjs b/packages/wasm-sdk/tests/unit/extended-keys.spec.mjs index 857a94b52cf..326f154e5f7 100644 --- a/packages/wasm-sdk/tests/unit/extended-keys.spec.mjs +++ b/packages/wasm-sdk/tests/unit/extended-keys.spec.mjs @@ -9,12 +9,12 @@ describe('Extended keys', () => { describe('deriveChildPublicKey - basic functionality', () => { it('derives non-hardened child xpubs that differ by index', () => { - const master = sdk.WasmSdk.deriveKeyFromSeedWithExtendedPath( - TEST_MNEMONIC, - null, - "m/44'/5'/0'", - 'mainnet', - ); + const master = sdk.WasmSdk.deriveKeyFromSeedWithExtendedPath({ + mnemonic: TEST_MNEMONIC, + passphrase: null, + path: "m/44'/5'/0'", + network: 'mainnet', + }); const parentXpub = master.xpub; const child0 = sdk.WasmSdk.deriveChildPublicKey(parentXpub, 0, false); @@ -29,12 +29,12 @@ describe('Extended keys', () => { describe('xprvToXpub - basic functionality', () => { it('converts xprv to the expected xpub', () => { - const master = sdk.WasmSdk.deriveKeyFromSeedWithExtendedPath( - TEST_MNEMONIC, - null, - "m/44'/5'/0'", - 'mainnet', - ); + const master = sdk.WasmSdk.deriveKeyFromSeedWithExtendedPath({ + mnemonic: TEST_MNEMONIC, + passphrase: null, + path: "m/44'/5'/0'", + network: 'mainnet', + }); const derivedXpub = sdk.WasmSdk.xprvToXpub(master.xprv); expect(derivedXpub).to.be.a('string'); @@ -44,24 +44,24 @@ describe('Extended keys', () => { describe('deriveChildPublicKey - error handling', () => { it('throws when hardened=true', () => { - const master = sdk.WasmSdk.deriveKeyFromSeedWithExtendedPath( - TEST_MNEMONIC, - null, - "m/44'/5'/0'", - 'mainnet', - ); + const master = sdk.WasmSdk.deriveKeyFromSeedWithExtendedPath({ + mnemonic: TEST_MNEMONIC, + passphrase: null, + path: "m/44'/5'/0'", + network: 'mainnet', + }); const parentXpub = master.xpub; expect(() => sdk.WasmSdk.deriveChildPublicKey(parentXpub, 0, true)) .to.throw('Cannot derive hardened child from extended public key'); }); it('throws when index is in hardened range', () => { - const master = sdk.WasmSdk.deriveKeyFromSeedWithExtendedPath( - TEST_MNEMONIC, - null, - "m/44'/5'/0'", - 'mainnet', - ); + const master = sdk.WasmSdk.deriveKeyFromSeedWithExtendedPath({ + mnemonic: TEST_MNEMONIC, + passphrase: null, + path: "m/44'/5'/0'", + network: 'mainnet', + }); const parentXpub = master.xpub; // 0x80000000 == 2^31 expect(() => sdk.WasmSdk.deriveChildPublicKey(parentXpub, 0x80000000, false)) diff --git a/packages/wasm-sdk/tests/unit/key-generation.spec.mjs b/packages/wasm-sdk/tests/unit/key-generation.spec.mjs index 1f22806215d..47a6378b12f 100644 --- a/packages/wasm-sdk/tests/unit/key-generation.spec.mjs +++ b/packages/wasm-sdk/tests/unit/key-generation.spec.mjs @@ -9,11 +9,11 @@ describe('Keys and mnemonics', () => { describe('mnemonic', () => { it('generates 12 and 24 words and validates', () => { - const m12 = sdk.WasmSdk.generateMnemonic(12); + const m12 = sdk.WasmSdk.generateMnemonic({ wordCount: 12 }); expect(m12.split(' ').length).to.equal(12); expect(sdk.WasmSdk.validateMnemonic(m12)).to.equal(true); - const m24 = sdk.WasmSdk.generateMnemonic(24); + const m24 = sdk.WasmSdk.generateMnemonic({ wordCount: 24 }); expect(m24.split(' ').length).to.equal(24); expect(sdk.WasmSdk.validateMnemonic(m24)).to.equal(true); }); @@ -21,7 +21,7 @@ describe('Keys and mnemonics', () => { it('supports language wordlists', () => { const langs = ['en', 'es', 'fr', 'it', 'ja', 'ko', 'pt', 'cs']; for (const lang of langs) { - const m = sdk.WasmSdk.generateMnemonic(12, lang); + const m = sdk.WasmSdk.generateMnemonic({ wordCount: 12, languageCode: lang }); expect(sdk.WasmSdk.validateMnemonic(m, lang)).to.equal(true); } });