Skip to content
This repository was archived by the owner on Jun 1, 2026. It is now read-only.

Commit e7a8805

Browse files
committed
Implement Polkadot signer
1 parent 9273c46 commit e7a8805

17 files changed

Lines changed: 624 additions & 31 deletions

File tree

‎Cargo.lock‎

Lines changed: 6 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ chrono = { version = "0.4.43", features = ["serde"] }
9292
# crypto
9393
base64 = { version = "0.22.1" }
9494
bech32 = { version = "0.11.1" }
95+
blake2 = { version = "0.10.6" }
9596
bs58 = { version = "0.5.1", features = ["check"] }
9697
hex = { version = "0.4.3" }
9798
crc = { version = "3.4.0" }

‎crates/gem_hash/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ version = { workspace = true }
44
edition = { workspace = true }
55

66
[dependencies]
7+
blake2 = { workspace = true }
78
hex = { workspace = true }
89
sha2 = { workspace = true }
910
sha3 = { workspace = true }

‎crates/gem_hash/src/blake2.rs‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
use blake2::{Blake2b, Blake2b512, Digest, digest::consts::U32};
2+
3+
type Blake2b256 = Blake2b<U32>;
4+
5+
pub fn blake2b_256(bytes: &[u8]) -> [u8; 32] {
6+
let mut hasher = Blake2b256::new();
7+
Digest::update(&mut hasher, bytes);
8+
hasher.finalize().into()
9+
}
10+
11+
pub fn blake2b_512(bytes: &[u8]) -> [u8; 64] {
12+
let mut hasher = Blake2b512::new();
13+
Digest::update(&mut hasher, bytes);
14+
hasher.finalize().into()
15+
}

‎crates/gem_hash/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
pub mod blake2;
12
pub mod keccak;
23
pub mod message;
34
pub mod sha2;

‎crates/gem_polkadot/Cargo.toml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ edition = { workspace = true }
55

66
[features]
77
default = ["rpc"]
8+
signer = []
89
rpc = [
910
"dep:serde_json",
1011
"dep:serde_serializers",
@@ -20,6 +21,11 @@ primitives = { path = "../primitives" }
2021
serde = { workspace = true, features = ["derive"] }
2122
num-bigint = { workspace = true }
2223
chrono = { workspace = true, features = ["serde"] }
24+
bs58 = { workspace = true }
25+
gem_hash = { path = "../gem_hash" }
26+
hex = { workspace = true }
27+
signer = { path = "../signer" }
28+
rand = { workspace = true }
2329

2430
# Optional RPC dependencies
2531
serde_json = { workspace = true, optional = true }

‎crates/gem_polkadot/src/address.rs‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
use std::fmt;
2+
3+
use primitives::Address;
4+
5+
const POLKADOT_PREFIX: u8 = 0;
6+
const ADDRESS_DATA_LENGTH: usize = 32;
7+
const ADDRESS_CHECKSUM_LENGTH: usize = 2;
8+
const ADDRESS_LENGTH: usize = 1 + ADDRESS_DATA_LENGTH + ADDRESS_CHECKSUM_LENGTH;
9+
const ADDRESS_MAX_STRING_LENGTH: usize = 60;
10+
const SS58_CHECKSUM_PREFIX: &[u8] = b"SS58PRE";
11+
12+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13+
pub struct PolkadotAddress([u8; ADDRESS_DATA_LENGTH]);
14+
15+
impl Address for PolkadotAddress {
16+
fn try_parse(value: &str) -> Option<Self> {
17+
if value.len() > ADDRESS_MAX_STRING_LENGTH {
18+
return None;
19+
}
20+
21+
let decoded = bs58::decode(value).into_vec().ok()?;
22+
if decoded.len() != ADDRESS_LENGTH || decoded[0] != POLKADOT_PREFIX {
23+
return None;
24+
}
25+
26+
let checksum = Self::checksum(&decoded[..1 + ADDRESS_DATA_LENGTH]);
27+
if decoded[1 + ADDRESS_DATA_LENGTH..] != checksum {
28+
return None;
29+
}
30+
31+
Some(Self(decoded[1..1 + ADDRESS_DATA_LENGTH].try_into().ok()?))
32+
}
33+
34+
fn as_bytes(&self) -> &[u8] {
35+
&self.0
36+
}
37+
38+
fn encode(&self) -> String {
39+
let mut raw = Vec::with_capacity(ADDRESS_LENGTH);
40+
raw.push(POLKADOT_PREFIX);
41+
raw.extend_from_slice(&self.0);
42+
raw.extend_from_slice(&Self::checksum(&raw));
43+
bs58::encode(raw).into_string()
44+
}
45+
}
46+
47+
impl PolkadotAddress {
48+
pub(crate) fn account_id(&self) -> &[u8; ADDRESS_DATA_LENGTH] {
49+
&self.0
50+
}
51+
52+
fn checksum(data: &[u8]) -> [u8; ADDRESS_CHECKSUM_LENGTH] {
53+
let mut prefixed = Vec::with_capacity(SS58_CHECKSUM_PREFIX.len() + data.len());
54+
prefixed.extend_from_slice(SS58_CHECKSUM_PREFIX);
55+
prefixed.extend_from_slice(data);
56+
57+
let hash = gem_hash::blake2::blake2b_512(&prefixed);
58+
let mut checksum = [0u8; ADDRESS_CHECKSUM_LENGTH];
59+
checksum.copy_from_slice(&hash[..ADDRESS_CHECKSUM_LENGTH]);
60+
checksum
61+
}
62+
}
63+
64+
pub fn validate_address(address: &str) -> bool {
65+
PolkadotAddress::is_valid(address)
66+
}
67+
68+
impl fmt::Display for PolkadotAddress {
69+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70+
f.write_str(&self.encode())
71+
}
72+
}
73+
74+
#[cfg(test)]
75+
mod tests {
76+
use super::*;
77+
78+
const VALID_ADDRESS: &str = "15e6w4u9nH4Tb9HdJco2Zua4y5DpHb1hHXBKBGkUrLMTpuXo";
79+
const PUBLIC_KEY: &str = "cd3cfbbaa8f217c2a29ceae4b4063b597b629861916bad98f9826e03d1ab120e";
80+
81+
#[test]
82+
fn test_polkadot_address() {
83+
let parsed = PolkadotAddress::from_str(VALID_ADDRESS).unwrap();
84+
85+
assert!(validate_address(VALID_ADDRESS));
86+
assert_eq!(hex::encode(parsed.as_bytes()), PUBLIC_KEY);
87+
assert_eq!(parsed.to_string(), VALID_ADDRESS);
88+
assert_eq!(PolkadotAddress::try_parse(&parsed.encode()), Some(parsed));
89+
90+
assert!(PolkadotAddress::from_str("invalid").is_err());
91+
assert!(!validate_address(&"1".repeat(ADDRESS_MAX_STRING_LENGTH + 1)));
92+
assert!(!validate_address("15e6w4u9nH4Tb9HdJco2Zua4y5DpHb1hHXBKBGkUrLMTpuXj"));
93+
}
94+
}

