-
Notifications
You must be signed in to change notification settings - Fork 42
/
saga.ts
218 lines (179 loc) · 6.55 KB
/
saga.ts
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
import { Signer } from '@oasisprotocol/client/dist/signature'
import { PayloadAction } from '@reduxjs/toolkit'
import { hex2uint, isValidAddress, uint2bigintString } from 'app/lib/helpers'
import { LedgerSigner } from 'app/lib/ledger'
import { OasisTransaction, signerFromPrivateKey, TW } from 'app/lib/transaction'
import { call, put, race, select, take, takeEvery } from 'typed-redux-saga'
import { ErrorPayload, WalletError, WalletErrors } from 'types/errors'
import { transactionActions } from '.'
import { sign } from '../ledger/saga'
import { getOasisNic } from '../network/saga'
import { selectChainContext } from '../network/selectors'
import { selectActiveWallet } from '../wallet/selectors'
import { Wallet, WalletType } from '../wallet/types'
import { TransactionPayload, TransactionStep } from './types'
export function* transactionSaga() {
yield* takeEvery(transactionActions.sendTransaction, doTransaction)
yield* takeEvery(transactionActions.addEscrow, doTransaction)
yield* takeEvery(transactionActions.reclaimEscrow, doTransaction)
}
function* setStep(step: TransactionStep) {
yield* put(transactionActions.setStep(step))
}
/**
* When we are previewing a transaction, await either a confirm action,
* or an abort action.
*/
function* expectConfirmation() {
const { confirm } = yield* race({
confirm: take(transactionActions.confirmTransaction),
abort: take(transactionActions.abortTransaction),
})
if (confirm) {
return true
} else {
return false
}
}
/**
* Yields the appropriate signer for the currently active wallet
*/
function* getSigner() {
const wallet = yield* select(selectActiveWallet)
if (!wallet) {
throw new WalletError(WalletErrors.NoOpenWallet, 'Cannot send transaction without an active wallet')
}
const privateKey = wallet.privateKey!
let signer: Signer | LedgerSigner
if (wallet.type === WalletType.PrivateKey || wallet.type === WalletType.Mnemonic) {
const bytes = hex2uint(privateKey!)
signer = yield* call(signerFromPrivateKey, bytes)
} else if (wallet.type === WalletType.Ledger) {
signer = new LedgerSigner(wallet)
} else {
throw new WalletError(WalletErrors.InvalidPrivateKey, 'Invalid private key')
}
return signer
}
function* prepareTransfer(signer: Signer, amount: bigint, to: string) {
const nic = yield* call(getOasisNic)
yield* call(assertWalletIsOpen)
yield* call(assertValidAddress, to)
yield* call(assertSufficientBalance, amount)
yield* call(assertRecipientNotSelf, to)
return yield* call(OasisTransaction.buildTransfer, nic, signer as Signer, to, amount)
}
function* prepareAddEscrow(signer: Signer, amount: bigint, validator: string) {
const nic = yield* call(getOasisNic)
yield* call(assertWalletIsOpen)
yield* call(assertValidAddress, validator)
yield* call(assertSufficientBalance, amount)
return yield* call(OasisTransaction.buildAddEscrow, nic, signer as Signer, validator, amount)
}
function* prepareReclaimEscrow(signer: Signer, shares: bigint, validator: string) {
const nic = yield* call(getOasisNic)
yield* call(assertWalletIsOpen)
yield* call(assertValidAddress, validator)
return yield* call(OasisTransaction.buildReclaimEscrow, nic, signer as Signer, validator, shares)
}
/**
* Generate transaction, sign, push to node
*
* Build the transaction (and validate it client-side)
* Wait for either confirm or cancel, exit saga on cancel
*/
export function* doTransaction(action: PayloadAction<TransactionPayload>) {
const wallet = yield* select(selectActiveWallet)
const nic = yield* call(getOasisNic)
const chainContext = yield* select(selectChainContext)
try {
yield* setStep(TransactionStep.Building)
yield* call(assertWalletIsOpen)
const activeWallet = wallet as Wallet
const signer = yield* getSigner()
let tw: TW<any>
switch (action.payload.type) {
case 'transfer':
tw = yield* call(
prepareTransfer,
signer as Signer,
BigInt(action.payload.amount * 10 ** 9),
action.payload.to,
)
break
case 'addEscrow':
tw = yield* call(
prepareAddEscrow,
signer as Signer,
BigInt(action.payload.amount * 10 ** 9),
action.payload.validator,
)
break
case 'reclaimEscrow':
tw = yield* call(
prepareReclaimEscrow,
signer as Signer,
BigInt(Math.floor(action.payload.shares * 10 ** 9)),
action.payload.validator,
)
break
default:
throw new Error('Unsupported transaction type')
}
yield* put(
transactionActions.updateTransactionPreview({
transaction: action.payload,
fee: uint2bigintString(tw.transaction.fee?.amount!),
gas: BigInt(tw.transaction.fee?.gas!).toString(),
}),
)
yield* setStep(TransactionStep.Preview)
const confirmed = yield* expectConfirmation()
if (!confirmed) {
yield* put(transactionActions.clearTransaction())
return
}
yield* setStep(TransactionStep.Signing)
if (activeWallet.type === WalletType.Ledger) {
yield* call(sign, signer as LedgerSigner, tw)
} else {
yield* call(OasisTransaction.sign, chainContext, signer as Signer, tw)
}
yield* setStep(TransactionStep.Submitting)
yield* call(OasisTransaction.submit, nic, tw)
// Notify that the transaction was a success
yield* put(transactionActions.transactionSent(action.payload))
} catch (e) {
let payload: ErrorPayload
if (e instanceof WalletError) {
payload = { code: e.type, message: e.message }
} else {
payload = { code: WalletErrors.UnknownError, message: e.message }
}
yield* put(transactionActions.transactionFailed(payload))
}
}
function* assertWalletIsOpen() {
const wallet = yield* select(selectActiveWallet)
if (!wallet) {
throw new WalletError(WalletErrors.NoOpenWallet, 'Cannot send transaction without an active wallet')
}
}
function assertValidAddress(address: string) {
if (!isValidAddress(address)) {
throw new WalletError(WalletErrors.InvalidAddress, 'Invalid address')
}
}
function* assertSufficientBalance(amount: bigint) {
const wallet = yield* select(selectActiveWallet)
const balance = BigInt(wallet!.balance.available)
if (amount > balance) {
throw new WalletError(WalletErrors.InsufficientBalance, 'Insufficient balance')
}
}
function* assertRecipientNotSelf(recipient: string) {
const wallet = yield* select(selectActiveWallet)
if (wallet!.address === recipient) {
throw new WalletError(WalletErrors.CannotSendToSelf, 'Cannot send to your own account')
}
}