forked from DA0-DA0/dao-dao-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathactions.ts
85 lines (77 loc) · 2.4 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
84
85
import {
ActionContextType,
ActionKeyAndData,
ActionOptions,
CosmosMsgForEmpty,
LoadedActions,
} from '@dao-dao/types'
import { getAccountAddress } from './dao'
// Convert action data to a Cosmos message given all loaded actions.
export const convertActionsToMessages = (
loadedActions: LoadedActions,
actions: ActionKeyAndData[],
{
// 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(({ actionKey, data }) => {
// If no action, skip it.
if (!actionKey) {
return
}
// If no data, throw error because this is invalidly selected.
if (!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 address registered in the
* wallet's profile, if any.
*/
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 chain profile address if set.
context.type === ActionContextType.Wallet
? context.profile?.chains[chainId]?.address
: undefined