Skip to content
Draft
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
11 changes: 10 additions & 1 deletion packages/wasm-dot/js/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,15 @@ import type { TransactionIntent, BuildContext } from "./types.js";
*
* The intent describes *what* to do (payment, stake, etc.) and the context
* provides *how* to build it (sender, nonce, material, validity).
* Multi-call intents are batched automatically.
* Multi-call intents are batched automatically. Destinations must have the
* SS58 prefix of context.material.chainName (Polkadot 0, Kusama 2, Westend 42).
* Other chains must supply material.ss58AddressPolicy.prefix. Generic prefix 42
* is only accepted on another chain with allowGeneric: true; because calls
* encode AccountId32 without a prefix, parseTransaction will display its
* canonical chain-form address. The caller must show and obtain approval for
* that canonical address before using allowGeneric.
* A wrong-domain destination throws an Error with code "WrongNetwork",
* actualPrefix, and expectedPrefix.
*
* @param intent - Business intent (payment, stake, unstake, claim, etc.)
* @param context - Build context (sender, nonce, material, validity, referenceBlock)
Expand All @@ -26,6 +34,7 @@ import type { TransactionIntent, BuildContext } from "./types.js";
* ```typescript
* import { buildTransaction } from '@bitgo/wasm-dot';
*
* // These prefix-42 examples assume Westend material in context.
* // Payment
* const tx = buildTransaction(
* { type: 'payment', to: '5FHneW46...', amount: 1000000000000n },
Expand Down
2 changes: 2 additions & 0 deletions packages/wasm-dot/js/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ function createParseContext(ctx: ParseContext): ParseContextJs {
ctx.material.specVersion,
ctx.material.txVersion,
ctx.material.metadata,
ctx.material.ss58AddressPolicy?.prefix,
ctx.material.ss58AddressPolicy?.allowGeneric,
);
return new ParseContextJs(material, ctx.sender ?? null);
}
4 changes: 4 additions & 0 deletions packages/wasm-dot/js/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,8 @@ export class DotTransaction {
material.specVersion,
material.txVersion,
material.metadata,
material.ss58AddressPolicy?.prefix,
material.ss58AddressPolicy?.allowGeneric,
);
const validityJs = new ValidityJs(validity.firstValid, validity.maxDuration);
this._wasm.setContext(materialJs, validityJs, referenceBlock);
Expand Down Expand Up @@ -219,6 +221,8 @@ function createContext(material: Material): ParseContextJs {
material.specVersion,
material.txVersion,
material.metadata,
material.ss58AddressPolicy?.prefix,
material.ss58AddressPolicy?.allowGeneric,
);
return new ParseContextJs(m, null);
}
23 changes: 17 additions & 6 deletions packages/wasm-dot/js/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,20 @@ export interface Material {
* SCALE decoding.
*/
metadata: string;
/** Required for chains outside the built-in Polkadot/Kusama/Westend mapping.
* For known chains, prefix must match the chain's canonical format.
*/
ss58AddressPolicy?: Ss58AddressPolicy;
}

/** Accepted SS58 formats for addresses used by the transaction builder. */
export interface Ss58AddressPolicy {
/** The canonical chain prefix, in the SS58 range 0..16383. */
prefix: number;
/** Explicitly accept generic (42) inputs; they parse back in the chain format.
* Approve the canonical chain-form address before submitting such an intent.
*/
allowGeneric?: boolean;
}

/**
Expand Down Expand Up @@ -221,16 +235,13 @@ export interface ParsedTransaction {
}

/**
* SS58 address format prefixes.
* Using a numeric union type rather than an enum so that callers can pass
* the raw SS58 prefix number directly without a cast.
* SS58 address format prefix (0..16383). Custom chains can use their
* verified numeric prefix without a cast.
*/
export type AddressFormat = 0 | 2 | 42;
export type AddressFormat = number;

/**
* Named constants for common SS58 address formats.
* All existing call sites using AddressFormat.Polkadot / .Kusama / .Substrate
* continue to work unchanged.
*/
export const AddressFormat = {
/** Polkadot mainnet (prefix 0, addresses start with '1') */
Expand Down
96 changes: 73 additions & 23 deletions packages/wasm-dot/src/builder/calls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use crate::address::decode_ss58;
use crate::builder::types::{intent_to_calls, CallIntent, StakePayee, TransactionIntent};
use crate::error::WasmDotError;
use crate::types::Ss58AddressPolicy;
use subxt_core::{
ext::scale_value::{Composite, Value},
metadata::Metadata,
Expand All @@ -22,20 +23,25 @@ pub fn encode_intent(
intent: &TransactionIntent,
sender: &str,
metadata: &Metadata,
policy: Ss58AddressPolicy,
) -> Result<Vec<u8>, WasmDotError> {
let calls = intent_to_calls(intent, sender)?;

match calls.len() {
0 => Err(WasmDotError::InvalidInput(
"Intent produced no calls".to_string(),
)),
1 => encode_call(&calls[0], metadata),
_ => encode_batch(&calls, metadata),
1 => encode_call(&calls[0], metadata, policy),
_ => encode_batch(&calls, metadata, policy),
}
}

/// Encode a single call-level intent to call data bytes.
fn encode_call(call: &CallIntent, metadata: &Metadata) -> Result<Vec<u8>, WasmDotError> {
fn encode_call(
call: &CallIntent,
metadata: &Metadata,
policy: Ss58AddressPolicy,
) -> Result<Vec<u8>, WasmDotError> {
let payload = match call {
CallIntent::Transfer {
to,
Expand All @@ -47,10 +53,10 @@ fn encode_call(call: &CallIntent, metadata: &Metadata) -> Result<Vec<u8>, WasmDo
} else {
"transfer_allow_death"
};
balances(method, to, *amount)?
balances(method, to, *amount, policy)?
}
CallIntent::TransferAll { to, keep_alive } => transfer_all(to, *keep_alive)?,
CallIntent::Bond { amount, payee } => staking_bond(*amount, payee)?,
CallIntent::TransferAll { to, keep_alive } => transfer_all(to, *keep_alive, policy)?,
CallIntent::Bond { amount, payee } => staking_bond(*amount, payee, policy)?,
CallIntent::BondExtra { amount } => staking_bond_extra(*amount),
CallIntent::Unbond { amount } => staking_unbond(*amount),
CallIntent::WithdrawUnbonded { slashing_spans } => {
Expand All @@ -61,12 +67,12 @@ fn encode_call(call: &CallIntent, metadata: &Metadata) -> Result<Vec<u8>, WasmDo
delegate,
proxy_type,
delay,
} => proxy_add(delegate, proxy_type, *delay)?,
} => proxy_add(delegate, proxy_type, *delay, policy)?,
CallIntent::RemoveProxy {
delegate,
proxy_type,
delay,
} => proxy_remove(delegate, proxy_type, *delay)?,
} => proxy_remove(delegate, proxy_type, *delay, policy)?,
};

payload
Expand All @@ -82,12 +88,13 @@ fn balances(
method: &str,
to: &str,
amount: u64,
policy: Ss58AddressPolicy,
) -> Result<subxt_core::tx::payload::DynamicPayload, WasmDotError> {
Ok(dynamic(
"Balances",
method,
named([
("dest", multi_address(to)?),
("dest", multi_address(to, policy)?),
("value", Value::u128(amount as u128)),
]),
))
Expand All @@ -96,12 +103,13 @@ fn balances(
fn transfer_all(
to: &str,
keep_alive: bool,
policy: Ss58AddressPolicy,
) -> Result<subxt_core::tx::payload::DynamicPayload, WasmDotError> {
Ok(dynamic(
"Balances",
"transfer_all",
named([
("dest", multi_address(to)?),
("dest", multi_address(to, policy)?),
("keep_alive", Value::bool(keep_alive)),
]),
))
Expand All @@ -114,13 +122,14 @@ fn transfer_all(
fn staking_bond(
amount: u64,
payee: &StakePayee,
policy: Ss58AddressPolicy,
) -> Result<subxt_core::tx::payload::DynamicPayload, WasmDotError> {
let payee_value = match payee {
StakePayee::Staked => Value::unnamed_variant("Staked", []),
StakePayee::Stash => Value::unnamed_variant("Stash", []),
StakePayee::Controller => Value::unnamed_variant("Controller", []),
StakePayee::Account { address } => {
Value::unnamed_variant("Account", [account_id(address)?])
Value::unnamed_variant("Account", [account_id(address, policy)?])
}
};

Expand Down Expand Up @@ -173,12 +182,13 @@ fn proxy_add(
delegate: &str,
proxy_type: &str,
delay: u32,
policy: Ss58AddressPolicy,
) -> Result<subxt_core::tx::payload::DynamicPayload, WasmDotError> {
Ok(dynamic(
"Proxy",
"add_proxy",
named([
("delegate", multi_address(delegate)?),
("delegate", multi_address(delegate, policy)?),
("proxy_type", Value::unnamed_variant(proxy_type, [])),
("delay", Value::u128(delay as u128)),
]),
Expand All @@ -189,12 +199,13 @@ fn proxy_remove(
delegate: &str,
proxy_type: &str,
delay: u32,
policy: Ss58AddressPolicy,
) -> Result<subxt_core::tx::payload::DynamicPayload, WasmDotError> {
Ok(dynamic(
"Proxy",
"remove_proxy",
named([
("delegate", multi_address(delegate)?),
("delegate", multi_address(delegate, policy)?),
("proxy_type", Value::unnamed_variant(proxy_type, [])),
("delay", Value::u128(delay as u128)),
]),
Expand All @@ -206,12 +217,16 @@ fn proxy_remove(
// =============================================================================

/// Encode multiple calls as a batchAll (atomic batch).
fn encode_batch(calls: &[CallIntent], metadata: &Metadata) -> Result<Vec<u8>, WasmDotError> {
fn encode_batch(
calls: &[CallIntent],
metadata: &Metadata,
policy: Ss58AddressPolicy,
) -> Result<Vec<u8>, WasmDotError> {
use parity_scale_codec::{Compact, Encode};

let encoded_calls: Result<Vec<_>, _> = calls
.iter()
.map(|call| encode_call(call, metadata))
.map(|call| encode_call(call, metadata, policy))
.collect();
let encoded_calls = encoded_calls?;

Expand Down Expand Up @@ -255,13 +270,19 @@ fn named<const N: usize>(fields: [(&str, Value<()>); N]) -> Composite<()> {
}

/// Convert SS58 address to MultiAddress::Id value
fn multi_address(address: &str) -> Result<Value<()>, WasmDotError> {
Ok(Value::unnamed_variant("Id", [account_id(address)?]))
fn multi_address(address: &str, policy: Ss58AddressPolicy) -> Result<Value<()>, WasmDotError> {
Ok(Value::unnamed_variant("Id", [account_id(address, policy)?]))
}

/// Convert SS58 address to AccountId32 bytes value
fn account_id(address: &str) -> Result<Value<()>, WasmDotError> {
let (pubkey, _) = decode_ss58(address)?;
fn account_id(address: &str, policy: Ss58AddressPolicy) -> Result<Value<()>, WasmDotError> {
let (pubkey, prefix) = decode_ss58(address)?;
if prefix != policy.prefix && !(policy.allow_generic && prefix == 42) {
return Err(WasmDotError::WrongNetwork {
actual: prefix,
expected: policy.prefix,
});
}
let bytes: [u8; 32] = pubkey.try_into().map_err(|v: Vec<u8>| {
WasmDotError::InvalidInput(format!(
"Invalid pubkey length: expected 32, got {}",
Expand Down Expand Up @@ -289,9 +310,38 @@ mod tests {
}

#[test]
fn test_account_id() {
// Valid SS58 address
let result = account_id("5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty");
assert!(result.is_ok());
fn test_account_id_network_binding() {
let pubkey = [7u8; 32];
let polkadot = crate::address::encode_ss58(&pubkey, 0).unwrap();
let kusama = crate::address::encode_ss58(&pubkey, 2).unwrap();
let generic = crate::address::encode_ss58(&pubkey, 42).unwrap();

for (expected, accepted) in [(0, &polkadot), (2, &kusama), (42, &generic)] {
let policy = Ss58AddressPolicy { prefix: expected, allow_generic: false };
assert!(account_id(accepted, policy).is_ok());
for (actual, address) in [(0, &polkadot), (2, &kusama), (42, &generic)] {
if actual != expected {
assert!(matches!(
account_id(address, policy),
Err(WasmDotError::WrongNetwork { actual: found, expected: wanted })
if found == actual && wanted == expected
));
}
}
}

let allow_generic = Ss58AddressPolicy { prefix: 0, allow_generic: true };
assert!(account_id(&generic, allow_generic).is_ok());
assert!(matches!(
account_id(&kusama, allow_generic),
Err(WasmDotError::WrongNetwork { actual: 2, expected: 0 })
));

let mut malformed = generic.into_bytes();
malformed[0] = b'!';
assert!(matches!(
account_id(std::str::from_utf8(&malformed).unwrap(), allow_generic),
Err(WasmDotError::InvalidAddress(_))
));
}
}
5 changes: 3 additions & 2 deletions packages/wasm-dot/src/builder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,12 @@ pub fn build_transaction(
intent: TransactionIntent,
context: BuildContext,
) -> Result<Transaction, WasmDotError> {
// Decode metadata once
// Resolve the address domain before any destination becomes AccountId32.
let address_policy = context.material.address_policy()?;
let metadata = decode_metadata(&context.material.metadata)?;

// Compose intent into calls and encode (batching if needed)
let call_data = encode_intent(&intent, &context.sender, &metadata)?;
let call_data = encode_intent(&intent, &context.sender, &metadata, address_policy)?;

// Calculate era from validity
let era = compute_era(&context.validity);
Expand Down
13 changes: 12 additions & 1 deletion packages/wasm-dot/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ use wasm_bindgen::prelude::*;
pub enum WasmDotError {
/// Invalid SS58 address
InvalidAddress(String),
/// Valid SS58 address from a disallowed network
WrongNetwork { actual: u16, expected: u16 },
/// Invalid transaction format
InvalidTransaction(String),
/// Invalid signature
Expand All @@ -28,6 +30,9 @@ impl fmt::Display for WasmDotError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
WasmDotError::InvalidAddress(s) => write!(f, "Invalid address: {}", s),
WasmDotError::WrongNetwork { actual, expected } => {
write!(f, "Wrong SS58 network: prefix {} (expected {})", actual, expected)
},
WasmDotError::InvalidTransaction(s) => write!(f, "Invalid transaction: {}", s),
WasmDotError::InvalidSignature(s) => write!(f, "Invalid signature: {}", s),
WasmDotError::ScaleDecodeError(s) => write!(f, "SCALE decode error: {}", s),
Expand Down Expand Up @@ -59,7 +64,13 @@ impl From<parity_scale_codec::Error> for WasmDotError {
// REQUIRED: Converts to JS Error with stack trace
impl From<WasmDotError> for JsValue {
fn from(err: WasmDotError) -> Self {
js_sys::Error::new(&err.to_string()).into()
let error: JsValue = js_sys::Error::new(&err.to_string()).into();
if let WasmDotError::WrongNetwork { actual, expected } = err {
let _ = js_sys::Reflect::set(&error, &"code".into(), &"WrongNetwork".into());
let _ = js_sys::Reflect::set(&error, &"actualPrefix".into(), &JsValue::from_f64(actual as f64));
let _ = js_sys::Reflect::set(&error, &"expectedPrefix".into(), &JsValue::from_f64(expected as f64));
}
error
}
}

Expand Down
Loading
Loading