forked from daostack/alchemy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharcActions.ts
More file actions
217 lines (198 loc) · 8.81 KB
/
arcActions.ts
File metadata and controls
217 lines (198 loc) · 8.81 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
import { Address, DAO, IProposalCreateOptions, IProposalOutcome, ITransactionState,
ITransactionUpdate, ReputationFromTokenScheme, Scheme } from "@daostack/client";
import { IAsyncAction } from "actions/async";
import { getArc } from "arc";
import { toWei } from "lib/util";
import { IRedemptionState } from "lib/proposalHelpers";
import { IRootState } from "reducers/index";
import { NotificationStatus, showNotification } from "reducers/notifications";
import * as Redux from "redux";
import { ThunkAction } from "redux-thunk";
export type CreateProposalAction = IAsyncAction<"ARC_CREATE_PROPOSAL", { avatarAddress: string }, any>;
/** use like this (unfortunately you need the @ts-ignore)
* // @ts-ignore
* transaction.send().observer(...operationNotifierObserver(dispatch, "Whatever"))
*/
export const operationNotifierObserver = (dispatch: Redux.Dispatch<any, any>, txDescription = ""): [(update: ITransactionUpdate<any>) => void, (err: Error) => void] => {
return [
(update: ITransactionUpdate<any>) => {
let msg: string;
if (update.state === ITransactionState.Sent) {
msg = `${txDescription} transaction sent! Please wait for it to be processed`;
dispatch(showNotification(NotificationStatus.Success, msg));
} else if (update.confirmations === 0) {
msg = `${txDescription} transaction processed successfully`;
dispatch(showNotification(NotificationStatus.Success, msg));
} else if (update.confirmations === 3) {
msg = `${txDescription} transaction confirmed`;
dispatch(showNotification(NotificationStatus.Success, msg));
}
},
(err: Error) => {
const msg = `${txDescription}: transaction failed :-( - ${err.message}`;
// eslint-disable-next-line no-console
console.warn(msg);
dispatch(showNotification(NotificationStatus.Failure, msg));
},
];
};
export function saveSignalDescription(signalDescription: any): ThunkAction<any, IRootState, null> {
return async (_getState: () => IRootState) => {
const arc = getArc();
let ipfsDataToSave: object = {};
if (signalDescription.key && signalDescription.value !== undefined) {
if (!arc.ipfsProvider) {
throw Error("No ipfsProvider set on Arc instance - cannot save data on IPFS");
}
ipfsDataToSave = {
key: signalDescription.key,
value: signalDescription.value,
};
}
return await arc.ipfs.addAndPinString(Buffer.from(JSON.stringify(ipfsDataToSave)));
};
}
export function createProposal(proposalOptions: IProposalCreateOptions): ThunkAction<any, IRootState, null> {
return async (dispatch: Redux.Dispatch<any, any>, _getState: () => IRootState) => {
try {
const arc = getArc();
const dao = new DAO(proposalOptions.dao, arc);
const observer = operationNotifierObserver(dispatch, "Create proposal");
await dao.createProposal(proposalOptions).subscribe(...observer);
} catch (err) {
// eslint-disable-next-line no-console
console.error(err);
throw err;
}
};
}
export function executeProposal(avatarAddress: string, proposalId: string, _accountAddress: string) {
return async (dispatch: Redux.Dispatch<any, any>) => {
const arc = getArc();
const observer = operationNotifierObserver(dispatch, "Execute proposal");
const proposalObj = await arc.dao(avatarAddress).proposal(proposalId);
// Call claimRewards to both execute the proposal and redeem the ContributionReward rewards,
// pass in null to not redeem any GenesisProtocol rewards
const originalErrorHandler = observer[1];
observer[1] = async (_error: any): Promise<any> => {
observer[1] = originalErrorHandler;
return await proposalObj.execute().subscribe(...observer);
};
await proposalObj.claimRewards(null).subscribe(...observer);
};
}
export type VoteAction = IAsyncAction<"ARC_VOTE", {
avatarAddress: string;
proposalId: string;
reputation: number;
voteOption: IProposalOutcome;
voterAddress: string;
}, {
entities: any;
proposal: any;
voter: any;
}>;
export function voteOnProposal(daoAvatarAddress: string, proposalId: string, voteOption: IProposalOutcome) {
return async (dispatch: Redux.Dispatch<any, any>, _getState: () => IRootState) => {
const arc = getArc();
const proposalObj = await arc.dao(daoAvatarAddress).proposal(proposalId);
const observer = operationNotifierObserver(dispatch, "Vote");
await proposalObj.vote(voteOption).subscribe(...observer);
};
}
export type StakeAction = IAsyncAction<"ARC_STAKE", {
avatarAddress: string;
proposalId: string;
prediction: IProposalOutcome;
stakeAmount: number;
stakerAddress: string;
}, {
dao: any;
proposal: any;
}>;
export function stakeProposal(daoAvatarAddress: string, proposalId: string, prediction: number, stakeAmount: number) {
return async (dispatch: Redux.Dispatch<any, any>, ) => {
const arc = getArc();
const proposalObj = await arc.dao(daoAvatarAddress).proposal(proposalId);
const observer = operationNotifierObserver(dispatch, "Stake");
await proposalObj.stake(prediction, toWei(stakeAmount)).subscribe(...observer);
};
}
// Approve transfer of 100000 GENs from accountAddress to the GenesisProtocol contract for use in staking
export function approveStakingGens(spender: Address) {
return async (dispatch: Redux.Dispatch<any, any>, ) => {
const arc = getArc();
const observer = operationNotifierObserver(dispatch, "Approve GEN");
await arc.approveForStaking(spender, toWei(100000)).subscribe(...observer);
};
}
export type RedeemAction = IAsyncAction<"ARC_REDEEM", {
avatarAddress: string;
proposalId: string;
accountAddress: string;
}, {
currentAccount: any;
beneficiary: any;
dao: any;
proposal: any;
beneficiaryRedemptions: IRedemptionState;
currentAccountRedemptions: IRedemptionState;
}>;
export function redeemProposal(daoAvatarAddress: string, proposalId: string, accountAddress: string) {
return async (dispatch: Redux.Dispatch<any, any>) => {
const arc = getArc();
const proposalObj = await arc.dao(daoAvatarAddress).proposal(proposalId);
const observer = operationNotifierObserver(dispatch, "Reward");
await proposalObj.claimRewards(accountAddress).subscribe(...observer);
};
}
export function redeemReputationFromToken(scheme: Scheme, addressToRedeem: string, privateKey: string|undefined, redeemerAddress: Address|undefined, redemptionSucceededCallback: () => void) {
return async (dispatch: Redux.Dispatch<any, any>) => {
const arc = getArc();
// ensure that scheme.ReputationFromToken is set
await scheme.fetchStaticState();
if (privateKey) {
const reputationFromTokenScheme = scheme.ReputationFromToken as ReputationFromTokenScheme;
const agreementHash = await reputationFromTokenScheme.getAgreementHash();
const state = await reputationFromTokenScheme.scheme.fetchStaticState();
const contract = arc.getContract(state.address);
const block = await arc.web3.eth.getBlock("latest");
const gas = block.gasLimit - 100000;
const redeemMethod = contract.methods.redeem(addressToRedeem, agreementHash);
let gasPrice = await arc.web3.eth.getGasPrice();
gasPrice = gasPrice * 1.2;
const txToSign = {
gas,
gasPrice,
data: redeemMethod.encodeABI(),
to: state.address,
value: "0",
};
const gasEstimate = await arc.web3.eth.estimateGas(txToSign);
txToSign.gas = gasEstimate;
// if the gas cost is higher then the users balance, we lower it to fit
const userBalance = await arc.web3.eth.getBalance(redeemerAddress);
if (userBalance < gasEstimate * gasPrice) {
txToSign.gasPrice = Math.floor(userBalance/gasEstimate);
}
const signedTransaction = await arc.web3.eth.accounts.signTransaction(txToSign, privateKey);
dispatch(showNotification(NotificationStatus.Success, "Sending redeem transaction, please wait for it to be mined"));
// const txHash = await arc.web3.utils.sha3(signedTransaction.rawTransaction);
try {
await arc.web3.eth.sendSignedTransaction(signedTransaction.rawTransaction);
dispatch(showNotification(NotificationStatus.Success, "Transaction was succesful!"));
redemptionSucceededCallback();
} catch(err) {
dispatch(showNotification(NotificationStatus.Failure, `Transaction failed: ${err.message}`));
}
} else {
const observer = operationNotifierObserver(dispatch, "Redeem reputation");
const reputationFromTokenScheme = scheme.ReputationFromToken as ReputationFromTokenScheme;
// send the transaction and get notifications
if (reputationFromTokenScheme) {
const agreementHash = await reputationFromTokenScheme.getAgreementHash();
reputationFromTokenScheme.redeem(addressToRedeem, agreementHash).subscribe(observer[0], observer[1], redemptionSucceededCallback);
}
}
};
}