-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathcontracts.ts
292 lines (268 loc) · 7.75 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
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
import {
ExecuteInstruction,
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 { HugeDecimal } from '@dao-dao/math'
import { ContractVersion, GenericToken, TokenType } from '@dao-dao/types'
import {
MsgExecuteContract,
MsgInstantiateContract,
MsgInstantiateContract2,
} 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 { encodeJsonToBase64 } from './messages'
import { SecretSigningCosmWasmClient } from './secret'
const CONTRACT_VERSIONS = Object.values(ContractVersion)
// If version is defined, returns it. Otherwise, returns
// ContractVersion.Unknown.
export const parseContractVersion = (version: string): ContractVersion =>
CONTRACT_VERSIONS.find((v) => v === version) || ContractVersion.Unknown
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 SupportedSigningCosmWasmClient =
| 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.
*
* If `salt` is passed, instantiate2 will be used instead of instantiate.
*/
export const instantiateSmartContract = async (
client:
| SupportedSigningCosmWasmClient
| (() => Promise<SupportedSigningCosmWasmClient>),
sender: string,
codeId: number,
label: string,
msg: object,
funds?: Coin[],
admin?: string | null,
fee = CHAIN_GAS_MULTIPLIER,
memo: string | undefined = undefined,
/**
* If passed, will use instantiate2 instead of instantiate.
*/
salt: Uint8Array | undefined = undefined
): Promise<string> => {
client = typeof client === 'function' ? await client() : client
if (client instanceof SecretSigningCosmWasmClient) {
if (salt) {
throw new Error('Secret Network does not support instantiate2')
}
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,
[
salt
? {
typeUrl: MsgInstantiateContract2.typeUrl,
value: MsgInstantiateContract2.fromPartial({
sender,
admin: admin ?? undefined,
codeId: BigInt(codeId),
label,
msg: toUtf8(JSON.stringify(msg)),
funds,
salt,
fixMsg: false,
}),
}
: {
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 message from any supported client.
*/
export const executeSmartContract = async (
client:
| SupportedSigningCosmWasmClient
| (() => Promise<SupportedSigningCosmWasmClient>),
sender: string,
contractAddress: string,
msg: object,
funds?: Coin[],
fee = CHAIN_GAS_MULTIPLIER,
memo: string | undefined = undefined
): Promise<ExecuteResult> =>
executeSmartContracts({
client,
sender,
instructions: [{ contractAddress, msg, funds }],
fee,
memo,
})
/**
* Execute a smart contract message with tokens from any supported client.
*/
export const executeSmartContractWithToken = async ({
client,
sender,
contractAddress,
msg,
token,
amount,
fee = CHAIN_GAS_MULTIPLIER,
memo = undefined,
}: {
client:
| SupportedSigningCosmWasmClient
| (() => Promise<SupportedSigningCosmWasmClient>)
sender: string
contractAddress: string
msg: object
token: GenericToken
amount: HugeDecimal
fee?: number
memo?: string
}): Promise<ExecuteResult> => {
return executeSmartContracts({
client,
sender,
instructions: [
// Wrap in CW20 send if necessary.
token.type === TokenType.Cw20
? {
contractAddress: token.denomOrAddress,
msg: {
send: {
amount,
contract: contractAddress,
msg: encodeJsonToBase64(msg),
},
},
}
: {
contractAddress,
msg,
funds: amount.toCoins(token.denomOrAddress),
},
],
fee,
memo,
})
}
/**
* Execute one or more smart contract messages from any supported client.
*/
export const executeSmartContracts = async ({
client,
sender,
instructions,
fee = CHAIN_GAS_MULTIPLIER,
memo = undefined,
}: {
client:
| SupportedSigningCosmWasmClient
| (() => Promise<SupportedSigningCosmWasmClient>)
sender: string
instructions: ExecuteInstruction[]
fee?: number
memo?: string
}): Promise<ExecuteResult> => {
client = typeof client === 'function' ? await client() : client
if (client instanceof SecretSigningCosmWasmClient) {
return await client.executeMultiple(sender, instructions, fee, memo)
} else {
const result = await client.signAndBroadcast(
sender,
instructions.map(({ contractAddress, msg, funds }) => ({
typeUrl: MsgExecuteContract.typeUrl,
value: MsgExecuteContract.fromPartial({
sender,
contract: contractAddress,
msg: toUtf8(JSON.stringify(msg)),
funds: [...(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).bech32Prefix, bech32Bytes)
/**
* Convert bech32 address string to base64 string with bech32 data.
*/
export const bech32AddressToBase64 = (bech32Address: string): string =>
toBase64(fromBech32(bech32Address).data)