-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathmessage.rs
285 lines (254 loc) · 8.36 KB
/
message.rs
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
// Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: Apache-2.0, MIT
use std::path::Path;
use anyhow::Context;
use base64::Engine;
use bytes::Bytes;
use fendermint_crypto::SecretKey;
use fendermint_vm_actor_interface::{eam, evm};
use fendermint_vm_message::{chain::ChainMessage, signed::SignedMessage};
use fvm_ipld_encoding::{BytesSer, RawBytes};
use fvm_shared::{
address::Address, chainid::ChainID, econ::TokenAmount, message::Message, MethodNum, METHOD_SEND,
};
use fs_err as fs;
use crate::B64_ENGINE;
/// Factory methods for transaction payload construction.
///
/// It assumes the sender is an `f1` type address, it won't work with `f410` addresses.
/// For those one must use the Ethereum API, with a suitable client library such as [ethers].
pub struct MessageFactory {
addr: Address,
sequence: u64,
}
impl MessageFactory {
pub fn new(addr: Address, sequence: u64) -> Self {
Self { addr, sequence }
}
pub fn address(&self) -> &Address {
&self.addr
}
/// Set the sequence to an arbitrary value.
pub fn set_sequence(&mut self, sequence: u64) {
self.sequence = sequence;
}
pub fn transaction(
&mut self,
to: Address,
method_num: MethodNum,
params: RawBytes,
value: TokenAmount,
gas_params: GasParams,
) -> Message {
let msg = Message {
version: Default::default(), // TODO: What does this do?
from: self.addr,
to,
sequence: self.sequence,
value,
method_num,
params,
gas_limit: gas_params.gas_limit,
gas_fee_cap: gas_params.gas_fee_cap,
gas_premium: gas_params.gas_premium,
};
self.sequence += 1;
msg
}
pub fn fevm_create(
&mut self,
contract: Bytes,
constructor_args: Bytes,
value: TokenAmount,
gas_params: GasParams,
) -> anyhow::Result<Message> {
let initcode = [contract.to_vec(), constructor_args.to_vec()].concat();
let initcode = RawBytes::serialize(BytesSer(&initcode))?;
Ok(self.transaction(
eam::EAM_ACTOR_ADDR,
eam::Method::CreateExternal as u64,
initcode,
value,
gas_params,
))
}
pub fn fevm_invoke(
&mut self,
contract: Address,
calldata: Bytes,
value: TokenAmount,
gas_params: GasParams,
) -> anyhow::Result<Message> {
let calldata = RawBytes::serialize(BytesSer(&calldata))?;
Ok(self.transaction(
contract,
evm::Method::InvokeContract as u64,
calldata,
value,
gas_params,
))
}
pub fn fevm_call(
&mut self,
contract: Address,
calldata: Bytes,
value: TokenAmount,
gas_params: GasParams,
) -> anyhow::Result<Message> {
let msg = self.fevm_invoke(contract, calldata, value, gas_params)?;
// Roll back the sequence, we don't really want to invoke anything.
self.set_sequence(msg.sequence);
Ok(msg)
}
}
/// Wrapper for MessageFactory which generates signed messages
///
/// It assumes the sender is an `f1` type address, it won't work with `f410` addresses.
/// For those one must use the Ethereum API, with a suitable client library such as [ethers].
pub struct SignedMessageFactory {
inner: MessageFactory,
sk: SecretKey,
chain_id: ChainID,
}
impl SignedMessageFactory {
/// Create a factor from a secret key and its corresponding address, which could be a delegated one.
pub fn new(sk: SecretKey, addr: Address, sequence: u64, chain_id: ChainID) -> Self {
Self {
inner: MessageFactory::new(addr, sequence),
sk,
chain_id,
}
}
/// Treat the secret key as an f1 type account.
pub fn new_secp256k1(sk: SecretKey, sequence: u64, chain_id: ChainID) -> Self {
let pk = sk.public_key();
let addr = Address::new_secp256k1(&pk.serialize()).expect("public key is 65 bytes");
Self::new(sk, addr, sequence, chain_id)
}
/// Convenience method to read the secret key from a file, expected to be in Base64 format.
pub fn read_secret_key(sk: &Path) -> anyhow::Result<SecretKey> {
let b64 = fs::read_to_string(sk).context("failed to read secret key")?;
let bz: Vec<u8> = B64_ENGINE
.decode(b64)
.context("failed to parse base64 string")?;
let sk = SecretKey::try_from(bz)?;
Ok(sk)
}
/// Convenience method to serialize a [`ChainMessage`] for inclusion in a Tendermint transaction.
pub fn serialize(message: &ChainMessage) -> anyhow::Result<Vec<u8>> {
Ok(fvm_ipld_encoding::to_vec(message)?)
}
/// Actor address.
pub fn address(&self) -> &Address {
self.inner.address()
}
/// Transfer tokens to another account.
pub fn transfer(
&mut self,
to: Address,
value: TokenAmount,
gas_params: GasParams,
) -> anyhow::Result<ChainMessage> {
self.transaction(to, METHOD_SEND, Default::default(), value, gas_params)
}
/// Send a message to an actor.
pub fn transaction(
&mut self,
to: Address,
method_num: MethodNum,
params: RawBytes,
value: TokenAmount,
gas_params: GasParams,
) -> anyhow::Result<ChainMessage> {
let message = self
.inner
.transaction(to, method_num, params, value, gas_params);
let signed = SignedMessage::new_secp256k1(message, &self.sk, &self.chain_id)?;
let chain = ChainMessage::Signed(signed);
Ok(chain)
}
/// Send a validator message to the node
pub fn create_chain_message<T, F: Fn(SignedMessage) -> T>(
&mut self,
to: Address,
calldata: Bytes,
value: TokenAmount,
gas_params: GasParams,
f: F,
) -> anyhow::Result<T> {
let params = RawBytes::serialize(BytesSer(&calldata))?;
let method_num = evm::Method::InvokeContract as u64;
let message = self
.inner
.transaction(to, method_num, params, value, gas_params);
let signed = SignedMessage::new_secp256k1(message, &self.sk, &self.chain_id)?;
Ok(f(signed))
}
/// Deploy a FEVM contract.
pub fn fevm_create(
&mut self,
contract: Bytes,
constructor_args: Bytes,
value: TokenAmount,
gas_params: GasParams,
) -> anyhow::Result<ChainMessage> {
let initcode = [contract.to_vec(), constructor_args.to_vec()].concat();
let initcode = RawBytes::serialize(BytesSer(&initcode))?;
let message = self.transaction(
eam::EAM_ACTOR_ADDR,
eam::Method::CreateExternal as u64,
initcode,
value,
gas_params,
)?;
Ok(message)
}
/// Invoke a method on a FEVM contract.
pub fn fevm_invoke(
&mut self,
contract: Address,
calldata: Bytes,
value: TokenAmount,
gas_params: GasParams,
) -> anyhow::Result<ChainMessage> {
let calldata = RawBytes::serialize(BytesSer(&calldata))?;
let message = self.transaction(
contract,
evm::Method::InvokeContract as u64,
calldata,
value,
gas_params,
)?;
Ok(message)
}
/// Create a message for a read-only operation.
pub fn fevm_call(
&mut self,
contract: Address,
calldata: Bytes,
value: TokenAmount,
gas_params: GasParams,
) -> anyhow::Result<Message> {
let msg = self.fevm_invoke(contract, calldata, value, gas_params)?;
let msg = if let ChainMessage::Signed(signed) = msg {
signed.into_message()
} else {
panic!("unexpected message type: {msg:?}");
};
// Roll back the sequence, we don't really want to invoke anything.
self.inner.set_sequence(msg.sequence);
Ok(msg)
}
}
#[derive(Clone, Debug)]
pub struct GasParams {
/// Maximum amount of gas that can be charged.
pub gas_limit: u64,
/// Price of gas.
///
/// Any discrepancy between this and the base fee is paid for
/// by the validator who puts the transaction into the block.
pub gas_fee_cap: TokenAmount,
/// Gas premium.
pub gas_premium: TokenAmount,
}