-
Notifications
You must be signed in to change notification settings - Fork 1
/
deployment-block.go
80 lines (65 loc) · 2.23 KB
/
deployment-block.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
package main
import (
"context"
"errors"
"github.com/NethermindEth/juno/core/felt"
"github.com/NethermindEth/starknet.go/rpc"
)
var ErrAddressIsNotContract error = errors.New("address is not a contract")
// Perform a binary search to determine the block number at which the contract at the given address
// was deployed.
// Since the starknet_getCode method has been deprecated, this uses starknet_getClassHashAt in order
// to conduct the search. If the contract has not been deployed at a given block, calling
// starknet_getClassHashAt at that block will result in an error with code 20.
func DeploymentBlock(ctx context.Context, provider *rpc.Provider, address *felt.Felt) (uint64, error) {
maxBlock, blockNumberErr := provider.BlockNumber(ctx)
if blockNumberErr != nil {
return 0, blockNumberErr
}
var minBlock uint64 = 0
midBlock := (minBlock + maxBlock) / 2
var isDeployed map[uint64]bool = make(map[uint64]bool)
isDeployedAtBlock, blockErr := ContractExistsAtBlock(ctx, provider, address, maxBlock)
if blockErr != nil {
return 0, blockErr
}
if !isDeployedAtBlock {
return 0, ErrAddressIsNotContract
}
isDeployed[maxBlock] = isDeployedAtBlock
isDeployed[minBlock], blockErr = ContractExistsAtBlock(ctx, provider, address, minBlock)
if blockErr != nil {
return 0, blockErr
}
isDeployed[midBlock], blockErr = ContractExistsAtBlock(ctx, provider, address, midBlock)
if blockErr != nil {
return 0, blockErr
}
for (maxBlock - minBlock) >= 2 {
if !isDeployed[minBlock] && !isDeployed[midBlock] {
minBlock = midBlock
} else {
maxBlock = midBlock
}
midBlock = (minBlock + maxBlock) / 2
isDeployed[midBlock], blockErr = ContractExistsAtBlock(ctx, provider, address, midBlock)
if blockErr != nil {
return 0, blockErr
}
}
if isDeployed[minBlock] {
return minBlock, nil
}
return maxBlock, nil
}
func ContractExistsAtBlock(ctx context.Context, provider *rpc.Provider, address *felt.Felt, blockNumber uint64) (bool, error) {
_, err := provider.ClassHashAt(ctx, rpc.BlockID{Number: &blockNumber}, address)
if err != nil {
// Note: No other comparison (e.g. using errors.Is) is working.
if err.Error() == rpc.ErrContractNotFound.Error() {
return false, nil
}
return false, err
}
return true, nil
}