1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
use crate::{Client, ClientError, Signer};
use ethers_providers::{JsonRpcClient, Provider};
use ethers_core::{
rand::Rng,
secp256k1,
types::{Address, PrivateKey, PublicKey, Signature, Transaction, TransactionRequest, TxError},
};
use serde::{Deserialize, Serialize};
use std::str::FromStr;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Wallet {
private_key: PrivateKey,
public_key: PublicKey,
address: Address,
chain_id: Option<u64>,
}
impl Signer for Wallet {
type Error = TxError;
fn sign_message<S: AsRef<[u8]>>(&self, message: S) -> Signature {
self.private_key.sign(message)
}
fn sign_transaction(&self, tx: TransactionRequest) -> Result<Transaction, Self::Error> {
self.private_key.sign_transaction(tx, self.chain_id)
}
fn address(&self) -> Address {
self.address
}
}
impl From<TxError> for ClientError {
fn from(src: TxError) -> Self {
ClientError::SignerError(Box::new(src))
}
}
impl Wallet {
pub fn new<R: Rng>(rng: &mut R) -> Self {
let private_key = PrivateKey::new(rng);
let public_key = PublicKey::from(&private_key);
let address = Address::from(&private_key);
Self {
private_key,
public_key,
address,
chain_id: None,
}
}
pub fn connect<P: JsonRpcClient>(self, provider: Provider<P>) -> Client<P, Wallet> {
let address = self.address();
Client {
address,
signer: self,
provider,
}
}
pub fn set_chain_id<T: Into<u64>>(mut self, chain_id: T) -> Self {
self.chain_id = Some(chain_id.into());
self
}
pub fn public_key(&self) -> &PublicKey {
&self.public_key
}
pub fn private_key(&self) -> &PrivateKey {
&self.private_key
}
pub fn chain_id(&self) -> Option<u64> {
self.chain_id
}
}
impl From<PrivateKey> for Wallet {
fn from(private_key: PrivateKey) -> Self {
let public_key = PublicKey::from(&private_key);
let address = Address::from(&private_key);
Self {
private_key,
public_key,
address,
chain_id: None,
}
}
}
impl FromStr for Wallet {
type Err = secp256k1::Error;
fn from_str(src: &str) -> Result<Self, Self::Err> {
Ok(PrivateKey::from_str(src)?.into())
}
}