forked from DA0-DA0/dao-dao-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontracts.ts
184 lines (163 loc) · 5.17 KB
/
contracts.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
import { ExecuteResult, SigningCosmWasmClient } from '@cosmjs/cosmwasm-stargate'
import { fromBech32, toBase64, toBech32 } from '@cosmjs/encoding'
import { Coin, DeliverTxResponse, isDeliverTxFailure } from '@cosmjs/stargate'
import { parseRawLog } from '@cosmjs/stargate/build/logs'
import { toUtf8 } from 'secretjs'
import { ContractVersion } from '@dao-dao/types'
import {
MsgExecuteContract,
MsgInstantiateContract,
} from '@dao-dao/types/protobuf/codegen/cosmwasm/wasm/v1/tx'
import { getChainForChainId } from './chain'
import { findEventsAttributeValue } from './client'
import { CHAIN_GAS_MULTIPLIER } from './constants'
import { SecretSigningCosmWasmClient } from './secret'
const CONTRACT_VERSIONS = Object.values(ContractVersion)
// If version is defined, returns it. Otherwise, returns `undefined`.
// Essentially just filters version by its presence in the `ContractVersion`
// enum.
export const parseContractVersion = (
version: string
): ContractVersion | undefined => CONTRACT_VERSIONS.find((v) => v === version)
export const indexToProposalModulePrefix = (index: number) => {
index += 1
let prefix = ''
while (index > 0) {
const letterIndex = (index - 1) % 26
// capital A = 65, Z = 90
prefix = String.fromCharCode('A'.charCodeAt(0) + letterIndex) + prefix
index = ((index - letterIndex) / 26) | 0
}
return prefix
}
export type SupportedCosmWasmClient =
| SigningCosmWasmClient
| SecretSigningCosmWasmClient
/**
* Instantiate a smart contract from any supported client.
*
* This uses our custom instantiate encoder since CosmJS is unreliable due to
* the SDK version (47+) change that improperly handles the optional admin field
* as an empty string. The normal signing client `instantiate` function is thus
* no longer reliable.
*/
export const instantiateSmartContract = async (
client: SupportedCosmWasmClient | (() => Promise<SupportedCosmWasmClient>),
sender: string,
codeId: number,
label: string,
msg: object,
funds?: Coin[],
admin?: string | null,
fee = CHAIN_GAS_MULTIPLIER,
memo: string | undefined = undefined
): Promise<string> => {
client = typeof client === 'function' ? await client() : client
if (client instanceof SecretSigningCosmWasmClient) {
const { contractAddress } = await client.instantiate(
sender,
codeId,
msg,
label,
fee,
{
funds,
admin: typeof admin === 'string' ? admin : undefined,
memo,
}
)
return contractAddress
} else {
const result = await client.signAndBroadcast(
sender,
[
{
typeUrl: MsgInstantiateContract.typeUrl,
value: MsgInstantiateContract.fromPartial({
sender,
admin: admin ?? undefined,
codeId: BigInt(codeId),
label,
msg: toUtf8(JSON.stringify(msg)),
funds,
}),
},
],
fee,
memo
)
if (isDeliverTxFailure(result)) {
throw new Error(createDeliverTxResponseErrorMessage(result))
}
const contractAddress = findEventsAttributeValue(
result.events,
'instantiate',
'_contract_address'
)
if (!contractAddress) {
throw new Error(
`Contract address not found for TX: ${result.transactionHash}`
)
}
return contractAddress
}
}
/**
* Execute a smart contract from any supported client.
*/
export const executeSmartContract = async (
client: SupportedCosmWasmClient | (() => Promise<SupportedCosmWasmClient>),
sender: string,
contractAddress: string,
msg: object,
funds?: Coin[],
fee = CHAIN_GAS_MULTIPLIER,
memo: string | undefined = undefined
): Promise<ExecuteResult> => {
client = typeof client === 'function' ? await client() : client
if (client instanceof SecretSigningCosmWasmClient) {
return await client.execute(sender, contractAddress, msg, fee, memo, funds)
} else {
const result = await client.signAndBroadcast(
sender,
[
{
typeUrl: MsgExecuteContract.typeUrl,
value: MsgExecuteContract.fromPartial({
sender,
contract: contractAddress,
msg: toUtf8(JSON.stringify(msg)),
funds,
}),
},
],
fee,
memo
)
if (isDeliverTxFailure(result)) {
throw new Error(createDeliverTxResponseErrorMessage(result))
}
return {
logs: parseRawLog(result.rawLog),
height: result.height,
transactionHash: result.transactionHash,
events: result.events,
gasWanted: result.gasWanted,
gasUsed: result.gasUsed,
}
}
}
const createDeliverTxResponseErrorMessage = (result: DeliverTxResponse) =>
`Error when broadcasting tx ${result.transactionHash} at height ${result.height}. Code: ${result.code}; Raw log: ${result.rawLog}`
/**
* Convert bech32 address data to address string for the given chain.
*/
export const bech32DataToAddress = (
chainId: string,
bech32Bytes: Uint8Array
): string => toBech32(getChainForChainId(chainId).bech32_prefix, bech32Bytes)
/**
* Convert bech32 address string to base64 string with bech32 data.
*/
export const bech32AddressToBase64 = (bech32Address: string): string =>
toBase64(fromBech32(bech32Address).data)