Merge pull request #89 from 8thlight/rename-watched-contract-to-contract

Rename watched contract to contract
This commit is contained in:
ericmeyer 2017-12-05 10:08:10 -06:00 committed by GitHub
commit f496303f15
22 changed files with 208 additions and 227 deletions

View File

@ -10,8 +10,8 @@ import (
"math/big" "math/big"
"github.com/8thlight/vulcanizedb/cmd" "github.com/8thlight/vulcanizedb/cmd"
"github.com/8thlight/vulcanizedb/pkg/contract_summary"
"github.com/8thlight/vulcanizedb/pkg/geth" "github.com/8thlight/vulcanizedb/pkg/geth"
"github.com/8thlight/vulcanizedb/pkg/watched_contracts"
) )
func main() { func main() {
@ -24,11 +24,11 @@ func main() {
repository := cmd.LoadPostgres(config.Database) repository := cmd.LoadPostgres(config.Database)
blockNumber := requestedBlockNumber(_blockNumber) blockNumber := requestedBlockNumber(_blockNumber)
contractSummary, err := watched_contracts.NewSummary(blockchain, repository, *contractHash, blockNumber) contractSummary, err := contract_summary.NewSummary(blockchain, repository, *contractHash, blockNumber)
if err != nil { if err != nil {
log.Fatalln(err) log.Fatalln(err)
} }
output := watched_contracts.GenerateConsoleOutput(contractSummary) output := contract_summary.GenerateConsoleOutput(contractSummary)
fmt.Println(output) fmt.Println(output)
} }

View File

@ -4,7 +4,7 @@ import (
"flag" "flag"
"github.com/8thlight/vulcanizedb/cmd" "github.com/8thlight/vulcanizedb/cmd"
"github.com/8thlight/vulcanizedb/pkg/repositories" "github.com/8thlight/vulcanizedb/pkg/core"
) )
func main() { func main() {
@ -14,9 +14,9 @@ func main() {
flag.Parse() flag.Parse()
config := cmd.LoadConfig(*environment) config := cmd.LoadConfig(*environment)
repository := cmd.LoadPostgres(config.Database) repository := cmd.LoadPostgres(config.Database)
watchedContract := repositories.WatchedContract{ watchedContract := core.Contract{
Abi: cmd.ReadAbiFile(*abiFilepath), Abi: cmd.ReadAbiFile(*abiFilepath),
Hash: *contractHash, Hash: *contractHash,
} }
repository.CreateWatchedContract(watchedContract) repository.CreateContract(watchedContract)
} }

View File

@ -1,4 +1,4 @@
package watched_contracts package contract_summary
import ( import (
"fmt" "fmt"

View File

@ -0,0 +1,13 @@
package contract_summary_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestContractSummary(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "ContractSummary Suite")
}

View File

@ -1,4 +1,4 @@
package watched_contracts package contract_summary
import ( import (
"errors" "errors"
@ -11,25 +11,25 @@ import (
) )
type ContractSummary struct { type ContractSummary struct {
Contract core.Contract
ContractHash string
NumberOfTransactions int
LastTransaction *core.Transaction
blockChain core.Blockchain
Attributes core.ContractAttributes Attributes core.ContractAttributes
BlockNumber *big.Int BlockNumber *big.Int
Contract core.Contract
ContractHash string
LastTransaction *core.Transaction
NumberOfTransactions int
blockChain core.Blockchain
} }
var NewContractNotWatchedErr = func(contractHash string) error { var ErrContractDoesNotExist = func(contractHash string) error {
return errors.New(fmt.Sprintf("Contract %v not being watched", contractHash)) return errors.New(fmt.Sprintf("Contract %v does not exist", contractHash))
} }
func NewSummary(blockchain core.Blockchain, repository repositories.Repository, contractHash string, blockNumber *big.Int) (ContractSummary, error) { func NewSummary(blockchain core.Blockchain, repository repositories.Repository, contractHash string, blockNumber *big.Int) (ContractSummary, error) {
watchedContract := repository.FindWatchedContract(contractHash) contract := repository.FindContract(contractHash)
if watchedContract != nil { if contract != nil {
return newContractSummary(blockchain, *watchedContract, blockNumber), nil return newContractSummary(blockchain, *contract, blockNumber), nil
} else { } else {
return ContractSummary{}, NewContractNotWatchedErr(contractHash) return ContractSummary{}, ErrContractDoesNotExist(contractHash)
} }
} }
@ -39,22 +39,22 @@ func (contractSummary ContractSummary) GetStateAttribute(attributeName string) i
return result return result
} }
func newContractSummary(blockchain core.Blockchain, watchedContract repositories.WatchedContract, blockNumber *big.Int) ContractSummary { func newContractSummary(blockchain core.Blockchain, contract core.Contract, blockNumber *big.Int) ContractSummary {
contract, _ := blockchain.GetContract(watchedContract.Hash) attributes, _ := blockchain.GetAttributes(contract)
return ContractSummary{ return ContractSummary{
blockChain: blockchain, Attributes: attributes,
Contract: contract,
ContractHash: watchedContract.Hash,
NumberOfTransactions: len(watchedContract.Transactions),
LastTransaction: lastTransaction(watchedContract),
Attributes: contract.Attributes,
BlockNumber: blockNumber, BlockNumber: blockNumber,
Contract: contract,
ContractHash: contract.Hash,
LastTransaction: lastTransaction(contract),
NumberOfTransactions: len(contract.Transactions),
blockChain: blockchain,
} }
} }
func lastTransaction(watchedContract repositories.WatchedContract) *core.Transaction { func lastTransaction(contract core.Contract) *core.Transaction {
if len(watchedContract.Transactions) > 0 { if len(contract.Transactions) > 0 {
return &watchedContract.Transactions[0] return &contract.Transactions[0]
} else { } else {
return nil return nil
} }

View File

@ -1,51 +1,51 @@
package watched_contracts_test package contract_summary_test
import ( import (
"math/big" "math/big"
"github.com/8thlight/vulcanizedb/pkg/contract_summary"
"github.com/8thlight/vulcanizedb/pkg/core" "github.com/8thlight/vulcanizedb/pkg/core"
"github.com/8thlight/vulcanizedb/pkg/fakes" "github.com/8thlight/vulcanizedb/pkg/fakes"
"github.com/8thlight/vulcanizedb/pkg/repositories" "github.com/8thlight/vulcanizedb/pkg/repositories"
"github.com/8thlight/vulcanizedb/pkg/watched_contracts"
. "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
) )
func NewCurrentContractSummary(blockchain core.Blockchain, repository repositories.Repository, contractHash string) (watched_contracts.ContractSummary, error) { func NewCurrentContractSummary(blockchain core.Blockchain, repository repositories.Repository, contractHash string) (contract_summary.ContractSummary, error) {
return watched_contracts.NewSummary(blockchain, repository, contractHash, nil) return contract_summary.NewSummary(blockchain, repository, contractHash, nil)
} }
var _ = Describe("The watched contract summary", func() { var _ = Describe("The contract summary", func() {
Context("when the given contract is not being watched", func() { Context("when the given contract does not exist", func() {
It("returns an error", func() { It("returns an error", func() {
repository := repositories.NewInMemory() repository := repositories.NewInMemory()
blockchain := fakes.NewBlockchain() blockchain := fakes.NewBlockchain()
contractSummary, err := NewCurrentContractSummary(blockchain, repository, "0x123") contractSummary, err := NewCurrentContractSummary(blockchain, repository, "0x123")
Expect(contractSummary).To(Equal(watched_contracts.ContractSummary{})) Expect(contractSummary).To(Equal(contract_summary.ContractSummary{}))
Expect(err).NotTo(BeNil()) Expect(err).NotTo(BeNil())
}) })
}) })
Context("when the given contract is being watched", func() { Context("when the given contract exists", func() {
It("returns the summary", func() { It("returns the summary", func() {
repository := repositories.NewInMemory() repository := repositories.NewInMemory()
watchedContract := repositories.WatchedContract{Hash: "0x123"} contract := core.Contract{Hash: "0x123"}
repository.CreateWatchedContract(watchedContract) repository.CreateContract(contract)
blockchain := fakes.NewBlockchain() blockchain := fakes.NewBlockchain()
contractSummary, err := NewCurrentContractSummary(blockchain, repository, "0x123") contractSummary, err := NewCurrentContractSummary(blockchain, repository, "0x123")
Expect(contractSummary).NotTo(Equal(watched_contracts.ContractSummary{})) Expect(contractSummary).NotTo(Equal(contract_summary.ContractSummary{}))
Expect(err).To(BeNil()) Expect(err).To(BeNil())
}) })
It("includes the contract hash in the summary", func() { It("includes the contract hash in the summary", func() {
repository := repositories.NewInMemory() repository := repositories.NewInMemory()
watchedContract := repositories.WatchedContract{Hash: "0x123"} contract := core.Contract{Hash: "0x123"}
repository.CreateWatchedContract(watchedContract) repository.CreateContract(contract)
blockchain := fakes.NewBlockchain() blockchain := fakes.NewBlockchain()
contractSummary, _ := NewCurrentContractSummary(blockchain, repository, "0x123") contractSummary, _ := NewCurrentContractSummary(blockchain, repository, "0x123")
@ -55,8 +55,8 @@ var _ = Describe("The watched contract summary", func() {
It("sets the number of transactions", func() { It("sets the number of transactions", func() {
repository := repositories.NewInMemory() repository := repositories.NewInMemory()
watchedContract := repositories.WatchedContract{Hash: "0x123"} contract := core.Contract{Hash: "0x123"}
repository.CreateWatchedContract(watchedContract) repository.CreateContract(contract)
block := core.Block{ block := core.Block{
Transactions: []core.Transaction{ Transactions: []core.Transaction{
{To: "0x123"}, {To: "0x123"},
@ -73,8 +73,8 @@ var _ = Describe("The watched contract summary", func() {
It("sets the last transaction", func() { It("sets the last transaction", func() {
repository := repositories.NewInMemory() repository := repositories.NewInMemory()
watchedContract := repositories.WatchedContract{Hash: "0x123"} contract := core.Contract{Hash: "0x123"}
repository.CreateWatchedContract(watchedContract) repository.CreateContract(contract)
block := core.Block{ block := core.Block{
Transactions: []core.Transaction{ Transactions: []core.Transaction{
{Hash: "TRANSACTION2", To: "0x123"}, {Hash: "TRANSACTION2", To: "0x123"},
@ -91,8 +91,8 @@ var _ = Describe("The watched contract summary", func() {
It("gets contract state attribute for the contract from the blockchain", func() { It("gets contract state attribute for the contract from the blockchain", func() {
repository := repositories.NewInMemory() repository := repositories.NewInMemory()
watchedContract := repositories.WatchedContract{Hash: "0x123"} contract := core.Contract{Hash: "0x123"}
repository.CreateWatchedContract(watchedContract) repository.CreateContract(contract)
blockchain := fakes.NewBlockchain() blockchain := fakes.NewBlockchain()
blockchain.SetContractStateAttribute("0x123", nil, "foo", "bar") blockchain.SetContractStateAttribute("0x123", nil, "foo", "bar")
@ -104,14 +104,14 @@ var _ = Describe("The watched contract summary", func() {
It("gets contract state attribute for the contract from the blockchain at specific block height", func() { It("gets contract state attribute for the contract from the blockchain at specific block height", func() {
repository := repositories.NewInMemory() repository := repositories.NewInMemory()
watchedContract := repositories.WatchedContract{Hash: "0x123"} contract := core.Contract{Hash: "0x123"}
repository.CreateWatchedContract(watchedContract) repository.CreateContract(contract)
blockchain := fakes.NewBlockchain() blockchain := fakes.NewBlockchain()
blockNumber := big.NewInt(1000) blockNumber := big.NewInt(1000)
blockchain.SetContractStateAttribute("0x123", nil, "foo", "bar") blockchain.SetContractStateAttribute("0x123", nil, "foo", "bar")
blockchain.SetContractStateAttribute("0x123", blockNumber, "foo", "baz") blockchain.SetContractStateAttribute("0x123", blockNumber, "foo", "baz")
contractSummary, _ := watched_contracts.NewSummary(blockchain, repository, "0x123", blockNumber) contractSummary, _ := contract_summary.NewSummary(blockchain, repository, "0x123", blockNumber)
attribute := contractSummary.GetStateAttribute("foo") attribute := contractSummary.GetStateAttribute("foo")
Expect(attribute).To(Equal("baz")) Expect(attribute).To(Equal("baz"))
@ -119,8 +119,8 @@ var _ = Describe("The watched contract summary", func() {
It("gets attributes for the contract from the blockchain", func() { It("gets attributes for the contract from the blockchain", func() {
repository := repositories.NewInMemory() repository := repositories.NewInMemory()
watchedContract := repositories.WatchedContract{Hash: "0x123"} contract := core.Contract{Hash: "0x123"}
repository.CreateWatchedContract(watchedContract) repository.CreateContract(contract)
blockchain := fakes.NewBlockchain() blockchain := fakes.NewBlockchain()
blockchain.SetContractStateAttribute("0x123", nil, "foo", "bar") blockchain.SetContractStateAttribute("0x123", nil, "foo", "bar")
blockchain.SetContractStateAttribute("0x123", nil, "baz", "bar") blockchain.SetContractStateAttribute("0x123", nil, "baz", "bar")

View File

@ -7,6 +7,6 @@ type Blockchain interface {
SubscribeToBlocks(blocks chan Block) SubscribeToBlocks(blocks chan Block)
StartListening() StartListening()
StopListening() StopListening()
GetContract(contractHash string) (Contract, error) GetAttributes(contract Contract) (ContractAttributes, error)
GetAttribute(contract Contract, attributeName string, blockNumber *big.Int) (interface{}, error) GetAttribute(contract Contract, attributeName string, blockNumber *big.Int) (interface{}, error)
} }

View File

@ -1,25 +1,7 @@
package core package core
type Contract struct { type Contract struct {
Attributes ContractAttributes Abi string
Hash string Hash string
} Transactions []Transaction
type ContractAttribute struct {
Name string
Type string
}
type ContractAttributes []ContractAttribute
func (attributes ContractAttributes) Len() int {
return len(attributes)
}
func (attributes ContractAttributes) Swap(i, j int) {
attributes[i], attributes[j] = attributes[j], attributes[i]
}
func (attributes ContractAttributes) Less(i, j int) bool {
return attributes[i].Name < attributes[j].Name
} }

View File

@ -0,0 +1,20 @@
package core
type ContractAttribute struct {
Name string
Type string
}
type ContractAttributes []ContractAttribute
func (attributes ContractAttributes) Len() int {
return len(attributes)
}
func (attributes ContractAttributes) Swap(i, j int) {
attributes[i], attributes[j] = attributes[j], attributes[i]
}
func (attributes ContractAttributes) Less(i, j int) bool {
return attributes[i].Name < attributes[j].Name
}

View File

@ -15,15 +15,6 @@ type Blockchain struct {
WasToldToStop bool WasToldToStop bool
} }
func (blockchain *Blockchain) GetContract(contractHash string) (core.Contract, error) {
contractAttributes, err := blockchain.getContractAttributes(contractHash)
contract := core.Contract{
Attributes: contractAttributes,
Hash: contractHash,
}
return contract, err
}
func (blockchain *Blockchain) GetAttribute(contract core.Contract, attributeName string, blockNumber *big.Int) (interface{}, error) { func (blockchain *Blockchain) GetAttribute(contract core.Contract, attributeName string, blockNumber *big.Int) (interface{}, error) {
var result interface{} var result interface{}
if blockNumber == nil { if blockNumber == nil {
@ -84,9 +75,9 @@ func (blockchain *Blockchain) SetContractStateAttribute(contractHash string, blo
blockchain.contractAttributes[key][attributeName] = attributeValue blockchain.contractAttributes[key][attributeName] = attributeValue
} }
func (blockchain *Blockchain) getContractAttributes(contractHash string) (core.ContractAttributes, error) { func (blockchain *Blockchain) GetAttributes(contract core.Contract) (core.ContractAttributes, error) {
var contractAttributes core.ContractAttributes var contractAttributes core.ContractAttributes
attributes, ok := blockchain.contractAttributes[contractHash+"-1"] attributes, ok := blockchain.contractAttributes[contract.Hash+"-1"]
if ok { if ok {
for key, _ := range attributes { for key, _ := range attributes {
contractAttributes = append(contractAttributes, core.ContractAttribute{Name: key, Type: "string"}) contractAttributes = append(contractAttributes, core.ContractAttribute{Name: key, Type: "string"})

View File

@ -18,6 +18,10 @@ func ParseAbiFile(abiFilePath string) (abi.ABI, error) {
if err != nil { if err != nil {
return abi.ABI{}, ErrMissingAbiFile return abi.ABI{}, ErrMissingAbiFile
} }
return ParseAbi(abiString)
}
func ParseAbi(abiString string) (abi.ABI, error) {
parsedAbi, err := abi.JSON(strings.NewReader(abiString)) parsedAbi, err := abi.JSON(strings.NewReader(abiString))
if err != nil { if err != nil {
return abi.ABI{}, ErrInvalidAbiFile return abi.ABI{}, ErrInvalidAbiFile

View File

@ -13,7 +13,6 @@ import (
"github.com/8thlight/vulcanizedb/pkg/config" "github.com/8thlight/vulcanizedb/pkg/config"
"github.com/8thlight/vulcanizedb/pkg/core" "github.com/8thlight/vulcanizedb/pkg/core"
"github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
) )
@ -21,30 +20,8 @@ var (
ErrInvalidStateAttribute = errors.New("invalid state attribute") ErrInvalidStateAttribute = errors.New("invalid state attribute")
) )
func (blockchain *GethBlockchain) GetContract(contractHash string) (core.Contract, error) {
attributes, err := blockchain.getContractAttributes(contractHash)
if err != nil {
return core.Contract{}, err
} else {
contract := core.Contract{
Attributes: attributes,
Hash: contractHash,
}
return contract, nil
}
}
func (blockchain *GethBlockchain) getParseAbi(contract core.Contract) (abi.ABI, error) {
abiFilePath := filepath.Join(config.ProjectRoot(), "contracts", "public", fmt.Sprintf("%s.json", contract.Hash))
parsed, err := ParseAbiFile(abiFilePath)
if err != nil {
return abi.ABI{}, err
}
return parsed, nil
}
func (blockchain *GethBlockchain) GetAttribute(contract core.Contract, attributeName string, blockNumber *big.Int) (interface{}, error) { func (blockchain *GethBlockchain) GetAttribute(contract core.Contract, attributeName string, blockNumber *big.Int) (interface{}, error) {
parsed, err := blockchain.getParseAbi(contract) parsed, err := ParseAbi(contract.Abi)
var result interface{} var result interface{}
if err != nil { if err != nil {
return result, err return result, err
@ -53,7 +30,7 @@ func (blockchain *GethBlockchain) GetAttribute(contract core.Contract, attribute
if err != nil { if err != nil {
return nil, ErrInvalidStateAttribute return nil, ErrInvalidStateAttribute
} }
output, err := callContract(contract, input, err, blockchain, blockNumber) output, err := callContract(contract.Hash, input, blockchain, blockNumber)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -63,13 +40,27 @@ func (blockchain *GethBlockchain) GetAttribute(contract core.Contract, attribute
} }
return result, nil return result, nil
} }
func callContract(contract core.Contract, input []byte, err error, blockchain *GethBlockchain, blockNumber *big.Int) ([]byte, error) {
to := common.HexToAddress(contract.Hash) func callContract(contractHash string, input []byte, blockchain *GethBlockchain, blockNumber *big.Int) ([]byte, error) {
to := common.HexToAddress(contractHash)
msg := ethereum.CallMsg{To: &to, Data: input} msg := ethereum.CallMsg{To: &to, Data: input}
return blockchain.client.CallContract(context.Background(), msg, blockNumber) return blockchain.client.CallContract(context.Background(), msg, blockNumber)
} }
func (blockchain *GethBlockchain) getContractAttributes(contractHash string) (core.ContractAttributes, error) { func (blockchain *GethBlockchain) GetAttributes(contract core.Contract) (core.ContractAttributes, error) {
parsed, _ := ParseAbi(contract.Abi)
var contractAttributes core.ContractAttributes
for _, abiElement := range parsed.Methods {
if (len(abiElement.Outputs) > 0) && (len(abiElement.Inputs) == 0) && abiElement.Const {
attributeType := abiElement.Outputs[0].Type.String()
contractAttributes = append(contractAttributes, core.ContractAttribute{abiElement.Name, attributeType})
}
}
sort.Sort(contractAttributes)
return contractAttributes, nil
}
func (blockchain *GethBlockchain) GetContractAttributesOld(contractHash string) (core.ContractAttributes, error) {
abiFilePath := filepath.Join(config.ProjectRoot(), "contracts", "public", fmt.Sprintf("%s.json", contractHash)) abiFilePath := filepath.Join(config.ProjectRoot(), "contracts", "public", fmt.Sprintf("%s.json", contractHash))
parsed, _ := ParseAbiFile(abiFilePath) parsed, _ := ParseAbiFile(abiFilePath)
var contractAttributes core.ContractAttributes var contractAttributes core.ContractAttributes

View File

@ -16,13 +16,13 @@ package geth_test
// It("returns a string attribute for a real contract", func() { // It("returns a string attribute for a real contract", func() {
// config, _ := cfg.NewConfig("public") // config, _ := cfg.NewConfig("public")
// blockchain := geth.NewGethBlockchain(config.Client.IPCPath) // blockchain := geth.NewGethBlockchain(config.Client.IPCPath)
// contractHash := "0xd26114cd6EE289AccF82350c8d8487fedB8A0C07" // contract := testing.SampleContract()
// //
// contract, err := blockchain.GetContract(contractHash) // contractAttributes, err := blockchain.GetAttributes(contract)
// //
// Expect(err).To(BeNil()) // Expect(err).To(BeNil())
// Expect(len(contract.Attributes)).NotTo(Equal(0)) // Expect(len(contractAttributes)).NotTo(Equal(0))
// symbolAttribute := *testing.FindAttribute(contract.Attributes, "symbol") // symbolAttribute := *testing.FindAttribute(contractAttributes, "symbol")
// Expect(symbolAttribute.Name).To(Equal("symbol")) // Expect(symbolAttribute.Name).To(Equal("symbol"))
// Expect(symbolAttribute.Type).To(Equal("string")) // Expect(symbolAttribute.Type).To(Equal("string"))
// }) // })
@ -30,24 +30,24 @@ package geth_test
// It("does not return an attribute that takes an input", func() { // It("does not return an attribute that takes an input", func() {
// config, _ := cfg.NewConfig("public") // config, _ := cfg.NewConfig("public")
// blockchain := geth.NewGethBlockchain(config.Client.IPCPath) // blockchain := geth.NewGethBlockchain(config.Client.IPCPath)
// contractHash := "0xd26114cd6EE289AccF82350c8d8487fedB8A0C07" // contract := testing.SampleContract()
// //
// contract, err := blockchain.GetContract(contractHash) // contractAttributes, err := blockchain.GetAttributes(contract)
// //
// Expect(err).To(BeNil()) // Expect(err).To(BeNil())
// attribute := testing.FindAttribute(contract.Attributes, "balanceOf") // attribute := testing.FindAttribute(contractAttributes, "balanceOf")
// Expect(attribute).To(BeNil()) // Expect(attribute).To(BeNil())
// }) // })
// //
// It("does not return an attribute that is not constant", func() { // It("does not return an attribute that is not constant", func() {
// config, _ := cfg.NewConfig("public") // config, _ := cfg.NewConfig("public")
// blockchain := geth.NewGethBlockchain(config.Client.IPCPath) // blockchain := geth.NewGethBlockchain(config.Client.IPCPath)
// contractHash := "0xd26114cd6EE289AccF82350c8d8487fedB8A0C07" // contract := testing.SampleContract()
// //
// contract, err := blockchain.GetContract(contractHash) // contractAttributes, err := blockchain.GetAttributes(contract)
// //
// Expect(err).To(BeNil()) // Expect(err).To(BeNil())
// attribute := testing.FindAttribute(contract.Attributes, "unpause") // attribute := testing.FindAttribute(contractAttributes, "unpause")
// Expect(attribute).To(BeNil()) // Expect(attribute).To(BeNil())
// }) // })
// }) // })
@ -56,9 +56,8 @@ package geth_test
// It("returns the correct attribute for a real contract", func() { // It("returns the correct attribute for a real contract", func() {
// config, _ := cfg.NewConfig("public") // config, _ := cfg.NewConfig("public")
// blockchain := geth.NewGethBlockchain(config.Client.IPCPath) // blockchain := geth.NewGethBlockchain(config.Client.IPCPath)
// contractHash := "0xd26114cd6EE289AccF82350c8d8487fedB8A0C07"
// //
// contract, _ := blockchain.GetContract(contractHash) // contract := testing.SampleContract()
// name, err := blockchain.GetAttribute(contract, "name", nil) // name, err := blockchain.GetAttribute(contract, "name", nil)
// //
// Expect(err).To(BeNil()) // Expect(err).To(BeNil())
@ -68,9 +67,8 @@ package geth_test
// It("returns the correct attribute for a real contract", func() { // It("returns the correct attribute for a real contract", func() {
// config, _ := cfg.NewConfig("public") // config, _ := cfg.NewConfig("public")
// blockchain := geth.NewGethBlockchain(config.Client.IPCPath) // blockchain := geth.NewGethBlockchain(config.Client.IPCPath)
// contractHash := "0xd26114cd6EE289AccF82350c8d8487fedB8A0C07" // contract := testing.SampleContract()
// //
// contract, _ := blockchain.GetContract(contractHash)
// name, err := blockchain.GetAttribute(contract, "name", nil) // name, err := blockchain.GetAttribute(contract, "name", nil)
// //
// Expect(err).To(BeNil()) // Expect(err).To(BeNil())
@ -80,33 +78,19 @@ package geth_test
// It("returns the correct attribute for a real contract at a specific block height", func() { // It("returns the correct attribute for a real contract at a specific block height", func() {
// config, _ := cfg.NewConfig("public") // config, _ := cfg.NewConfig("public")
// blockchain := geth.NewGethBlockchain(config.Client.IPCPath) // blockchain := geth.NewGethBlockchain(config.Client.IPCPath)
// contractHash := "0xd26114cd6EE289AccF82350c8d8487fedB8A0C07" // contract := testing.SampleContract()
// //
// contract, _ := blockchain.GetContract(contractHash)
// name, err := blockchain.GetAttribute(contract, "name", big.NewInt(4652791)) // name, err := blockchain.GetAttribute(contract, "name", big.NewInt(4652791))
// //
// Expect(name).To(Equal("OMGToken")) // Expect(name).To(Equal("OMGToken"))
// Expect(err).To(BeNil()) // Expect(err).To(BeNil())
// }) // })
// //
// It("returns an error when there is no ABI for the given contract", func() {
// config, _ := cfg.NewConfig("public")
// blockchain := geth.NewGethBlockchain(config.Client.IPCPath)
// contractHash := "MISSINGHASH"
//
// contract, _ := blockchain.GetContract(contractHash)
// name, err := blockchain.GetAttribute(contract, "name", nil)
//
// Expect(err).To(Equal(geth.ErrMissingAbiFile))
// Expect(name).To(BeNil())
// })
//
// It("returns an error when asking for an attribute that does not exist", func() { // It("returns an error when asking for an attribute that does not exist", func() {
// config, _ := cfg.NewConfig("public") // config, _ := cfg.NewConfig("public")
// blockchain := geth.NewGethBlockchain(config.Client.IPCPath) // blockchain := geth.NewGethBlockchain(config.Client.IPCPath)
// contractHash := "0xd26114cd6EE289AccF82350c8d8487fedB8A0C07" // contract := testing.SampleContract()
// //
// contract, _ := blockchain.GetContract(contractHash)
// name, err := blockchain.GetAttribute(contract, "missing_attribute", nil) // name, err := blockchain.GetAttribute(contract, "missing_attribute", nil)
// //
// Expect(err).To(Equal(geth.ErrInvalidStateAttribute)) // Expect(err).To(Equal(geth.ErrInvalidStateAttribute))

View File

@ -1,14 +0,0 @@
package testing
import (
"github.com/8thlight/vulcanizedb/pkg/core"
)
func FindAttribute(contractAttributes core.ContractAttributes, attributeName string) *core.ContractAttribute {
for _, contractAttribute := range contractAttributes {
if contractAttribute.Name == attributeName {
return &contractAttribute
}
}
return nil
}

View File

@ -0,0 +1,31 @@
package testing
import (
"path/filepath"
"github.com/8thlight/vulcanizedb/pkg/config"
"github.com/8thlight/vulcanizedb/pkg/core"
"github.com/8thlight/vulcanizedb/pkg/geth"
)
func FindAttribute(contractAttributes core.ContractAttributes, attributeName string) *core.ContractAttribute {
for _, contractAttribute := range contractAttributes {
if contractAttribute.Name == attributeName {
return &contractAttribute
}
}
return nil
}
func SampleContract() core.Contract {
return core.Contract{
Abi: sampleAbiFileContents(),
Hash: "0xd26114cd6EE289AccF82350c8d8487fedB8A0C07",
}
}
func sampleAbiFileContents() string {
abiFilepath := filepath.Join(config.ProjectRoot(), "pkg", "geth", "testing", "sample_abi.json")
abiFileContents, _ := geth.ReadAbiFile(abiFilepath)
return abiFileContents
}

View File

@ -0,0 +1 @@
[{"constant":true,"inputs":[],"name":"mintingFinished","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"unpause","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"}],"name":"mint","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"paused","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"finishMinting","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"pause","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"},{"name":"_releaseTime","type":"uint256"}],"name":"mintTimelocked","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[],"name":"MintFinished","type":"event"},{"anonymous":false,"inputs":[],"name":"Pause","type":"event"},{"anonymous":false,"inputs":[],"name":"Unpause","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}]

View File

@ -5,33 +5,33 @@ import (
) )
type InMemory struct { type InMemory struct {
blocks map[int64]*core.Block blocks map[int64]*core.Block
watchedContracts map[string]*WatchedContract contracts map[string]*core.Contract
} }
func (repository *InMemory) CreateWatchedContract(watchedContract WatchedContract) error { func (repository *InMemory) CreateContract(contract core.Contract) error {
repository.watchedContracts[watchedContract.Hash] = &watchedContract repository.contracts[contract.Hash] = &contract
return nil return nil
} }
func (repository *InMemory) IsWatchedContract(contractHash string) bool { func (repository *InMemory) ContractExists(contractHash string) bool {
_, present := repository.watchedContracts[contractHash] _, present := repository.contracts[contractHash]
return present return present
} }
func (repository *InMemory) FindWatchedContract(contractHash string) *WatchedContract { func (repository *InMemory) FindContract(contractHash string) *core.Contract {
watchedContract, ok := repository.watchedContracts[contractHash] contract, ok := repository.contracts[contractHash]
if !ok { if !ok {
return nil return nil
} }
for _, block := range repository.blocks { for _, block := range repository.blocks {
for _, transaction := range block.Transactions { for _, transaction := range block.Transactions {
if transaction.To == contractHash { if transaction.To == contractHash {
watchedContract.Transactions = append(watchedContract.Transactions, transaction) contract.Transactions = append(contract.Transactions, transaction)
} }
} }
} }
return watchedContract return contract
} }
func (repository *InMemory) MissingBlockNumbers(startingBlockNumber int64, endingBlockNumber int64) []int64 { func (repository *InMemory) MissingBlockNumbers(startingBlockNumber int64, endingBlockNumber int64) []int64 {
@ -46,8 +46,8 @@ func (repository *InMemory) MissingBlockNumbers(startingBlockNumber int64, endin
func NewInMemory() *InMemory { func NewInMemory() *InMemory {
return &InMemory{ return &InMemory{
blocks: make(map[int64]*core.Block), blocks: make(map[int64]*core.Block),
watchedContracts: make(map[string]*WatchedContract), contracts: make(map[string]*core.Contract),
} }
} }

View File

@ -31,7 +31,7 @@ func NewPostgres(databaseConfig config.Database) (Postgres, error) {
return Postgres{Db: db}, nil return Postgres{Db: db}, nil
} }
func (repository Postgres) CreateWatchedContract(contract WatchedContract) error { func (repository Postgres) CreateContract(contract core.Contract) error {
abi := contract.Abi abi := contract.Abi
var abiToInsert *string var abiToInsert *string
if abi != "" { if abi != "" {
@ -45,15 +45,15 @@ func (repository Postgres) CreateWatchedContract(contract WatchedContract) error
return nil return nil
} }
func (repository Postgres) IsWatchedContract(contractHash string) bool { func (repository Postgres) ContractExists(contractHash string) bool {
var exists bool var exists bool
repository.Db.QueryRow( repository.Db.QueryRow(
`SELECT exists(SELECT 1 FROM watched_contracts WHERE contract_hash=$1) FROM watched_contracts`, contractHash).Scan(&exists) `SELECT exists(SELECT 1 FROM watched_contracts WHERE contract_hash=$1) FROM watched_contracts`, contractHash).Scan(&exists)
return exists return exists
} }
func (repository Postgres) FindWatchedContract(contractHash string) *WatchedContract { func (repository Postgres) FindContract(contractHash string) *core.Contract {
var savedContracts []WatchedContract var savedContracts []core.Contract
contractRows, _ := repository.Db.Query( contractRows, _ := repository.Db.Query(
`SELECT contract_hash, contract_abi FROM watched_contracts WHERE contract_hash=$1`, contractHash) `SELECT contract_hash, contract_abi FROM watched_contracts WHERE contract_hash=$1`, contractHash)
savedContracts = repository.loadContract(contractRows) savedContracts = repository.loadContract(contractRows)
@ -197,15 +197,15 @@ func (repository Postgres) loadTransactions(transactionRows *sql.Rows) []core.Tr
return transactions return transactions
} }
func (repository Postgres) loadContract(contractRows *sql.Rows) []WatchedContract { func (repository Postgres) loadContract(contractRows *sql.Rows) []core.Contract {
var savedContracts []WatchedContract var savedContracts []core.Contract
for contractRows.Next() { for contractRows.Next() {
var savedContractHash string var savedContractHash string
var savedContractAbi string var savedContractAbi string
contractRows.Scan(&savedContractHash, &savedContractAbi) contractRows.Scan(&savedContractHash, &savedContractAbi)
transactionRows, _ := repository.Db.Query(`SELECT tx_hash, tx_nonce, tx_to, tx_from, tx_gaslimit, tx_gasprice, tx_value FROM transactions WHERE tx_to = $1 ORDER BY block_id desc`, savedContractHash) transactionRows, _ := repository.Db.Query(`SELECT tx_hash, tx_nonce, tx_to, tx_from, tx_gaslimit, tx_gasprice, tx_value FROM transactions WHERE tx_to = $1 ORDER BY block_id desc`, savedContractHash)
transactions := repository.loadTransactions(transactionRows) transactions := repository.loadTransactions(transactionRows)
savedContract := WatchedContract{Hash: savedContractHash, Transactions: transactions, Abi: savedContractAbi} savedContract := core.Contract{Hash: savedContractHash, Transactions: transactions, Abi: savedContractAbi}
savedContracts = append(savedContracts, savedContract) savedContracts = append(savedContracts, savedContract)
} }
return savedContracts return savedContracts

View File

@ -8,7 +8,7 @@ type Repository interface {
FindBlockByNumber(blockNumber int64) *core.Block FindBlockByNumber(blockNumber int64) *core.Block
MaxBlockNumber() int64 MaxBlockNumber() int64
MissingBlockNumbers(startingBlockNumber int64, endingBlockNumber int64) []int64 MissingBlockNumbers(startingBlockNumber int64, endingBlockNumber int64) []int64
CreateWatchedContract(contract WatchedContract) error CreateContract(contract core.Contract) error
IsWatchedContract(contractHash string) bool ContractExists(contractHash string) bool
FindWatchedContract(contractHash string) *WatchedContract FindContract(contractHash string) *core.Contract
} }

View File

@ -208,31 +208,31 @@ func AssertRepositoryBehavior(buildRepository func() repositories.Repository) {
}) })
}) })
Describe("Creating watched contracts", func() { Describe("Creating contracts", func() {
It("returns the watched contract when it exists", func() { It("returns the contract when it exists", func() {
repository.CreateWatchedContract(repositories.WatchedContract{Hash: "x123"}) repository.CreateContract(core.Contract{Hash: "x123"})
watchedContract := repository.FindWatchedContract("x123") contract := repository.FindContract("x123")
Expect(watchedContract).NotTo(BeNil()) Expect(contract).NotTo(BeNil())
Expect(watchedContract.Hash).To(Equal("x123")) Expect(contract.Hash).To(Equal("x123"))
Expect(repository.IsWatchedContract("x123")).To(BeTrue()) Expect(repository.ContractExists("x123")).To(BeTrue())
Expect(repository.IsWatchedContract("x456")).To(BeFalse()) Expect(repository.ContractExists("x456")).To(BeFalse())
}) })
It("returns nil if contract does not exist", func() { It("returns nil if contract does not exist", func() {
watchedContract := repository.FindWatchedContract("x123") contract := repository.FindContract("x123")
Expect(watchedContract).To(BeNil()) Expect(contract).To(BeNil())
}) })
It("returns empty array when no transactions 'To' a watched contract", func() { It("returns empty array when no transactions 'To' a contract", func() {
repository.CreateWatchedContract(repositories.WatchedContract{Hash: "x123"}) repository.CreateContract(core.Contract{Hash: "x123"})
watchedContract := repository.FindWatchedContract("x123") contract := repository.FindContract("x123")
Expect(watchedContract).ToNot(BeNil()) Expect(contract).ToNot(BeNil())
Expect(watchedContract.Transactions).To(BeEmpty()) Expect(contract.Transactions).To(BeEmpty())
}) })
It("returns transactions 'To' a watched contract", func() { It("returns transactions 'To' a contract", func() {
block := core.Block{ block := core.Block{
Number: 123, Number: 123,
Transactions: []core.Transaction{ Transactions: []core.Transaction{
@ -243,10 +243,10 @@ func AssertRepositoryBehavior(buildRepository func() repositories.Repository) {
} }
repository.CreateBlock(block) repository.CreateBlock(block)
repository.CreateWatchedContract(repositories.WatchedContract{Hash: "x123"}) repository.CreateContract(core.Contract{Hash: "x123"})
watchedContract := repository.FindWatchedContract("x123") contract := repository.FindContract("x123")
Expect(watchedContract).ToNot(BeNil()) Expect(contract).ToNot(BeNil())
Expect(watchedContract.Transactions).To( Expect(contract.Transactions).To(
Equal([]core.Transaction{ Equal([]core.Transaction{
{Hash: "TRANSACTION1", To: "x123"}, {Hash: "TRANSACTION1", To: "x123"},
{Hash: "TRANSACTION3", To: "x123"}, {Hash: "TRANSACTION3", To: "x123"},
@ -254,13 +254,13 @@ func AssertRepositoryBehavior(buildRepository func() repositories.Repository) {
}) })
It("stores the ABI of the contract", func() { It("stores the ABI of the contract", func() {
repository.CreateWatchedContract(repositories.WatchedContract{ repository.CreateContract(core.Contract{
Abi: "{\"some\": \"json\"}", Abi: "{\"some\": \"json\"}",
Hash: "x123", Hash: "x123",
}) })
watchedContract := repository.FindWatchedContract("x123") contract := repository.FindContract("x123")
Expect(watchedContract).ToNot(BeNil()) Expect(contract).ToNot(BeNil())
Expect(watchedContract.Abi).To(Equal("{\"some\": \"json\"}")) Expect(contract.Abi).To(Equal("{\"some\": \"json\"}"))
}) })
}) })

View File

@ -1,9 +0,0 @@
package repositories
import "github.com/8thlight/vulcanizedb/pkg/core"
type WatchedContract struct {
Abi string
Hash string
Transactions []core.Transaction
}

View File

@ -1,13 +0,0 @@
package watched_contracts_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestWatchedContracts(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "WatchedContracts Suite")
}