Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/js-evo-sdk/src/tokens/facade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,12 +100,12 @@ export class TokensFacade {
return w.getTokenContractInfoWithProofInfo(contractId);
}

async perpetualDistributionLastClaim(identityId: wasm.IdentifierLike, tokenId: wasm.IdentifierLike): Promise<wasm.TokenLastClaim | undefined> {
async perpetualDistributionLastClaim(identityId: wasm.IdentifierLike, tokenId: wasm.IdentifierLike): Promise<wasm.RewardDistributionMoment | undefined> {
const w = await this.sdk.getWasmSdkConnected();
return w.getTokenPerpetualDistributionLastClaim(identityId, tokenId);
}

async perpetualDistributionLastClaimWithProof(identityId: wasm.IdentifierLike, tokenId: wasm.IdentifierLike): Promise<wasm.ProofMetadataResponseTyped<wasm.TokenLastClaim | undefined>> {
async perpetualDistributionLastClaimWithProof(identityId: wasm.IdentifierLike, tokenId: wasm.IdentifierLike): Promise<wasm.ProofMetadataResponseTyped<wasm.RewardDistributionMoment | undefined>> {
const w = await this.sdk.getWasmSdkConnected();
return w.getTokenPerpetualDistributionLastClaimWithProofInfo(identityId, tokenId);
}
Expand Down
20 changes: 20 additions & 0 deletions packages/js-evo-sdk/tests/functional/epoch.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,24 @@ describe('Epoch', function epochSuite() {
const res = await sdk.epoch.evonodesProposedBlocksByRange({ epoch: TEST_IDS.epoch, limit: 5 });
expect(res).to.exist();
});

it('evonodesProposedBlocksByIdsWithProof() returns results with proof', async () => {
const { epoch, proTxHash } = TEST_IDS;
const res = await sdk.epoch.evonodesProposedBlocksByIdsWithProof(epoch, [proTxHash]);
expect(res).to.exist();
expect(res.data).to.be.instanceOf(Map);
expect(res.proof).to.exist();
expect(res.metadata).to.exist();
});

it('evonodesProposedBlocksByRangeWithProof() returns results with proof', async () => {
const res = await sdk.epoch.evonodesProposedBlocksByRangeWithProof({
epoch: TEST_IDS.epoch,
limit: 5,
});
expect(res).to.exist();
expect(res.data).to.be.instanceOf(Map);
expect(res.proof).to.exist();
expect(res.metadata).to.exist();
});
});
16 changes: 16 additions & 0 deletions packages/js-evo-sdk/tests/functional/protocol.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,24 @@ describe('Protocol', function protocolSuite() {
expect(res).to.exist();
});

it('versionUpgradeStateWithProof() returns state with proof', async () => {
const res = await sdk.protocol.versionUpgradeStateWithProof();
expect(res).to.exist();
expect(res.data).to.exist();
expect(res.proof).to.exist();
expect(res.metadata).to.exist();
});

it('versionUpgradeVoteStatus() returns vote window status', async () => {
const res = await sdk.protocol.versionUpgradeVoteStatus(TEST_IDS.proTxHash, 1);
expect(res).to.exist();
});

it('versionUpgradeVoteStatusWithProof() returns vote status with proof', async () => {
const res = await sdk.protocol.versionUpgradeVoteStatusWithProof(TEST_IDS.proTxHash, 50);
expect(res).to.exist();
expect(res.data).to.be.instanceOf(Map);
expect(res.proof).to.exist();
expect(res.metadata).to.exist();
});
});
28 changes: 28 additions & 0 deletions packages/rs-sdk-trusted-context-provider/src/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ pub struct TrustedHttpContextProvider {
/// Known contracts cache - contracts that are pre-loaded and can be served immediately
known_contracts: Arc<Mutex<HashMap<Identifier, Arc<DataContract>>>>,

/// Known token configurations cache - token configs that are pre-loaded for proof verification
known_token_configurations: Arc<Mutex<HashMap<Identifier, TokenConfiguration>>>,

/// Whether to refetch quorums if not found in cache
refetch_if_not_found: bool,
}
Expand Down Expand Up @@ -165,6 +168,7 @@ impl TrustedHttpContextProvider {
last_previous_quorums: Arc::new(ArcSwap::new(Arc::new(None))),
fallback_provider: None,
known_contracts: Arc::new(Mutex::new(HashMap::new())),
known_token_configurations: Arc::new(Mutex::new(HashMap::new())),
refetch_if_not_found: true,
})
}
Expand Down Expand Up @@ -208,6 +212,23 @@ impl TrustedHttpContextProvider {
}
}

