forked from hashgraph/hedera-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
contract_call_query.go
412 lines (345 loc) · 12.1 KB
/
contract_call_query.go
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
package hedera
/*-
*
* Hedera Go SDK
*
* Copyright (C) 2020 - 2022 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import (
"fmt"
"time"
"github.com/hashgraph/hedera-protobufs-go/services"
)
// ContractCallQuery calls a function of the given smart contract instance, giving it ContractFunctionParameters as its
// inputs. It will consume the entire given amount of gas.
//
// This is performed locally on the particular _Node that the client is communicating with. It cannot change the state of
// the contract instance (and so, cannot spend anything from the instance's Hedera account). It will not have a
// consensus timestamp. It cannot generate a record or a receipt. This is useful for calling getter functions, which
// purely read the state and don't change it. It is faster and cheaper than a ContractExecuteTransaction, because it is
// purely local to a single _Node.
type ContractCallQuery struct {
Query
contractID *ContractID
gas uint64
maxResultSize uint64
functionParameters []byte
senderID *AccountID
}
// NewContractCallQuery creates a ContractCallQuery query which can be used to construct and execute a
// Contract Call Local Query.
func NewContractCallQuery() *ContractCallQuery {
header := services.QueryHeader{}
query := _NewQuery(true, &header)
return &ContractCallQuery{
Query: query,
}
}
// When execution is attempted, a single attempt will timeout when this deadline is reached. (The SDK may subsequently retry the execution.)
func (query *ContractCallQuery) SetGrpcDeadline(deadline *time.Duration) *ContractCallQuery {
query.Query.SetGrpcDeadline(deadline)
return query
}
// SetContractID sets the contract instance to call
func (query *ContractCallQuery) SetContractID(contractID ContractID) *ContractCallQuery {
query.contractID = &contractID
return query
}
// GetContractID returns the contract instance to call
func (query *ContractCallQuery) GetContractID() ContractID {
if query.contractID == nil {
return ContractID{}
}
return *query.contractID
}
// SetSenderID
// The account that is the "sender." If not present it is the accountId from the transactionId.
// Typically a different value than specified in the transactionId requires a valid signature
// over either the hedera transaction or foreign transaction data.
func (query *ContractCallQuery) SetSenderID(id AccountID) *ContractCallQuery {
query.senderID = &id
return query
}
// GetSenderID returns the AccountID that is the "sender."
func (query *ContractCallQuery) GetSenderID() AccountID {
if query.senderID == nil {
return AccountID{}
}
return *query.senderID
}
// SetGas sets the amount of gas to use for the call. All of the gas offered will be charged for.
func (query *ContractCallQuery) SetGas(gas uint64) *ContractCallQuery {
query.gas = gas
return query
}
// GetGas returns the amount of gas to use for the call.
func (query *ContractCallQuery) GetGas() uint64 {
return query.gas
}
// Deprecated
func (query *ContractCallQuery) SetMaxResultSize(size uint64) *ContractCallQuery {
query.maxResultSize = size
return query
}
// SetFunction sets which function to call, and the ContractFunctionParams to pass to the function
func (query *ContractCallQuery) SetFunction(name string, params *ContractFunctionParameters) *ContractCallQuery {
if params == nil {
params = NewContractFunctionParameters()
}
query.functionParameters = params._Build(&name)
return query
}
// SetFunctionParameters sets the function parameters as their raw bytes.
func (query *ContractCallQuery) SetFunctionParameters(byteArray []byte) *ContractCallQuery {
query.functionParameters = byteArray
return query
}
// GetFunctionParameters returns the function parameters as their raw bytes.
func (query *ContractCallQuery) GetFunctionParameters() []byte {
return query.functionParameters
}
func (query *ContractCallQuery) _ValidateNetworkOnIDs(client *Client) error {
if client == nil || !client.autoValidateChecksums {
return nil
}
if query.contractID != nil {
if err := query.contractID.ValidateChecksum(client); err != nil {
return err
}
}
if query.senderID != nil {
if err := query.senderID.ValidateChecksum(client); err != nil {
return err
}
}
return nil
}
func (query *ContractCallQuery) _Build() *services.Query_ContractCallLocal {
pb := services.Query_ContractCallLocal{
ContractCallLocal: &services.ContractCallLocalQuery{
Header: &services.QueryHeader{},
Gas: int64(query.gas),
},
}
if query.contractID != nil {
pb.ContractCallLocal.ContractID = query.contractID._ToProtobuf()
}
if query.senderID != nil {
pb.ContractCallLocal.SenderId = query.senderID._ToProtobuf()
}
if len(query.functionParameters) > 0 {
pb.ContractCallLocal.FunctionParameters = query.functionParameters
}
return &pb
}
// GetCost returns the fee that would be charged to get the requested information (if a cost was requested).
func (query *ContractCallQuery) GetCost(client *Client) (Hbar, error) {
if client == nil || client.operator == nil {
return Hbar{}, errNoClientProvided
}
var err error
err = query._ValidateNetworkOnIDs(client)
if err != nil {
return Hbar{}, err
}
for range query.nodeAccountIDs.slice {
paymentTransaction, err := _QueryMakePaymentTransaction(TransactionID{}, AccountID{}, client.operator, Hbar{})
if err != nil {
return Hbar{}, err
}
query.paymentTransactions = append(query.paymentTransactions, paymentTransaction)
}
pb := query._Build()
pb.ContractCallLocal.Header = query.pbHeader
query.pb = &services.Query{
Query: pb,
}
resp, err := _Execute(
client,
&query.Query,
_ContractCallQueryShouldRetry,
_CostQueryMakeRequest,
_CostQueryAdvanceRequest,
_QueryGetNodeAccountID,
_ContractCallQueryGetMethod,
_ContractCallQueryMapStatusError,
_QueryMapResponse,
query._GetLogID(),
query.grpcDeadline,
query.maxBackoff,
query.minBackoff,
query.maxRetry,
)
if err != nil {
return Hbar{}, err
}
cost := int64(resp.(*services.Response).GetContractCallLocal().Header.Cost)
return HbarFromTinybar(cost), nil
}
func _ContractCallQueryShouldRetry(logID string, _ interface{}, response interface{}) _ExecutionState {
return _QueryShouldRetry(logID, Status(response.(*services.Response).GetContractCallLocal().Header.NodeTransactionPrecheckCode))
}
func _ContractCallQueryMapStatusError(_ interface{}, response interface{}) error {
return ErrHederaPreCheckStatus{
Status: Status(response.(*services.Response).GetContractCallLocal().Header.NodeTransactionPrecheckCode),
}
}
func _ContractCallQueryGetMethod(_ interface{}, channel *_Channel) _Method {
return _Method{
query: channel._GetContract().ContractCallLocalMethod,
}
}
// Execute executes the Query with the provided client
func (query *ContractCallQuery) Execute(client *Client) (ContractFunctionResult, error) {
if client == nil || client.operator == nil {
return ContractFunctionResult{}, errNoClientProvided
}
var err error
err = query._ValidateNetworkOnIDs(client)
if err != nil {
return ContractFunctionResult{}, err
}
if !query.paymentTransactionIDs.locked {
query.paymentTransactionIDs._Clear()._Push(TransactionIDGenerate(client.operator.accountID))
}
var cost Hbar
if query.queryPayment.tinybar != 0 {
cost = query.queryPayment
} else {
if query.maxQueryPayment.tinybar == 0 {
cost = client.GetDefaultMaxQueryPayment()
} else {
cost = query.maxQueryPayment
}
actualCost, err := query.GetCost(client)
if err != nil {
return ContractFunctionResult{}, err
}
if cost.tinybar < actualCost.tinybar {
return ContractFunctionResult{}, ErrMaxQueryPaymentExceeded{
QueryCost: actualCost,
MaxQueryPayment: cost,
query: "ContractFunctionResultQuery",
}
}
cost = actualCost
}
query.paymentTransactions = make([]*services.Transaction, 0)
if query.nodeAccountIDs.locked {
err = _QueryGeneratePayments(&query.Query, client, cost)
if err != nil {
return ContractFunctionResult{}, err
}
} else {
paymentTransaction, err := _QueryMakePaymentTransaction(query.paymentTransactionIDs._GetCurrent().(TransactionID), AccountID{}, client.operator, cost)
if err != nil {
return ContractFunctionResult{}, err
}
query.paymentTransactions = append(query.paymentTransactions, paymentTransaction)
}
pb := query._Build()
pb.ContractCallLocal.Header = query.pbHeader
query.pb = &services.Query{
Query: pb,
}
resp, err := _Execute(
client,
&query.Query,
_ContractCallQueryShouldRetry,
_QueryMakeRequest,
_QueryAdvanceRequest,
_QueryGetNodeAccountID,
_ContractCallQueryGetMethod,
_ContractCallQueryMapStatusError,
_QueryMapResponse,
query._GetLogID(),
query.grpcDeadline,
query.maxBackoff,
query.minBackoff,
query.maxRetry,
)
if err != nil {
return ContractFunctionResult{}, err
}
return _ContractFunctionResultFromProtobuf(resp.(*services.Response).GetContractCallLocal().FunctionResult), nil
}
// SetMaxQueryPayment sets the maximum payment allowed for this Query.
func (query *ContractCallQuery) SetMaxQueryPayment(maxPayment Hbar) *ContractCallQuery {
query.Query.SetMaxQueryPayment(maxPayment)
return query
}
// SetQueryPayment sets the payment amount for this Query.
func (query *ContractCallQuery) SetQueryPayment(paymentAmount Hbar) *ContractCallQuery {
query.Query.SetQueryPayment(paymentAmount)
return query
}
// SetNodeAccountIDs sets the _Node AccountID for this ContractCallQuery.
func (query *ContractCallQuery) SetNodeAccountIDs(accountID []AccountID) *ContractCallQuery {
query.Query.SetNodeAccountIDs(accountID)
return query
}
// SetMaxRetry sets the max number of errors before execution will fail.
func (query *ContractCallQuery) SetMaxRetry(count int) *ContractCallQuery {
query.Query.SetMaxRetry(count)
return query
}
// SetMaxBackoff The maximum amount of time to wait between retries.
// Every retry attempt will increase the wait time exponentially until it reaches this time.
func (query *ContractCallQuery) SetMaxBackoff(max time.Duration) *ContractCallQuery {
if max.Nanoseconds() < 0 {
panic("maxBackoff must be a positive duration")
} else if max.Nanoseconds() < query.minBackoff.Nanoseconds() {
panic("maxBackoff must be greater than or equal to minBackoff")
}
query.maxBackoff = &max
return query
}
// GetMaxBackoff returns the maximum amount of time to wait between retries.
func (query *ContractCallQuery) GetMaxBackoff() time.Duration {
if query.maxBackoff != nil {
return *query.maxBackoff
}
return 8 * time.Second
}
// SetMinBackoff sets the minimum amount of time to wait between retries.
func (query *ContractCallQuery) SetMinBackoff(min time.Duration) *ContractCallQuery {
if min.Nanoseconds() < 0 {
panic("minBackoff must be a positive duration")
} else if query.maxBackoff.Nanoseconds() < min.Nanoseconds() {
panic("minBackoff must be less than or equal to maxBackoff")
}
query.minBackoff = &min
return query
}
// GetMinBackoff returns the minimum amount of time to wait between retries.
func (query *ContractCallQuery) GetMinBackoff() time.Duration {
if query.minBackoff != nil {
return *query.minBackoff
}
return 250 * time.Millisecond
}
func (query *ContractCallQuery) _GetLogID() string {
timestamp := query.timestamp.UnixNano()
if query.paymentTransactionIDs._Length() > 0 && query.paymentTransactionIDs._GetCurrent().(TransactionID).ValidStart != nil {
timestamp = query.paymentTransactionIDs._GetCurrent().(TransactionID).ValidStart.UnixNano()
}
return fmt.Sprintf("ContractCallQuery:%d", timestamp)
}
// SetPaymentTransactionID assigns the payment transaction id.
func (query *ContractCallQuery) SetPaymentTransactionID(transactionID TransactionID) *ContractCallQuery {
query.paymentTransactionIDs._Clear()._Push(transactionID)._SetLocked(true)
return query
}