forked from akure/dao-dao-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
actions.ts
83 lines (75 loc) · 2.52 KB
/
actions.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
import {
ActionContextType,
ActionOptions,
CosmosMsgForEmpty,
LoadedActions,
PartialCategorizedActionKeyAndData,
} from '@dao-dao/types'
import { transformBech32Address } from './conversion'
import { getAccountAddress } from './dao'
// Convert action data to a Cosmos message given all loaded actions.
export const convertActionsToMessages = (
loadedActions: LoadedActions,
actions: PartialCategorizedActionKeyAndData[],
{
// Whether or not to throw the error if a transform fails. If false, the
// error will be logged to the console, and the message will be skipped.
throwErrors = true,
}: {
throwErrors?: boolean
} = {}
): CosmosMsgForEmpty[] =>
actions
.map(({ categoryKey, actionKey, data }) => {
// If no category or action, skip it.
if (!categoryKey && !actionKey) {
return
}
// If no action or data, throw error because this is an unselected action.
if (!actionKey || !data) {
if (throwErrors) {
throw new Error('No action selected.')
}
return
}
try {
const loadedAction = loadedActions[actionKey]
if (!loadedAction) {
return
}
// If action not loaded or errored, throw error.
if (!loadedAction.defaults) {
throw new Error(`Action not loaded: ${loadedAction.action.label}.`)
} else if (loadedAction.defaults instanceof Error) {
throw loadedAction.defaults
}
return loadedAction.transform(data)
} catch (err) {
if (throwErrors) {
throw err
}
console.error(err)
}
})
// Filter out undefined messages.
.filter(Boolean) as CosmosMsgForEmpty[]
// Get the address for the given action options for the given chain. If a DAO,
// this is the address of the native address on the same chain or the polytone
// proxy on that chain. For a wallet, this is the transformed bech32 address.
export const getChainAddressForActionOptions = (
{ context, chain, address }: ActionOptions,
chainId: string
): string | undefined =>
// If on same chain, return address.
chain.chain_id === chainId
? address
: // If on different chain, return DAO's polytone proxy address.
context.type === ActionContextType.Dao
? getAccountAddress({
accounts: context.info.accounts,
chainId,
})
: // If on different chain, return wallet's transformed bech32 address.
context.type === ActionContextType.Wallet
? transformBech32Address(address, chainId)
: undefined