-
Notifications
You must be signed in to change notification settings - Fork 76
/
proposals.rs
515 lines (492 loc) · 18.1 KB
/
proposals.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
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
use std::collections::HashMap;
use std::convert::TryFrom;
use near_contract_standards::fungible_token::core_impl::ext_fungible_token;
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::json_types::{Base64VecU8, WrappedTimestamp, U64};
use near_sdk::{log, AccountId, Balance, PromiseOrValue};
use crate::policy::UserInfo;
use crate::types::{
upgrade_remote, upgrade_self, Action, Config, BASE_TOKEN, GAS_FOR_FT_TRANSFER, ONE_YOCTO_NEAR,
};
use crate::*;
/// Status of a proposal.
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize, Clone, PartialEq, Debug)]
#[serde(crate = "near_sdk::serde")]
pub enum ProposalStatus {
InProgress,
/// If quorum voted yes, this proposal is successfully approved.
Approved,
/// If quorum voted no, this proposal is rejected. Bond is returned.
Rejected,
/// If quorum voted to remove (e.g. spam), this proposal is rejected and bond is not returned.
/// Interfaces shouldn't show removed proposals.
Removed,
/// Expired after period of time.
Expired,
/// If proposal was moved to Hub or somewhere else.
Moved,
}
/// Function call arguments.
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize)]
#[cfg_attr(not(target_arch = "wasm32"), derive(Clone, Debug))]
#[serde(crate = "near_sdk::serde")]
pub struct ActionCall {
method_name: String,
args: Base64VecU8,
deposit: U128,
gas: U64,
}
/// Kinds of proposals, doing different action.
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize)]
#[cfg_attr(not(target_arch = "wasm32"), derive(Clone, Debug))]
#[serde(crate = "near_sdk::serde")]
pub enum ProposalKind {
/// Change the DAO config.
ChangeConfig { config: Config },
/// Change the full policy.
ChangePolicy { policy: VersionedPolicy },
/// Add member to given role in the policy. This is short cut to updating the whole policy.
AddMemberToRole {
member_id: ValidAccountId,
role: String,
},
/// Remove member to given role in the policy. This is short cut to updating the whole policy.
RemoveMemberFromRole {
member_id: ValidAccountId,
role: String,
},
/// Calls `receiver_id` with list of method names in a single promise.
/// Allows this contract to execute any arbitrary set of actions in other contracts.
FunctionCall {
receiver_id: ValidAccountId,
actions: Vec<ActionCall>,
},
/// Upgrade this contract with given hash from blob store.
UpgradeSelf { hash: Base58CryptoHash },
/// Upgrade another contract, by calling method with the code from given hash from blob store.
UpgradeRemote {
receiver_id: ValidAccountId,
method_name: String,
hash: Base58CryptoHash,
},
/// Transfers given amount of `token_id` from this DAO to `receiver_id`.
/// If `msg` is not None, calls `ft_transfer_call` with given `msg`. Fails if this base token.
/// For `ft_transfer` and `ft_transfer_call` `memo` is the `description` of the proposal.
Transfer {
/// Can be "" for $NEAR or a valid account id.
token_id: AccountId,
receiver_id: ValidAccountId,
amount: U128,
msg: Option<String>,
},
/// Sets staking contract. Can only be proposed if staking contract is not set yet.
SetStakingContract { staking_id: ValidAccountId },
/// Add new bounty.
AddBounty { bounty: Bounty },
/// Indicates that given bounty is done by given user.
BountyDone {
bounty_id: u64,
receiver_id: ValidAccountId,
},
/// Just a signaling vote, with no execution.
Vote,
}
impl ProposalKind {
/// Returns label of policy for given type of proposal.
pub fn to_policy_label(&self) -> &str {
match self {
ProposalKind::ChangeConfig { .. } => "config",
ProposalKind::ChangePolicy { .. } => "policy",
ProposalKind::AddMemberToRole { .. } => "add_member_to_role",
ProposalKind::RemoveMemberFromRole { .. } => "remove_member_from_role",
ProposalKind::FunctionCall { .. } => "call",
ProposalKind::UpgradeSelf { .. } => "upgrade_self",
ProposalKind::UpgradeRemote { .. } => "upgrade_remote",
ProposalKind::Transfer { .. } => "transfer",
ProposalKind::SetStakingContract { .. } => "set_vote_token",
ProposalKind::AddBounty { .. } => "add_bounty",
ProposalKind::BountyDone { .. } => "bounty_done",
ProposalKind::Vote => "vote",
}
}
}
/// Votes recorded in the proposal.
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize, Clone, Debug)]
#[serde(crate = "near_sdk::serde")]
pub enum Vote {
Approve = 0x0,
Reject = 0x1,
Remove = 0x2,
}
impl From<Action> for Vote {
fn from(action: Action) -> Self {
match action {
Action::VoteApprove => Vote::Approve,
Action::VoteReject => Vote::Reject,
Action::VoteRemove => Vote::Remove,
_ => unreachable!(),
}
}
}
/// Proposal that are sent to this DAO.
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize)]
#[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
#[serde(crate = "near_sdk::serde")]
pub struct Proposal {
/// Original proposer.
pub proposer: AccountId,
/// Description of this proposal.
pub description: String,
/// Kind of proposal with relevant information.
pub kind: ProposalKind,
/// Current status of the proposal.
pub status: ProposalStatus,
/// Count of votes per role per decision: yes / no / spam.
pub vote_counts: HashMap<String, [Balance; 3]>,
/// Map of who voted and how.
pub votes: HashMap<AccountId, Vote>,
/// Submission time (for voting period).
pub submission_time: WrappedTimestamp,
}
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize)]
#[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
#[serde(crate = "near_sdk::serde")]
pub enum VersionedProposal {
Default(Proposal),
}
impl From<VersionedProposal> for Proposal {
fn from(v: VersionedProposal) -> Self {
match v {
VersionedProposal::Default(p) => p,
}
}
}
impl Proposal {
/// Adds vote of the given user with given `amount` of weight. If user already voted, fails.
pub fn update_votes(
&mut self,
account_id: &AccountId,
roles: &[String],
vote: Vote,
policy: &Policy,
user_weight: Balance,
) {
for role in roles {
let amount = if policy.is_token_weighted(role, &self.kind.to_policy_label().to_string())
{
user_weight
} else {
1
};
self.vote_counts.entry(role.clone()).or_insert([0u128; 3])[vote.clone() as usize] +=
amount;
}
assert!(
self.votes.insert(account_id.clone(), vote).is_none(),
"ERR_ALREADY_VOTED"
);
}
}
#[derive(Serialize, Deserialize)]
#[serde(crate = "near_sdk::serde")]
pub struct ProposalInput {
/// Description of this proposal.
pub description: String,
/// Kind of proposal with relevant information.
pub kind: ProposalKind,
}
impl From<ProposalInput> for Proposal {
fn from(input: ProposalInput) -> Self {
Self {
proposer: env::predecessor_account_id(),
description: input.description,
kind: input.kind,
status: ProposalStatus::InProgress,
vote_counts: HashMap::default(),
votes: HashMap::default(),
submission_time: WrappedTimestamp::from(env::block_timestamp()),
}
}
}
impl Contract {
/// Execute payout of given token to given user.
pub(crate) fn internal_payout(
&mut self,
token_id: &AccountId,
receiver_id: &AccountId,
amount: Balance,
memo: String,
msg: Option<String>,
) -> PromiseOrValue<()> {
if token_id == BASE_TOKEN {
Promise::new(receiver_id.clone()).transfer(amount).into()
} else {
if let Some(msg) = msg {
ext_fungible_token::ft_transfer_call(
receiver_id.clone(),
U128(amount),
Some(memo),
msg,
&token_id,
ONE_YOCTO_NEAR,
GAS_FOR_FT_TRANSFER,
)
.into()
} else {
ext_fungible_token::ft_transfer(
receiver_id.clone(),
U128(amount),
Some(memo),
&token_id,
ONE_YOCTO_NEAR,
GAS_FOR_FT_TRANSFER,
)
.into()
}
}
}
/// Executes given proposal and updates the contract's state.
fn internal_execute_proposal(
&mut self,
policy: &Policy,
proposal: &Proposal,
) -> PromiseOrValue<()> {
// Return the proposal bond.
Promise::new(proposal.proposer.clone()).transfer(policy.proposal_bond.0);
match &proposal.kind {
ProposalKind::ChangeConfig { config } => {
self.config.set(config);
PromiseOrValue::Value(())
}
ProposalKind::ChangePolicy { policy } => {
self.policy.set(policy);
PromiseOrValue::Value(())
}
ProposalKind::AddMemberToRole { member_id, role } => {
let mut new_policy = policy.clone();
new_policy.add_member_to_role(role, &member_id.clone().into());
self.policy.set(&VersionedPolicy::Current(new_policy));
PromiseOrValue::Value(())
}
ProposalKind::RemoveMemberFromRole { member_id, role } => {
let mut new_policy = policy.clone();
new_policy.remove_member_from_role(role, &member_id.clone().into());
self.policy.set(&VersionedPolicy::Current(new_policy));
PromiseOrValue::Value(())
}
ProposalKind::FunctionCall {
receiver_id,
actions,
} => {
let mut promise = Promise::new(receiver_id.clone().into());
for action in actions {
promise = promise.function_call(
action.method_name.clone().into_bytes(),
action.args.clone().into(),
action.deposit.0,
action.gas.0,
)
}
promise.into()
}
ProposalKind::UpgradeSelf { hash } => {
upgrade_self(&CryptoHash::from(hash.clone()));
PromiseOrValue::Value(())
}
ProposalKind::UpgradeRemote {
receiver_id,
method_name,
hash,
} => {
upgrade_remote(
&receiver_id.clone().into(),
method_name,
&CryptoHash::from(hash.clone()),
);
PromiseOrValue::Value(())
}
ProposalKind::Transfer {
token_id,
receiver_id,
amount,
msg,
} => self.internal_payout(
token_id,
&receiver_id.clone().into(),
amount.0,
proposal.description.clone(),
msg.clone(),
),
ProposalKind::SetStakingContract { staking_id } => {
assert!(self.staking_id.is_none(), "ERR_INVALID_STAKING_CHANGE");
self.staking_id = Some(staking_id.clone().into());
PromiseOrValue::Value(())
}
ProposalKind::AddBounty { bounty } => {
self.internal_add_bounty(bounty);
PromiseOrValue::Value(())
}
ProposalKind::BountyDone {
bounty_id,
receiver_id,
} => self.internal_execute_bounty_payout(*bounty_id, &receiver_id.clone().into(), true),
ProposalKind::Vote => PromiseOrValue::Value(()),
}
}
/// Process rejecting proposal.
fn internal_reject_proposal(
&mut self,
policy: &Policy,
proposal: &Proposal,
return_bond: bool,
) -> PromiseOrValue<()> {
if return_bond {
// Return bond to the proposer.
Promise::new(proposal.proposer.clone()).transfer(policy.proposal_bond.0);
}
match &proposal.kind {
ProposalKind::BountyDone {
bounty_id,
receiver_id,
} => {
self.internal_execute_bounty_payout(*bounty_id, &receiver_id.clone().into(), false)
}
_ => PromiseOrValue::Value(()),
}
}
pub(crate) fn internal_user_info(&self) -> UserInfo {
let account_id = env::predecessor_account_id();
UserInfo {
amount: self.get_user_weight(&account_id),
account_id,
}
}
}
#[near_bindgen]
impl Contract {
/// Add proposal to this DAO.
#[payable]
pub fn add_proposal(&mut self, proposal: ProposalInput) -> u64 {
// 0. validate bond attached.
// TODO: consider bond in the token of this DAO.
let policy = self.policy.get().unwrap().to_policy();
assert!(
env::attached_deposit() >= policy.proposal_bond.0,
"ERR_MIN_BOND"
);
// 1. Validate proposal.
match &proposal.kind {
ProposalKind::ChangePolicy { policy } => match policy {
VersionedPolicy::Current(_) => {}
_ => panic!("ERR_INVALID_POLICY"),
},
ProposalKind::Transfer { token_id, msg, .. } => {
assert!(
!(token_id == BASE_TOKEN) || msg.is_none(),
"ERR_BASE_TOKEN_NO_MSG"
);
if token_id != BASE_TOKEN {
assert!(
ValidAccountId::try_from(token_id.clone()).is_ok(),
"ERR_TOKEN_ID_INVALID"
);
}
}
ProposalKind::SetStakingContract { .. } => assert!(
self.staking_id.is_none(),
"ERR_STAKING_CONTRACT_CANT_CHANGE"
),
// TODO: add more verifications.
_ => {}
};
// 2. Check permission of caller to add this type of proposal.
assert!(
policy
.can_execute_action(
self.internal_user_info(),
&proposal.kind,
&Action::AddProposal
)
.1,
"ERR_PERMISSION_DENIED"
);
// 3. Actually add proposal to the current list of proposals.
let id = self.last_proposal_id;
self.proposals
.insert(&id, &VersionedProposal::Default(proposal.into()));
self.last_proposal_id += 1;
id
}
/// Act on given proposal by id, if permissions allow.
/// Memo is logged but not stored in the state. Can be used to leave notes or explain the action.
pub fn act_proposal(&mut self, id: u64, action: Action, memo: Option<String>) {
let mut proposal: Proposal = self.proposals.get(&id).expect("ERR_NO_PROPOSAL").into();
let policy = self.policy.get().unwrap().to_policy();
// Check permissions for the given action.
let (roles, allowed) =
policy.can_execute_action(self.internal_user_info(), &proposal.kind, &action);
assert!(allowed, "ERR_PERMISSION_DENIED");
let sender_id = env::predecessor_account_id();
// Update proposal given action. Returns true if should be updated in storage.
let update = match action {
Action::AddProposal => env::panic(b"ERR_WRONG_ACTION"),
Action::RemoveProposal => {
self.proposals.remove(&id);
false
}
Action::VoteApprove | Action::VoteReject | Action::VoteRemove => {
assert_eq!(
proposal.status,
ProposalStatus::InProgress,
"ERR_PROPOSAL_NOT_IN_PROGRESS"
);
proposal.update_votes(
&sender_id,
&roles,
Vote::from(action),
&policy,
self.get_user_weight(&sender_id),
);
// Updates proposal status with new votes using the policy.
proposal.status =
policy.proposal_status(&proposal, roles, self.total_delegation_amount);
if proposal.status == ProposalStatus::Approved {
self.internal_execute_proposal(&policy, &proposal);
true
} else if proposal.status == ProposalStatus::Removed {
self.internal_reject_proposal(&policy, &proposal, false);
self.proposals.remove(&id);
false
} else if proposal.status == ProposalStatus::Rejected {
self.internal_reject_proposal(&policy, &proposal, true);
true
} else {
// Still in progress or expired.
true
}
}
Action::Finalize => {
proposal.status = policy.proposal_status(
&proposal,
policy.roles.iter().map(|r| r.name.clone()).collect(),
self.total_delegation_amount,
);
assert_eq!(
proposal.status,
ProposalStatus::Expired,
"ERR_PROPOSAL_NOT_EXPIRED"
);
self.internal_reject_proposal(&policy, &proposal, true);
true
}
Action::MoveToHub => false,
};
if update {
self.proposals
.insert(&id, &VersionedProposal::Default(proposal));
}
if let Some(memo) = memo {
log!("Memo: {}", memo);
}
}
}