-
Notifications
You must be signed in to change notification settings - Fork 238
Expand file tree
/
Copy pathcontracts.go
More file actions
703 lines (603 loc) · 22.4 KB
/
Copy pathcontracts.go
File metadata and controls
703 lines (603 loc) · 22.4 KB
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
package client
import (
"bytes"
"context"
"fmt"
"strconv"
"github.com/fbsobreira/gotron-sdk/pkg/abi"
"github.com/fbsobreira/gotron-sdk/pkg/address"
"github.com/fbsobreira/gotron-sdk/pkg/common"
"github.com/fbsobreira/gotron-sdk/pkg/proto/api"
"github.com/fbsobreira/gotron-sdk/pkg/proto/core"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// defaultFromAddress is the zero address used as the default "from" for
// read-only contract calls. Decoded once at init to avoid repeated parsing.
var defaultFromAddress address.Address
func init() {
var err error
defaultFromAddress, err = address.HexToAddress("410000000000000000000000000000000000000000")
if err != nil {
panic("invalid default from address: " + err.Error())
}
}
// ConstantCallOption configures optional fields on a TriggerSmartContract
// used by constant (read-only) contract calls. This allows callers to set
// values like CallValue or TokenValue without breaking backward compatibility.
type ConstantCallOption func(*core.TriggerSmartContract)
// WithCallValue sets the TRX call value (in sun) on a constant contract call.
// This is required to accurately simulate payable functions that depend on msg.value.
func WithCallValue(value int64) ConstantCallOption {
return func(ct *core.TriggerSmartContract) {
ct.CallValue = value
}
}
// WithTokenValue sets the TRC10 token ID and amount on a constant contract call.
// It returns an error if tokenID is not a valid integer.
func WithTokenValue(tokenID string, amount int64) (ConstantCallOption, error) {
id, err := strconv.ParseInt(tokenID, 10, 64)
if err != nil {
return nil, fmt.Errorf("invalid token ID %q: %w", tokenID, err)
}
return func(ct *core.TriggerSmartContract) {
ct.TokenId = id
ct.CallTokenValue = amount
}, nil
}
func applyConstantCallOptions(ct *core.TriggerSmartContract, opts []ConstantCallOption) {
for _, opt := range opts {
if opt == nil {
continue
}
opt(ct)
}
}
// UpdateEnergyLimitContract updates the energy limit of a deployed smart contract.
func (g *GrpcClient) UpdateEnergyLimitContract(from, contractAddress string, value int64) (*api.TransactionExtention, error) {
ctx, cancel := g.newContext()
defer cancel()
return g.UpdateEnergyLimitContractCtx(ctx, from, contractAddress, value)
}
// UpdateEnergyLimitContractCtx is the context-aware version of UpdateEnergyLimitContract.
func (g *GrpcClient) UpdateEnergyLimitContractCtx(ctx context.Context, from, contractAddress string, value int64) (*api.TransactionExtention, error) {
ctx = g.withAPIKey(ctx)
fromDesc, err := address.Base58ToAddress(from)
if err != nil {
return nil, err
}
contractDesc, err := address.Base58ToAddress(contractAddress)
if err != nil {
return nil, err
}
ct := &core.UpdateEnergyLimitContract{
OwnerAddress: fromDesc.Bytes(),
ContractAddress: contractDesc.Bytes(),
OriginEnergyLimit: value,
}
tx, err := g.Client.UpdateEnergyLimit(ctx, ct)
if err != nil {
return nil, err
}
if tx.GetResult().GetCode() > 0 {
return nil, fmt.Errorf("%s", string(tx.GetResult().GetMessage()))
}
return tx, err
}
// UpdateSettingContract changes the user resource consumption ratio of a deployed contract.
func (g *GrpcClient) UpdateSettingContract(from, contractAddress string, value int64) (*api.TransactionExtention, error) {
ctx, cancel := g.newContext()
defer cancel()
return g.UpdateSettingContractCtx(ctx, from, contractAddress, value)
}
// UpdateSettingContractCtx is the context-aware version of UpdateSettingContract.
func (g *GrpcClient) UpdateSettingContractCtx(ctx context.Context, from, contractAddress string, value int64) (*api.TransactionExtention, error) {
ctx = g.withAPIKey(ctx)
fromDesc, err := address.Base58ToAddress(from)
if err != nil {
return nil, err
}
contractDesc, err := address.Base58ToAddress(contractAddress)
if err != nil {
return nil, err
}
ct := &core.UpdateSettingContract{
OwnerAddress: fromDesc.Bytes(),
ContractAddress: contractDesc.Bytes(),
ConsumeUserResourcePercent: value,
}
tx, err := g.Client.UpdateSetting(ctx, ct)
if err != nil {
return nil, err
}
if tx.GetResult().GetCode() > 0 {
return nil, fmt.Errorf("%s", string(tx.GetResult().GetMessage()))
}
return tx, err
}
// TriggerConstantContract executes a read-only smart contract call and returns the result.
func (g *GrpcClient) TriggerConstantContract(from, contractAddress, method, jsonString string, opts ...ConstantCallOption) (*api.TransactionExtention, error) {
ctx, cancel := g.newContext()
defer cancel()
return g.TriggerConstantContractCtx(ctx, from, contractAddress, method, jsonString, opts...)
}
// TriggerConstantContractCtx is the context-aware version of TriggerConstantContract.
func (g *GrpcClient) TriggerConstantContractCtx(ctx context.Context, from, contractAddress, method, jsonString string, opts ...ConstantCallOption) (*api.TransactionExtention, error) {
ctx = g.withAPIKey(ctx)
var err error
fromDesc := defaultFromAddress
if len(from) > 0 {
fromDesc, err = address.Base58ToAddress(from)
if err != nil {
return nil, err
}
}
contractDesc, err := address.Base58ToAddress(contractAddress)
if err != nil {
return nil, err
}
param, err := abi.LoadFromJSONWithMethod(method, jsonString)
if err != nil {
return nil, err
}
dataBytes, err := abi.Pack(method, param)
if err != nil {
return nil, err
}
ct := &core.TriggerSmartContract{
OwnerAddress: fromDesc.Bytes(),
ContractAddress: contractDesc.Bytes(),
Data: dataBytes,
}
applyConstantCallOptions(ct, opts)
return g.triggerConstantContract(ctx, ct)
}
// triggerConstantContract and return tx result
func (g *GrpcClient) triggerConstantContract(ctx context.Context, ct *core.TriggerSmartContract) (*api.TransactionExtention, error) {
return g.Client.TriggerConstantContract(ctx, ct)
}
// TriggerContract executes a state-changing smart contract call and returns the unsigned transaction.
func (g *GrpcClient) TriggerContract(from, contractAddress, method, jsonString string,
feeLimit, tAmount int64, tTokenID string, tTokenAmount int64) (*api.TransactionExtention, error) {
ctx, cancel := g.newContext()
defer cancel()
return g.TriggerContractCtx(ctx, from, contractAddress, method, jsonString, feeLimit, tAmount, tTokenID, tTokenAmount)
}
// TriggerContractCtx is the context-aware version of TriggerContract.
func (g *GrpcClient) TriggerContractCtx(ctx context.Context, from, contractAddress, method, jsonString string,
feeLimit, tAmount int64, tTokenID string, tTokenAmount int64) (*api.TransactionExtention, error) {
ctx = g.withAPIKey(ctx)
fromDesc, err := address.Base58ToAddress(from)
if err != nil {
return nil, err
}
contractDesc, err := address.Base58ToAddress(contractAddress)
if err != nil {
return nil, err
}
param, err := abi.LoadFromJSONWithMethod(method, jsonString)
if err != nil {
return nil, err
}
dataBytes, err := abi.Pack(method, param)
if err != nil {
return nil, err
}
ct := &core.TriggerSmartContract{
OwnerAddress: fromDesc.Bytes(),
ContractAddress: contractDesc.Bytes(),
Data: dataBytes,
}
if tAmount > 0 {
ct.CallValue = tAmount
}
if len(tTokenID) > 0 && tTokenAmount > 0 {
ct.CallTokenValue = tTokenAmount
ct.TokenId, err = strconv.ParseInt(tTokenID, 10, 64)
if err != nil {
return nil, err
}
}
return g.triggerContract(ctx, ct, feeLimit)
}
// triggerContract and return tx result
func (g *GrpcClient) triggerContract(ctx context.Context, ct *core.TriggerSmartContract, feeLimit int64) (*api.TransactionExtention, error) {
tx, err := g.Client.TriggerContract(ctx, ct)
if err != nil {
return nil, err
}
if tx.GetResult().GetCode() > 0 {
return nil, fmt.Errorf("%s", string(tx.GetResult().GetMessage()))
}
// A success code does not guarantee a transaction: guard before assigning
// through it, as DeployContractCtx does.
if tx.GetTransaction().GetRawData() == nil {
return nil, fmt.Errorf("trigger contract: node returned no transaction")
}
if feeLimit > 0 {
tx.Transaction.RawData.FeeLimit = feeLimit
// update hash
err = g.UpdateHash(tx)
}
return tx, err
}
// TriggerConstantContractWithData calls a constant contract method using
// pre-packed ABI data, bypassing the JSON string → parse → pack pipeline.
// This is useful when callers already have packed data from go-ethereum's
// abi.Pack() or similar tooling.
func (g *GrpcClient) TriggerConstantContractWithData(from, contractAddress string, data []byte, opts ...ConstantCallOption) (*api.TransactionExtention, error) {
ctx, cancel := g.newContext()
defer cancel()
return g.TriggerConstantContractWithDataCtx(ctx, from, contractAddress, data, opts...)
}
// TriggerConstantContractWithDataCtx is the context-aware version of TriggerConstantContractWithData.
func (g *GrpcClient) TriggerConstantContractWithDataCtx(ctx context.Context, from, contractAddress string, data []byte, opts ...ConstantCallOption) (*api.TransactionExtention, error) {
ctx = g.withAPIKey(ctx)
var err error
fromDesc := defaultFromAddress
if len(from) > 0 {
fromDesc, err = address.Base58ToAddress(from)
if err != nil {
return nil, err
}
}
contractDesc, err := address.Base58ToAddress(contractAddress)
if err != nil {
return nil, err
}
ct := &core.TriggerSmartContract{
OwnerAddress: fromDesc.Bytes(),
ContractAddress: contractDesc.Bytes(),
Data: data,
}
applyConstantCallOptions(ct, opts)
return g.triggerConstantContract(ctx, ct)
}
// TriggerContractWithData triggers a contract method using pre-packed ABI
// data, bypassing the JSON string → parse → pack pipeline. This is useful
// when callers already have packed data from go-ethereum's abi.Pack() or
// similar tooling.
func (g *GrpcClient) TriggerContractWithData(from, contractAddress string, data []byte,
feeLimit, tAmount int64, tTokenID string, tTokenAmount int64) (*api.TransactionExtention, error) {
ctx, cancel := g.newContext()
defer cancel()
return g.TriggerContractWithDataCtx(ctx, from, contractAddress, data, feeLimit, tAmount, tTokenID, tTokenAmount)
}
// TriggerContractWithDataCtx is the context-aware version of TriggerContractWithData.
func (g *GrpcClient) TriggerContractWithDataCtx(ctx context.Context, from, contractAddress string, data []byte,
feeLimit, tAmount int64, tTokenID string, tTokenAmount int64) (*api.TransactionExtention, error) {
ctx = g.withAPIKey(ctx)
fromDesc, err := address.Base58ToAddress(from)
if err != nil {
return nil, err
}
contractDesc, err := address.Base58ToAddress(contractAddress)
if err != nil {
return nil, err
}
ct := &core.TriggerSmartContract{
OwnerAddress: fromDesc.Bytes(),
ContractAddress: contractDesc.Bytes(),
Data: data,
}
if tAmount > 0 {
ct.CallValue = tAmount
}
if len(tTokenID) > 0 && tTokenAmount > 0 {
ct.CallTokenValue = tTokenAmount
ct.TokenId, err = strconv.ParseInt(tTokenID, 10, 64)
if err != nil {
return nil, err
}
}
return g.triggerContract(ctx, ct, feeLimit)
}
// EstimateEnergy returns the estimated energy required for a contract call.
func (g *GrpcClient) EstimateEnergy(from, contractAddress, method, jsonString string,
tAmount int64, tTokenID string, tTokenAmount int64) (*api.EstimateEnergyMessage, error) {
ctx, cancel := g.newContext()
defer cancel()
return g.EstimateEnergyCtx(ctx, from, contractAddress, method, jsonString, tAmount, tTokenID, tTokenAmount)
}
// EstimateEnergyCtx is the context-aware version of EstimateEnergy.
func (g *GrpcClient) EstimateEnergyCtx(ctx context.Context, from, contractAddress, method, jsonString string,
tAmount int64, tTokenID string, tTokenAmount int64) (*api.EstimateEnergyMessage, error) {
ctx = g.withAPIKey(ctx)
fromDesc, err := address.Base58ToAddress(from)
if err != nil {
return nil, err
}
contractDesc, err := address.Base58ToAddress(contractAddress)
if err != nil {
return nil, err
}
param, err := abi.LoadFromJSONWithMethod(method, jsonString)
if err != nil {
return nil, err
}
dataBytes, err := abi.Pack(method, param)
if err != nil {
return nil, err
}
ct := &core.TriggerSmartContract{
OwnerAddress: fromDesc.Bytes(),
ContractAddress: contractDesc.Bytes(),
Data: dataBytes,
}
if tAmount > 0 {
ct.CallValue = tAmount
}
if len(tTokenID) > 0 && tTokenAmount > 0 {
ct.CallTokenValue = tTokenAmount
ct.TokenId, err = strconv.ParseInt(tTokenID, 10, 64)
if err != nil {
return nil, err
}
}
return g.estimateEnergy(ctx, ct)
}
// EstimateEnergyWithData returns the estimated energy using pre-packed ABI
// data, bypassing the JSON string → parse → pack pipeline.
func (g *GrpcClient) EstimateEnergyWithData(from, contractAddress string, data []byte,
tAmount int64, tTokenID string, tTokenAmount int64) (*api.EstimateEnergyMessage, error) {
ctx, cancel := g.newContext()
defer cancel()
return g.EstimateEnergyWithDataCtx(ctx, from, contractAddress, data, tAmount, tTokenID, tTokenAmount)
}
// EstimateEnergyWithDataCtx is the context-aware version of EstimateEnergyWithData.
func (g *GrpcClient) EstimateEnergyWithDataCtx(ctx context.Context, from, contractAddress string, data []byte,
tAmount int64, tTokenID string, tTokenAmount int64) (*api.EstimateEnergyMessage, error) {
ctx = g.withAPIKey(ctx)
fromDesc, err := address.Base58ToAddress(from)
if err != nil {
return nil, err
}
contractDesc, err := address.Base58ToAddress(contractAddress)
if err != nil {
return nil, err
}
ct := &core.TriggerSmartContract{
OwnerAddress: fromDesc.Bytes(),
ContractAddress: contractDesc.Bytes(),
Data: data,
}
if tAmount > 0 {
ct.CallValue = tAmount
}
if len(tTokenID) > 0 && tTokenAmount > 0 {
ct.CallTokenValue = tTokenAmount
ct.TokenId, err = strconv.ParseInt(tTokenID, 10, 64)
if err != nil {
return nil, err
}
}
return g.estimateEnergy(ctx, ct)
}
// triggerContract and return tx result
func (g *GrpcClient) estimateEnergy(ctx context.Context, ct *core.TriggerSmartContract) (*api.EstimateEnergyMessage, error) {
tx, err := g.Client.EstimateEnergy(ctx, ct)
if err != nil {
if s, ok := status.FromError(err); ok && s.Code() == codes.Unimplemented {
return nil, fmt.Errorf("%w: %w", ErrEstimateEnergyNotSupported, err)
}
return nil, err
}
if tx.GetResult().GetCode() > 0 {
return nil, fmt.Errorf("%s", string(tx.GetResult().GetMessage()))
}
return tx, err
}
// DeployContract deploys a new smart contract and returns the unsigned transaction.
func (g *GrpcClient) DeployContract(from, contractName string,
abi *core.SmartContract_ABI, codeStr string,
feeLimit, curPercent, oeLimit int64,
) (*api.TransactionExtention, error) {
ctx, cancel := g.newContext()
defer cancel()
return g.DeployContractCtx(ctx, from, contractName, abi, codeStr, feeLimit, curPercent, oeLimit)
}
// DeployContractCtx is the context-aware version of DeployContract.
func (g *GrpcClient) DeployContractCtx(ctx context.Context, from, contractName string,
abi *core.SmartContract_ABI, codeStr string,
feeLimit, curPercent, oeLimit int64,
) (*api.TransactionExtention, error) {
ctx = g.withAPIKey(ctx)
var err error
fromDesc, err := address.Base58ToAddress(from)
if err != nil {
return nil, err
}
if curPercent > 100 || curPercent < 0 {
return nil, fmt.Errorf("consume_user_resource_percent should be >= 0 and <= 100")
}
if oeLimit <= 0 {
return nil, fmt.Errorf("origin_energy_limit must > 0")
}
bc, err := common.FromHex(codeStr)
if err != nil {
return nil, err
}
ct := &core.CreateSmartContract{
OwnerAddress: fromDesc.Bytes(),
NewContract: &core.SmartContract{
OriginAddress: fromDesc.Bytes(),
Abi: abi,
Name: contractName,
ConsumeUserResourcePercent: curPercent,
OriginEnergyLimit: oeLimit,
Bytecode: bc,
},
}
tx, err := g.Client.DeployContract(ctx, ct)
if err != nil {
return nil, err
}
// A rejected deployment comes back with a nil gRPC error, a non-zero result
// code and no Transaction, so the fee-limit assignment below would panic
// instead of surfacing the node's reason for the rejection.
if tx.GetResult().GetCode() != 0 {
return nil, fmt.Errorf("%s", tx.GetResult().GetMessage())
}
if tx.GetTransaction().GetRawData() == nil {
return nil, fmt.Errorf("deploy contract: node returned no transaction")
}
if feeLimit > 0 {
tx.Transaction.RawData.FeeLimit = feeLimit
// update hash
err = g.UpdateHash(tx)
}
return tx, err
}
// UpdateHash recalculates the transaction hash after local modifications (e.g. setting fee limit).
func (g *GrpcClient) UpdateHash(tx *api.TransactionExtention) error {
return tx.UpdateHash()
}
// GetContractABI returns the ABI of a deployed smart contract.
func (g *GrpcClient) GetContractABI(contractAddress string) (*core.SmartContract_ABI, error) {
ctx, cancel := g.newContext()
defer cancel()
return g.GetContractABICtx(ctx, contractAddress)
}
// GetContractABICtx is the context-aware version of GetContractABI.
func (g *GrpcClient) GetContractABICtx(ctx context.Context, contractAddress string) (*core.SmartContract_ABI, error) {
ctx = g.withAPIKey(ctx)
var err error
contractDesc, err := address.Base58ToAddress(contractAddress)
if err != nil {
return nil, err
}
sm, err := g.Client.GetContract(ctx, GetMessageBytes(contractDesc))
if err != nil {
return nil, err
}
if sm == nil {
return nil, fmt.Errorf("invalid contract abi")
}
return sm.Abi, nil
}
// proxySelectors lists the EVM function selectors tried (in order) when
// resolving a proxy contract's implementation address. Each entry is a
// 4-byte keccak256 prefix of a well-known getter exposed by different
// proxy patterns.
var proxySelectors = [][4]byte{
{0x5c, 0x60, 0xda, 0x1b}, // implementation() — ERC-1967 / OpenZeppelin / UUPS
{0xbb, 0x82, 0xaa, 0x5e}, // comptrollerImplementation() — Compound-style (Unitroller, etc.)
{0xaa, 0xf1, 0x0f, 0x42}, // getImplementation() — alternate proxy getter
{0xa6, 0x19, 0x48, 0x6e}, // masterCopy() — Gnosis Safe / GnosisSafeProxy
}
// zeroEVMAddr is a pre-allocated zero address used by callForAddress to
// detect invalid implementation addresses without allocating on each call.
var zeroEVMAddr [20]byte
// GetContractABIResolved returns the ABI for a contract, resolving proxy
// contracts transparently. It first calls GetContractABI on the given
// address; if the returned ABI has no entries, or if the ABI looks like a
// proxy-only ABI (contains an "implementation" function), it attempts to
// detect a proxy by trying several well-known proxy getter selectors
// (implementation(), comptrollerImplementation(), getImplementation(),
// masterCopy()). On success it fetches the ABI from the implementation
// contract instead.
//
// Only a single level of proxy indirection is resolved; chained proxies
// (proxy → proxy → implementation) are not followed.
func (g *GrpcClient) GetContractABIResolved(contractAddress string) (*core.SmartContract_ABI, error) {
ctx, cancel := g.newContext()
defer cancel()
return g.GetContractABIResolvedCtx(ctx, contractAddress)
}
// GetContractABIResolvedCtx is the context-aware version of GetContractABIResolved.
func (g *GrpcClient) GetContractABIResolvedCtx(ctx context.Context, contractAddress string) (*core.SmartContract_ABI, error) {
ctx = g.withAPIKey(ctx)
contractABI, err := g.GetContractABICtx(ctx, contractAddress)
if err != nil {
return nil, err
}
if len(contractABI.GetEntrys()) > 0 && !isProxyABI(contractABI) {
return contractABI, nil
}
implAddr, err := g.getProxyImplementation(ctx, contractAddress)
if err != nil || implAddr == "" {
// Not a recognised proxy — return the original ABI.
return contractABI, nil
}
implABI, err := g.GetContractABICtx(ctx, implAddr)
if err != nil {
return contractABI, nil
}
if len(implABI.GetEntrys()) == 0 {
return contractABI, nil
}
return implABI, nil
}
// isProxyABI reports whether the given ABI looks like a proxy contract ABI
// rather than a real business-logic ABI. It returns true when the ABI
// declares a function matching one of the well-known proxy getter names.
//
// This is a heuristic: a non-proxy contract with a matching function name
// would trigger proxy resolution, but the fallback logic in
// GetContractABIResolved ensures the original ABI is returned if resolution
// fails or produces no improvement.
func isProxyABI(contractABI *core.SmartContract_ABI) bool {
for _, entry := range contractABI.GetEntrys() {
if entry.GetType() != core.SmartContract_ABI_Entry_Function {
continue
}
switch entry.GetName() {
case "implementation", "comptrollerImplementation", "getImplementation", "masterCopy":
return true
}
}
return false
}
// getProxyImplementation tries multiple well-known getter selectors to
// discover the implementation address behind a proxy contract. Returns the
// implementation address in Base58 format, or an empty string if no
// strategy succeeds.
func (g *GrpcClient) getProxyImplementation(ctx context.Context, contractAddress string) (string, error) {
contractDesc, err := address.Base58ToAddress(contractAddress)
if err != nil {
return "", err
}
contractBytes := contractDesc.Bytes()
ownerBytes := defaultFromAddress.Bytes()
for _, sel := range proxySelectors {
addr := g.callForAddress(ctx, ownerBytes, contractBytes, sel[:])
if addr != "" {
return addr, nil
}
}
return "", nil
}
// callForAddress sends a constant contract call with the given data and
// interprets the result as an ABI-encoded address. Returns the Base58
// Tron address on success, or an empty string if the call fails or
// returns a zero/invalid address.
func (g *GrpcClient) callForAddress(ctx context.Context, ownerBytes, contractBytes, data []byte) string {
ct := &core.TriggerSmartContract{
OwnerAddress: ownerBytes,
ContractAddress: contractBytes,
Data: data,
}
tx, err := g.triggerConstantContract(ctx, ct)
if err != nil || tx == nil {
return ""
}
if res := tx.GetResult(); res == nil || res.GetCode() != 0 || !res.GetResult() {
return ""
}
if len(tx.GetConstantResult()) == 0 || len(tx.GetConstantResult()[0]) < 32 {
return ""
}
// The result is an ABI-encoded address: 12 bytes zero-padding followed
// by the 20-byte EVM address. Extract bytes [12:32] rather than
// using the tail, so oversized responses are handled correctly.
result := tx.GetConstantResult()[0]
evmAddr := result[12:32]
// Check for zero address — not a valid implementation.
if bytes.Equal(evmAddr, zeroEVMAddr[:]) {
return ""
}
tronAddr := make([]byte, 0, address.AddressLength)
tronAddr = append(tronAddr, address.TronBytePrefix)
tronAddr = append(tronAddr, evmAddr...)
return address.Address(tronAddr).String()
}