‎crates/gem_polkadot/src/lib.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,13 @@ pub mod rpc;
44
#[cfg(feature = "rpc")]
55
pub mod provider;
66

7+
pub mod address;
78
pub mod constants;
89
pub mod models;
10+
#[cfg(feature = "signer")]
11+
pub mod signer;
12+
mod transfer;
913

14+
pub use address::{PolkadotAddress, validate_address};
1015
#[cfg(feature = "rpc")]
1116
pub use rpc::client::PolkadotClient;
Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,22 @@
1+
use num_bigint::BigUint;
12
use serde::{Deserialize, Serialize};
2-
use serde_serializers::deserialize_u64_from_str;
3+
use serde_serializers::deserialize_biguint_from_str;
34

45
#[derive(Debug, Clone, Serialize, Deserialize)]
56
#[serde(rename_all = "camelCase")]
67
pub struct PolkadotEstimateFee {
7-
#[serde(deserialize_with = "deserialize_u64_from_str")]
8-
pub partial_fee: u64,
8+
#[serde(deserialize_with = "deserialize_biguint_from_str")]
9+
pub partial_fee: BigUint,
10+
}
11+
12+
#[cfg(test)]
13+
mod tests {
14+
use super::*;
15+
16+
#[test]
17+
fn test_estimate_fee_deserializes_base_units_without_narrowing() {
18+
let fee: PolkadotEstimateFee = serde_json::from_str(r#"{"partialFee":"18446744073709551616"}"#).unwrap();
19+
20+
assert_eq!(fee.partial_fee, BigUint::parse_bytes(b"18446744073709551616", 10).unwrap());
21+
}
922
}

‎crates/gem_polkadot/src/provider/preload.rs‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1+
use std::error::Error;
2+
13
use async_trait::async_trait;
24
use chain_traits::ChainTransactionLoad;
35
use num_bigint::BigInt;
4-
use std::error::Error;
56

67
use gem_client::Client;
78
use primitives::{
@@ -27,16 +28,15 @@ impl<C: Client> ChainTransactionLoad for PolkadotClient<C> {
2728
})
2829
}
2930

30-
async fn get_transaction_fee_from_data(&self, tx: String) -> Result<TransactionFee, Box<dyn Error + Sync + Send>> {
31-
let fee = self.estimate_fee(&tx).await?;
31+
async fn get_transaction_fee_from_data(&self, transaction: String) -> Result<TransactionFee, Box<dyn Error + Sync + Send>> {
32+
let fee = self.estimate_fee(&transaction).await?;
3233
Ok(TransactionFee::new_from_fee(BigInt::from(fee.partial_fee)))
3334
}
3435

3536
async fn get_transaction_load(&self, input: TransactionLoadInput) -> Result<TransactionLoadData, Box<dyn Error + Sync + Send>> {
36-
Ok(TransactionLoadData {
37-
fee: input.default_fee(),
38-
metadata: input.metadata,
39-
})
37+
let fee_estimation_transaction = crate::transfer::fee_estimation_transaction(&input)?;
38+
let fee = self.get_transaction_fee_from_data(fee_estimation_transaction).await?;
39+
Ok(TransactionLoadData { fee, metadata: input.metadata })
4040
}
4141

4242
async fn get_transaction_fee_rates(&self, _input_type: TransactionInputType) -> Result<Vec<FeeRate>, Box<dyn Error + Sync + Send>> {

0 commit comments

Comments
 (0)