forked from SO4-Markets/contracts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
312 lines (266 loc) · 9.72 KB
/
Copy pathlib.rs
File metadata and controls
312 lines (266 loc) · 9.72 KB
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
//! Testnet faucet for SO4.market mintable test tokens.
//!
//! Deploy this contract first, then initialize `test_token` instances with this
//! faucet address as owner. Users claim configured amounts with one call.
#![no_std]
#![allow(deprecated)]
use soroban_sdk::{
contract, contractclient, contracterror, contractimpl, contracttype, panic_with_error,
symbol_short, Address, BytesN, Env, Vec,
};
/// `network_id` (SHA-256 of the network passphrase) for the Stellar public
/// network. Test faucets must never be initialized here (issue #400).
const MAINNET_NETWORK_ID: [u8; 32] = [
0x7a, 0xc3, 0x39, 0x97, 0x54, 0x4e, 0x31, 0x75, 0xd2, 0x66, 0xbd, 0x02, 0x24, 0x39, 0xb2, 0x2c,
0xdb, 0x16, 0x50, 0x8c, 0x01, 0x16, 0x3f, 0x26, 0xe5, 0xcb, 0x2a, 0x3e, 0x10, 0x45, 0xa9, 0x79,
];
#[allow(dead_code)]
#[contractclient(name = "TestTokenClient")]
trait ITestToken {
fn mint(env: Env, caller: Address, account: Address, amount: i128);
}
#[contracterror]
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[repr(u32)]
pub enum Error {
AlreadyInitialized = 1,
NotInitialized = 2,
Unauthorized = 3,
TokenNotEnabled = 4,
InvalidAmount = 5,
ClaimTooSoon = 6,
MainnetNotAllowed = 7,
}
#[contracttype]
enum InstanceKey {
Admin,
CooldownLedgers,
}
#[contracttype]
enum DataKey {
ClaimAmount(Address),
LastClaim(Address, Address),
}
#[contract]
pub struct TestFaucet;
#[contractimpl]
impl TestFaucet {
pub fn initialize(env: Env, admin: Address, cooldown_ledgers: u32) {
require_not_mainnet(&env);
if env.storage().instance().has(&InstanceKey::Admin) {
panic_with_error!(&env, Error::AlreadyInitialized);
}
env.storage().instance().set(&InstanceKey::Admin, &admin);
env.storage()
.instance()
.set(&InstanceKey::CooldownLedgers, &cooldown_ledgers);
}
pub fn admin(env: Env) -> Address {
get_admin(&env)
}
pub fn cooldown_ledgers(env: Env) -> u32 {
env.storage()
.instance()
.get(&InstanceKey::CooldownLedgers)
.unwrap_or_else(|| panic_with_error!(&env, Error::NotInitialized))
}
pub fn set_cooldown(env: Env, caller: Address, cooldown_ledgers: u32) {
require_admin(&env, &caller);
env.storage()
.instance()
.set(&InstanceKey::CooldownLedgers, &cooldown_ledgers);
env.events()
.publish((symbol_short!("cooldown"),), cooldown_ledgers);
}
pub fn set_token(env: Env, caller: Address, token: Address, claim_amount: i128) {
require_admin(&env, &caller);
if claim_amount <= 0 {
panic_with_error!(&env, Error::InvalidAmount);
}
env.storage()
.persistent()
.set(&DataKey::ClaimAmount(token.clone()), &claim_amount);
env.events()
.publish((symbol_short!("token"),), (token, claim_amount));
}
pub fn remove_token(env: Env, caller: Address, token: Address) {
require_admin(&env, &caller);
env.storage()
.persistent()
.remove(&DataKey::ClaimAmount(token.clone()));
env.events().publish((symbol_short!("rm_token"),), token);
}
pub fn claim_amount(env: Env, token: Address) -> i128 {
env.storage()
.persistent()
.get(&DataKey::ClaimAmount(token))
.unwrap_or(0)
}
pub fn last_claim_ledger(env: Env, account: Address, token: Address) -> u32 {
env.storage()
.persistent()
.get(&DataKey::LastClaim(account, token))
.unwrap_or(0)
}
pub fn claim(env: Env, account: Address, token: Address) -> i128 {
account.require_auth();
do_claim(&env, &account, token)
}
/// Claim multiple tokens in a single transaction.
///
/// Authorizes `account` once for the whole call rather than once per token
/// (issue #399) — looping `Self::claim` per token previously called
/// `account.require_auth()` once per iteration within the same invocation,
/// which hit a Soroban auth-reuse bug and failed for real signed transactions.
pub fn claim_many(env: Env, account: Address, tokens: Vec<Address>) -> Vec<i128> {
account.require_auth();
let mut amounts = Vec::new(&env);
for token in tokens.iter() {
amounts.push_back(do_claim(&env, &account, token));
}
amounts
}
}
fn do_claim(env: &Env, account: &Address, token: Address) -> i128 {
let amount = TestFaucet::claim_amount(env.clone(), token.clone());
if amount <= 0 {
panic_with_error!(env, Error::TokenNotEnabled);
}
enforce_cooldown(env, account, &token);
let faucet = env.current_contract_address();
TestTokenClient::new(env, &token).mint(&faucet, account, &amount);
env.storage().persistent().set(
&DataKey::LastClaim(account.clone(), token.clone()),
&env.ledger().sequence(),
);
env.events()
.publish((symbol_short!("claim"),), (account.clone(), token, amount));
amount
}
fn require_not_mainnet(env: &Env) {
if env.ledger().network_id() == BytesN::from_array(env, &MAINNET_NETWORK_ID) {
panic_with_error!(env, Error::MainnetNotAllowed);
}
}
fn get_admin(env: &Env) -> Address {
env.storage()
.instance()
.get(&InstanceKey::Admin)
.unwrap_or_else(|| panic_with_error!(env, Error::NotInitialized))
}
fn require_admin(env: &Env, caller: &Address) {
caller.require_auth();
if caller != &get_admin(env) {
panic_with_error!(env, Error::Unauthorized);
}
}
fn enforce_cooldown(env: &Env, account: &Address, token: &Address) {
let cooldown: u32 = env
.storage()
.instance()
.get(&InstanceKey::CooldownLedgers)
.unwrap_or_else(|| panic_with_error!(env, Error::NotInitialized));
if cooldown == 0 {
return;
}
let last: u32 = env
.storage()
.persistent()
.get(&DataKey::LastClaim(account.clone(), token.clone()))
.unwrap_or(0);
if last != 0 && env.ledger().sequence() < last.saturating_add(cooldown) {
panic_with_error!(env, Error::ClaimTooSoon);
}
}
#[cfg(test)]
mod tests {
use super::*;
use soroban_sdk::{
testutils::{Address as _, Ledger},
String,
};
use test_token::{TestToken, TestTokenClient as TokenClient};
fn setup() -> (Env, Address, Address, TestFaucetClient<'static>) {
let env = Env::default();
env.mock_all_auths();
env.ledger().set_sequence_number(1);
let admin = Address::generate(&env);
let faucet_id = env.register(TestFaucet, ());
let faucet = TestFaucetClient::new(&env, &faucet_id);
faucet.initialize(&admin, &10);
let token_id = env.register(TestToken, ());
let token = TokenClient::new(&env, &token_id);
token.initialize(
&faucet_id,
&7,
&String::from_str(&env, "Test USD Coin"),
&String::from_str(&env, "TUSDC"),
);
faucet.set_token(&admin, &token_id, &100_0000000);
(env, admin, token_id, faucet)
}
#[test]
fn user_can_claim_enabled_token() {
let (env, _admin, token_id, faucet) = setup();
let user = Address::generate(&env);
let token = TokenClient::new(&env, &token_id);
assert_eq!(faucet.claim(&user, &token_id), 100_0000000);
assert_eq!(token.balance(&user), 100_0000000);
}
#[test]
fn cooldown_blocks_repeat_claim() {
let (env, _admin, token_id, faucet) = setup();
let user = Address::generate(&env);
faucet.claim(&user, &token_id);
assert!(faucet.try_claim(&user, &token_id).is_err());
env.ledger().set_sequence_number(11);
faucet.claim(&user, &token_id);
}
/// Issue #399: `claim_many` must authorize `account` once and mint every
/// configured token in a single call, matching what `claim` does per-token.
#[test]
fn claim_many_mints_every_configured_token() {
let (env, admin, token_a_id, faucet) = setup();
let user = Address::generate(&env);
let token_b_id = env.register(TestToken, ());
let token_b = TokenClient::new(&env, &token_b_id);
token_b.initialize(
&faucet.address,
&7,
&String::from_str(&env, "Test Wrapped Bitcoin"),
&String::from_str(&env, "TWBTC"),
);
faucet.set_token(&admin, &token_b_id, &50_0000000);
let amounts = faucet.claim_many(
&user,
&Vec::from_array(&env, [token_a_id.clone(), token_b_id.clone()]),
);
assert_eq!(amounts, Vec::from_array(&env, [100_0000000, 50_0000000]));
assert_eq!(TokenClient::new(&env, &token_a_id).balance(&user), 100_0000000);
assert_eq!(token_b.balance(&user), 50_0000000);
}
#[test]
#[should_panic]
fn admin_must_configure_token() {
let env = Env::default();
env.mock_all_auths();
let admin = Address::generate(&env);
let user = Address::generate(&env);
let faucet_id = env.register(TestFaucet, ());
let faucet = TestFaucetClient::new(&env, &faucet_id);
faucet.initialize(&admin, &0);
faucet.claim(&user, &Address::generate(&env));
}
/// Issue #400: initializing against the mainnet `network_id` must panic —
/// the faucet must never come up live on mainnet.
#[test]
#[should_panic]
fn initialize_rejects_mainnet_network_id() {
let env = Env::default();
env.mock_all_auths();
env.ledger().set_network_id(MAINNET_NETWORK_ID);
let admin = Address::generate(&env);
let faucet_id = env.register(TestFaucet, ());
TestFaucetClient::new(&env, &faucet_id).initialize(&admin, &10);
}
}