/// Add a token configuration to the known token configurations cache
pub fn add_known_token_configuration(&self, token_id: Identifier, config: TokenConfiguration) {
let mut known = self.known_token_configurations.lock().unwrap();
known.insert(token_id, config);
}

/// Add multiple token configurations to the known token configurations cache
pub fn add_known_token_configurations(
&self,
configs: Vec<(Identifier, TokenConfiguration)>,
) {
let mut known = self.known_token_configurations.lock().unwrap();
for (token_id, config) in configs {
known.insert(token_id, config);
}
}

/// Update the quorum caches by fetching current and previous quorums
pub async fn update_quorum_caches(&self) -> Result<(), TrustedContextProviderError> {
// Fetch current quorums
Expand Down Expand Up @@ -747,6 +768,13 @@ impl ContextProvider for TrustedHttpContextProvider {
&self,
token_id: &Identifier,
) -> Result<Option<TokenConfiguration>, ContextProviderError> {
// First check known token configurations cache
let known = self.known_token_configurations.lock().unwrap();
if let Some(config) = known.get(token_id) {
return Ok(Some(config.clone()));
}
drop(known);

// Delegate to fallback provider if available
if let Some(ref provider) = self.fallback_provider {
provider.get_token_configuration(token_id)
Expand Down
52 changes: 52 additions & 0 deletions packages/wasm-dpp2/TODO.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# wasm-dpp2 TODO

## Type Wrappers for Flexible Input

### ProTxHash Wrapper

Create a wrapper around `ProTxHash` from dashcore with flexible input types.

`ProTxHash` is a newtype wrapper around `sha256d::Hash`:

```rust
pub struct ProTxHash(sha256d::Hash);
```

```typescript
type ProTxHashLike = ProTxHash | Uint8Array | string;
```

**Requirements:**

- Create `ProTxHashWasm` wrapper in wasm-dpp2
- Accept hex string, raw bytes (Uint8Array), or ProTxHash object
- Centralize parsing logic (currently duplicated in wasm-sdk methods)

**Affected areas in wasm-sdk:**

- `getProtocolVersionUpgradeVoteStatus` (startProTxHash parameter)
- `getProtocolVersionUpgradeVoteStatusWithProofInfo` (startProTxHash parameter)
- `getEvonodesProposedEpochBlocksByIds` (ids parameter)
- `getEvonodesProposedEpochBlocksByIdsWithProofInfo` (proTxHashes parameter)
- `EvonodeProposedBlocksRangeQuery.startAfter` field

### Network Wrapper

Create a wrapper around `Network` from dashcore with flexible input types:

```typescript
type NetworkLike = Network | string;
```

**Requirements:**

- Create `NetworkWasm` wrapper in wasm-dpp2
- Accept string ("mainnet", "testnet", "devnet", "regtest") or Network object
- Centralize parsing logic
- Use everywhere we pass network parameter

**Affected areas:**

- SDK builder methods
- Wallet key derivation
- Address generation/validation
5 changes: 5 additions & 0 deletions packages/wasm-sdk/src/context_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,4 +162,9 @@ impl WasmTrustedContext {
pub fn add_known_contract(&self, contract: DataContract) {
self.inner.add_known_contract(contract);
}

/// Add a token configuration to the known token configurations cache
pub fn add_known_token_configuration(&self, token_id: Identifier, config: TokenConfiguration) {
self.inner.add_known_token_configuration(token_id, config);
}
}
100 changes: 72 additions & 28 deletions packages/wasm-sdk/src/queries/epoch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,12 +164,6 @@ export interface EvonodeProposedBlocksRangeQuery {
* @default undefined
*/
startAfter?: string;

/**
* Sort order for results.
* @default undefined (server default)
*/
orderAscending?: boolean;
}
"#;

Expand All @@ -187,15 +181,12 @@ struct EvonodeProposedBlocksRangeQueryInput {
limit: Option<u32>,
#[serde(default)]
start_after: Option<String>,
#[serde(default)]
order_ascending: Option<bool>,
}

struct EvonodeProposedBlocksRangeQueryParsed {
epoch: u16,
limit: Option<u32>,
start_info: Option<QueryStartInfo>,
order_ascending: Option<bool>,
}

fn parse_evonode_range_query(
Expand Down Expand Up @@ -223,7 +214,6 @@ fn parse_evonode_range_query(
epoch: input.epoch,
limit: input.limit,
start_info,
order_ascending: input.order_ascending,
})
}

Expand Down Expand Up @@ -374,11 +364,8 @@ impl WasmSdk {
epoch,
limit,
start_info,
order_ascending,
} = parse_evonode_range_query(query)?;

let _ = order_ascending;

let counts_result = ProposerBlockCounts::fetch_proposed_blocks_by_range(
self.as_ref(),
Some(epoch),
Expand Down Expand Up @@ -517,31 +504,88 @@ impl WasmSdk {
))
}

#[wasm_bindgen(js_name = "getEvonodesProposedEpochBlocksByIdsWithProofInfo")]
#[wasm_bindgen(
js_name = "getEvonodesProposedEpochBlocksByIdsWithProofInfo",
unchecked_return_type = "ProofMetadataResponseTyped<Map<Identifier, bigint>>"
)]
pub async fn get_evonodes_proposed_epoch_blocks_by_ids_with_proof_info(
&self,
epoch: u16,
#[wasm_bindgen(js_name = "proTxHashes")] pro_tx_hashes: Vec<String>,
) -> Result<JsValue, WasmSdkError> {
// TODO: Implement once SDK Query trait is implemented for ProposerBlockCountById
// Currently not supported due to query format issues
let _ = (self, epoch, pro_tx_hashes); // Parameters will be used when implemented
Err(WasmSdkError::generic(
"get_evonodes_proposed_epoch_blocks_by_ids_with_proof_info is not yet implemented",
) -> Result<ProofMetadataResponseWasm, WasmSdkError> {
use drive_proof_verifier::types::ProposerBlockCountById;

// Parse the ProTxHash strings
let parsed_hashes: Vec<ProTxHash> = pro_tx_hashes
.into_iter()
.map(|hash_str| {
ProTxHash::from_str(&hash_str).map_err(|e| {
WasmSdkError::invalid_argument(format!(
"Invalid ProTxHash '{}': {}",
hash_str, e
))
})
})
.collect::<Result<Vec<_>, WasmSdkError>>()?;

// Use FetchMany with proof to get block counts for specific IDs
let (counts, metadata, proof) = ProposerBlockCountById::fetch_many_with_metadata_and_proof(
self.as_ref(),
(epoch, parsed_hashes),
None,
)
.await?;

let map = Map::new();
for (identifier, count) in counts.0 {
let key = JsValue::from(IdentifierWasm::from(identifier));
map.set(&key, &JsValue::from(BigInt::from(count)));
}

Ok(ProofMetadataResponseWasm::from_sdk_parts(
map, metadata, proof,
))
}

#[wasm_bindgen(js_name = "getEvonodesProposedEpochBlocksByRangeWithProofInfo")]
#[wasm_bindgen(
js_name = "getEvonodesProposedEpochBlocksByRangeWithProofInfo",
unchecked_return_type = "ProofMetadataResponseTyped<Map<Identifier, bigint>>"
)]
pub async fn get_evonodes_proposed_epoch_blocks_by_range_with_proof_info(
&self,
query: EvonodeProposedBlocksRangeQueryJs,
) -> Result<JsValue, WasmSdkError> {
// TODO: Implement once SDK Query trait is implemented for ProposerBlockCountByRange
// Currently not supported due to query format issues
let parsed = parse_evonode_range_query(query)?;
let _ = (self, parsed); // Parameters will be used when implemented
Err(WasmSdkError::generic(
"get_evonodes_proposed_epoch_blocks_by_range_with_proof_info is not yet implemented",
) -> Result<ProofMetadataResponseWasm, WasmSdkError> {
use drive_proof_verifier::types::ProposerBlockCountByRange;

let EvonodeProposedBlocksRangeQueryParsed {
epoch,
limit,
start_info,
} = parse_evonode_range_query(query)?;

// Create a LimitQuery for the range request
let limit_query = LimitQuery {
query: Some(epoch),
limit,
start_info,
};

let (counts, metadata, proof) =
ProposerBlockCountByRange::fetch_many_with_metadata_and_proof(
self.as_ref(),
limit_query,
None,
)
.await?;

let map = Map::new();
for (identifier, count) in counts.0 {
let key = JsValue::from(IdentifierWasm::from(identifier));
map.set(&key, &JsValue::from(BigInt::from(count)));
}

Ok(ProofMetadataResponseWasm::from_sdk_parts(
map, metadata, proof,
))
}
}
Loading
Loading