Skip to content

fix: remove serde_json::value from transaction endpoints#297

Open
bee344 wants to merge 2 commits into
mainfrom
anp-remove-value
Open

fix: remove serde_json::value from transaction endpoints#297
bee344 wants to merge 2 commits into
mainfrom
anp-remove-value

Conversation

@bee344
Copy link
Copy Markdown
Contributor

@bee344 bee344 commented Mar 13, 2026

Replacement of #294 .
Also fixes a regression introduced in the dry_run call.

@bee344 bee344 requested review from TarikGul and jsdw March 13, 2026 15:46
@jsdw
Copy link
Copy Markdown
Contributor

jsdw commented Mar 13, 2026

If we had more time I would hope something more like this would work:

async fn dry_run_internal(
    client: &subxt::OnlineClient<subxt::SubstrateConfig>,
    body: DryRunRequest,
) -> Result<Json<DryRunResponse>, DryRunError> {
    let tx = body.tx.as_ref().ok_or(DryRunError::MissingTx)?;
    if tx.is_empty() {
        return Err(DryRunError::MissingTx);
    }
    let sender = validate_sender(&body.sender_address, tx)?;

    // Resolve block
    let client_at = match &body.at {
        None => client.at_current_block().await?,
        Some(at_str) => {
            let block_id =
                at_str
                    .parse::<BlockId>()
                    .map_err(|e| DryRunError::InvalidBlockParam {
                        transaction: tx.to_string(),
                        cause: e.to_string(),
                    })?;
            match block_id {
                BlockId::Hash(hash) => client.at_block(hash).await?,
                BlockId::Number(num) => client.at_block(num).await?,
            }
        }
    };

    // Build origin: OriginCaller::system(RawOrigin::Signed(account))
    let sender_bytes = decode_ss58_address(sender).map_err(|e| DryRunError::ParseFailed {
        transaction: tx.to_string(),
        cause: e.clone(),
        stack: format!("Error: {}\n    at dry_run", e),
    })?;

    // Decode the full extrinsic hex
    let tx_bytes =
        hex::decode(tx.strip_prefix("0x").unwrap_or(tx)).map_err(|e| DryRunError::ParseFailed {
            transaction: tx.to_string(),
            cause: format!("Invalid hex encoding: {}", e),
            stack: format!("Error: Invalid hex encoding: {}\n    at dry_run", e),
        })?;

    // Extract call bytes from the signed extrinsic using frame_decode
    let metadata = client_at.metadata();
    let extrinsic_info = frame_decode::extrinsics::decode_extrinsic(
        &mut &tx_bytes[..],
        &*metadata,
        metadata.types(),
    )
    .map_err(|e| {
        let cause = format!("Failed to decode extrinsic: {}", e);
        DryRunError::ParseFailed {
            transaction: tx.to_string(),
            cause: cause.clone(),
            stack: format!("Error: {}\n    at dry_run", cause),
        }
    })?;
    let call_range = extrinsic_info.call_data_range();

    // --- gather the arguments we'll be passing to the call ---

    // Call bytes argument.
    let call_bytes = &tx_bytes[call_range];

    // Origin argument.
    #[derive(scale_encode::EncodeAsType)]
    enum Origin {
        system(Caller)
    }
    #[derive(scale_encode::EncodeAsType)]
    enum Caller {
        Signer([u8; 32])
    }
    let origin = Origin::system(Caller::Signer(sender_bytes));

    // xcms_version argument.
    let xcm_version_addr = subxt::dynamic::constant::<u32>("PolkadotXcm", "AdvertisedXcmVersion");
    let xcm_version = client_at.constants().entry(xcm_version_addr).map_err(|e| {
        DryRunError::DryRunFailed {
            transaction: tx.to_string(),
            cause: format!("Failed to fetch AdvertisedXcmVersion: {}", e),
            stack: format!("Error: Failed to fetch AdvertisedXcmVersion: {}\n    at dry_run", e),
        }
    })?;

    // --- make the call ---
    let payload = subxt::runtime_apis::dynamic::<(Origin, Vec<u8>, u32), DryRunResult>(
        "DryRunApi",
        "dry_run_call",
        (origin, call_bytes, xcm_version)
    );
    let dry_run_result = client_at
        .runtime_apis()
        .call(payload)
        .await
        .map_err(|e| {
            let cause = e.to_string();
            DryRunError::DryRunFailed {
                transaction: tx.to_string(),
                cause: cause.clone(),
                stack: format!("Error: {}\n    at dry_run", cause),
            }
        })?;

    // --- transform and return it ---
    parse_result_to_response(dry_run_result, tx)
}

#[derive(scale_encode::EncodeAsType)]
enum DryRunResult {
    // What do we expect the dry run result from the node to look like?
    // make this type match that!
}

The main differences being:

  • Rely on Subxt to know how to encode the runtime API types appropriately, avoiding scale_value::Value.
  • Rely on Subxt to decode the response. This could be decoded into a scale_value::Value but ideally I would define the expected shape (or multiple expected shapes if it changes across runtimes) and then try to decode into each

This second point does expose a weakness in the Subxt APIs; when you cann a Runtime API you just get back the decoded result type or an error, which means you'd have to call it multiple times to try decoding the result into multiple types. APIs like storage have been changed to avoid that sort of issue. Thus, decoding to scale_value::Value may currently be easiest if there are multiple possible target types, or defining some type which grabs the type ID and bytes and then decode from that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants