-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathCall.tsx
294 lines (271 loc) · 9.01 KB
/
Call.tsx
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
293
294
// Copyright 2017-2023 @polkadot/app-contracts authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { SubmittableExtrinsic } from '@polkadot/api/types';
import type { ContractPromise } from '@polkadot/api-contract';
import type { ContractCallOutcome } from '@polkadot/api-contract/types';
import type { WeightV2 } from '@polkadot/types/interfaces';
import type { CallResult } from './types.js';
import React, { useCallback, useEffect, useState } from 'react';
import { Button, Dropdown, Expander, InputAddress, InputBalance, Modal, styled, Toggle, TxButton } from '@polkadot/react-components';
import { useAccountId, useApi, useDebounce, useFormField, useToggle } from '@polkadot/react-hooks';
import { Available } from '@polkadot/react-query';
import { BN, BN_ONE, BN_ZERO } from '@polkadot/util';
import { InputMegaGas, Params } from '../shared/index.js';
import { useTranslation } from '../translate.js';
import useWeight from '../useWeight.js';
import Outcome from './Outcome.js';
import { getCallMessageOptions } from './util.js';
interface Props {
className?: string;
contract: ContractPromise;
messageIndex: number;
onCallResult?: (messageIndex: number, result?: ContractCallOutcome) => void;
onChangeMessage: (messageIndex: number) => void;
onClose: () => void;
}
const MAX_CALL_WEIGHT = new BN(5_000_000_000_000).isub(BN_ONE);
function Call ({ className = '', contract, messageIndex, onCallResult, onChangeMessage, onClose }: Props): React.ReactElement<Props> | null {
const { t } = useTranslation();
const { api } = useApi();
const message = contract.abi.messages[messageIndex];
const [accountId, setAccountId] = useAccountId();
const [estimatedWeight, setEstimatedWeight] = useState<BN | null>(null);
const [estimatedWeightV2, setEstimatedWeightV2] = useState<WeightV2 | null>(null);
const [value, isValueValid, setValue] = useFormField<BN>(BN_ZERO);
const [outcomes, setOutcomes] = useState<CallResult[]>([]);
const [execTx, setExecTx] = useState<SubmittableExtrinsic<'promise'> | null>(null);
const [params, setParams] = useState<unknown[]>([]);
const [isViaCall, toggleViaCall] = useToggle();
const weight = useWeight();
const dbValue = useDebounce(value);
const dbParams = useDebounce(params);
useEffect((): void => {
setEstimatedWeight(null);
setEstimatedWeightV2(null);
setParams([]);
}, [contract, messageIndex]);
useEffect((): void => {
async function dryRun () {
if (accountId && value && message.isMutating) {
const dryRunParams: Parameters<typeof api.call.contractsApi.call> =
[
accountId,
contract.address,
message.isPayable
? api.registry.createType('Balance', value)
: api.registry.createType('Balance', BN_ZERO),
weight.weightV2,
null,
message.toU8a(params)
];
const dryRunResult = await api.call.contractsApi.call(...dryRunParams);
setExecTx((): SubmittableExtrinsic<'promise'> | null => {
try {
return contract.tx[message.method](
{
gasLimit: dryRunResult.gasRequired,
storageDepositLimit: dryRunResult.storageDeposit.isCharge ? dryRunResult.storageDeposit.asCharge : null,
value: message.isPayable ? value : 0
},
...params
);
} catch {
return null;
}
});
}
}
dryRun().catch((e) => console.error(e));
}, [api, accountId, contract, message, value, weight, params]);
useEffect((): void => {
if (!accountId || !message || !dbParams || !dbValue) {
return;
}
contract
.query[message.method](accountId, { gasLimit: -1, storageDepositLimit: null, value: message.isPayable ? dbValue : 0 }, ...dbParams)
.then(({ gasRequired, result }) => {
if (weight.isWeightV2) {
setEstimatedWeightV2(
result.isOk
? api.registry.createType('WeightV2', gasRequired)
: null
);
} else {
setEstimatedWeight(
result.isOk
? gasRequired.refTime.toBn()
: null
);
}
})
.catch(() => {
setEstimatedWeight(null);
setEstimatedWeightV2(null);
});
}, [api, accountId, contract, message, dbParams, dbValue, weight.isWeightV2]);
const _onSubmitRpc = useCallback(
(): void => {
if (!accountId || !message || !value || !weight) {
return;
}
contract
.query[message.method](
accountId,
{ gasLimit: weight.isWeightV2 ? weight.weightV2 : weight.isEmpty ? -1 : weight.weight, storageDepositLimit: null, value: message.isPayable ? value : 0 },
...params
)
.then((result): void => {
setOutcomes([{
...result,
from: accountId,
message,
params,
when: new Date()
}, ...outcomes]);
onCallResult && onCallResult(messageIndex, result);
})
.catch((error): void => {
console.error(error);
onCallResult && onCallResult(messageIndex);
});
},
[accountId, contract.query, message, messageIndex, onCallResult, outcomes, params, value, weight]
);
const _onClearOutcome = useCallback(
(outcomeIndex: number) =>
() => setOutcomes([...outcomes.filter((_, index) => index !== outcomeIndex)]),
[outcomes]
);
const isValid = !!(accountId && weight.isValid && isValueValid);
const isViaRpc = (isViaCall || (!message.isMutating && !message.isPayable));
return (
<StyledModal
className={`${className} app--contracts-Modal`}
header={t<string>('Call a contract')}
onClose={onClose}
>
<Modal.Content>
<InputAddress
isDisabled
label={t<string>('contract to use')}
type='contract'
value={contract.address}
/>
<InputAddress
defaultValue={accountId}
label={t<string>('call from account')}
labelExtra={
<Available
label={t<string>('transferrable')}
params={accountId}
/>
}
onChange={setAccountId}
type='account'
value={accountId}
/>
{messageIndex !== null && (
<>
<Dropdown
defaultValue={messageIndex}
isError={message === null}
label={t<string>('message to send')}
onChange={onChangeMessage}
options={getCallMessageOptions(contract)}
value={messageIndex}
/>
<Params
onChange={setParams}
params={
message
? message.args
: undefined
}
registry={contract.abi.registry}
/>
</>
)}
{message.isPayable && (
<InputBalance
isError={!isValueValid}
isZeroable
label={t<string>('value')}
onChange={setValue}
value={value}
/>
)}
<InputMegaGas
estimatedWeight={message.isMutating ? estimatedWeight : MAX_CALL_WEIGHT}
estimatedWeightV2={message.isMutating
? estimatedWeightV2
: api.registry.createType('WeightV2', {
proofSize: new BN(1_000_000),
refTIme: MAX_CALL_WEIGHT
})
}
isCall={!message.isMutating}
weight={weight}
/>
{message.isMutating && (
<Toggle
className='rpc-toggle'
label={t<string>('read contract only, no execution')}
onChange={toggleViaCall}
value={isViaCall}
/>
)}
{outcomes.length > 0 && (
<Expander
className='outcomes'
isOpen
summary={t<string>('Call results')}
>
{outcomes.map((outcome, index): React.ReactNode => (
<Outcome
key={`outcome-${index}`}
onClear={_onClearOutcome(index)}
outcome={outcome}
/>
))}
</Expander>
)}
</Modal.Content>
<Modal.Actions>
{isViaRpc
? (
<Button
icon='sign-in-alt'
isDisabled={!isValid}
label={t<string>('Read')}
onClick={_onSubmitRpc}
/>
)
: (
<TxButton
accountId={accountId}
extrinsic={execTx}
icon='sign-in-alt'
isDisabled={!isValid || !execTx}
label={t<string>('Execute')}
onStart={onClose}
/>
)
}
</Modal.Actions>
</StyledModal>
);
}
const StyledModal = styled(Modal)`
.rpc-toggle {
margin-top: 1rem;
display: flex;
justify-content: flex-end;
}
.clear-all {
float: right;
}
.outcomes {
margin-top: 1rem;
}
`;
export default React.memo(Call);