From 9c1bb21add8125116743c832d8534c196c4297e1 Mon Sep 17 00:00:00 2001 From: Allyson-English Date: Tue, 9 Jul 2024 16:51:14 -0400 Subject: [PATCH 01/12] listen for kernal creation and store --- internal/config/settings.go | 1 + internal/contracts/entrypoint.go | 575 +++++++++++ .../services/contracts_events_consumer.go | 28 +- internal/services/event_data_models.go | 5 + migrations/00031_kernal_tbl.sql | 12 + models/boil_table_names.go | 2 + models/kernal_accounts.go | 928 ++++++++++++++++++ settings.sample.yaml | 3 +- 8 files changed, 1552 insertions(+), 2 deletions(-) create mode 100644 internal/contracts/entrypoint.go create mode 100644 migrations/00031_kernal_tbl.sql create mode 100644 models/kernal_accounts.go diff --git a/internal/config/settings.go b/internal/config/settings.go index 04396a0b..edcc102b 100644 --- a/internal/config/settings.go +++ b/internal/config/settings.go @@ -22,4 +22,5 @@ type Settings struct { BaseVehicleDataURI string `yaml:"BASE_VEHICLE_DATA_URI"` TablelandAPIGateway string `yaml:"TABLELAND_API_GATEWAY"` EthereumRPCURL string `yaml:"ETHEREUM_RPC_URL"` + EntryPointAddr string `yaml:"ENTRYPOINT_ADDR"` } diff --git a/internal/contracts/entrypoint.go b/internal/contracts/entrypoint.go new file mode 100644 index 00000000..86962001 --- /dev/null +++ b/internal/contracts/entrypoint.go @@ -0,0 +1,575 @@ +// Code generated - DO NOT EDIT. +// This file is a generated binding and any manual changes will be lost. + +package contracts + +import ( + "errors" + "math/big" + "strings" + + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/event" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = errors.New + _ = big.NewInt + _ = strings.NewReader + _ = ethereum.NotFound + _ = bind.Bind + _ = common.Big1 + _ = types.BloomLookup + _ = event.NewSubscription +) + +// PackedUserOperation is an auto generated low-level Go binding around an user-defined struct. +type PackedUserOperation struct { + Sender common.Address + Nonce *big.Int + InitCode []byte + CallData []byte + AccountGasLimits [32]byte + PreVerificationGas *big.Int + GasFees [32]byte + PaymasterAndData []byte + Signature []byte +} + +// EntrypointMetaData contains all meta data concerning the Entrypoint contract. +var EntrypointMetaData = &bind.MetaData{ + ABI: "[{\"constant\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"smartAccount\",\"type\":\"address\"}],\"name\":\"AlreadyInitialized\",\"payable\":false,\"type\":\"error\"},{\"constant\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"target\",\"type\":\"address\"}],\"name\":\"InvalidTargetAddress\",\"payable\":false,\"type\":\"error\"},{\"constant\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"smartAccount\",\"type\":\"address\"}],\"name\":\"NotInitialized\",\"payable\":false,\"type\":\"error\"},{\"constant\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"kernel\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"OwnerRegistered\",\"payable\":false,\"type\":\"event\"},{\"constant\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"ecdsaValidatorStorage\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"smartAccount\",\"type\":\"address\"}],\"name\":\"isInitialized\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"typeID\",\"type\":\"uint256\"}],\"name\":\"isModuleType\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"pure\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"sig\",\"type\":\"bytes\"}],\"name\":\"isValidSignatureWithSender\",\"outputs\":[{\"internalType\":\"bytes4\",\"name\":\"\",\"type\":\"bytes4\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"_data\",\"type\":\"bytes\"}],\"name\":\"onInstall\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"name\":\"onUninstall\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"hookData\",\"type\":\"bytes\"},{\"indexed\":false,\"internalType\":\"bool\",\"name\":\"success\",\"type\":\"bool\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"res\",\"type\":\"bytes\"}],\"name\":\"postCheck\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"msgSender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"name\":\"preCheck\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"payable\":false,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"components\":[{\"name\":\"sender\",\"type\":\"address\"},{\"name\":\"nonce\",\"type\":\"uint256\"},{\"name\":\"initCode\",\"type\":\"bytes\"},{\"name\":\"callData\",\"type\":\"bytes\"},{\"name\":\"accountGasLimits\",\"type\":\"bytes32\"},{\"name\":\"preVerificationGas\",\"type\":\"uint256\"},{\"name\":\"gasFees\",\"type\":\"bytes32\"},{\"name\":\"paymasterAndData\",\"type\":\"bytes\"},{\"name\":\"signature\",\"type\":\"bytes\"}],\"indexed\":false,\"internalType\":\"structPackedUserOperation\",\"name\":\"userOp\",\"type\":\"tuple\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"userOpHash\",\"type\":\"bytes32\"}],\"name\":\"validateUserOp\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"payable\",\"type\":\"function\"}]", +} + +// EntrypointABI is the input ABI used to generate the binding from. +// Deprecated: Use EntrypointMetaData.ABI instead. +var EntrypointABI = EntrypointMetaData.ABI + +// Entrypoint is an auto generated Go binding around an Ethereum contract. +type Entrypoint struct { + EntrypointCaller // Read-only binding to the contract + EntrypointTransactor // Write-only binding to the contract + EntrypointFilterer // Log filterer for contract events +} + +// EntrypointCaller is an auto generated read-only Go binding around an Ethereum contract. +type EntrypointCaller struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// EntrypointTransactor is an auto generated write-only Go binding around an Ethereum contract. +type EntrypointTransactor struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// EntrypointFilterer is an auto generated log filtering Go binding around an Ethereum contract events. +type EntrypointFilterer struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// EntrypointSession is an auto generated Go binding around an Ethereum contract, +// with pre-set call and transact options. +type EntrypointSession struct { + Contract *Entrypoint // Generic contract binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// EntrypointCallerSession is an auto generated read-only Go binding around an Ethereum contract, +// with pre-set call options. +type EntrypointCallerSession struct { + Contract *EntrypointCaller // Generic contract caller binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session +} + +// EntrypointTransactorSession is an auto generated write-only Go binding around an Ethereum contract, +// with pre-set transact options. +type EntrypointTransactorSession struct { + Contract *EntrypointTransactor // Generic contract transactor binding to set the session for + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// EntrypointRaw is an auto generated low-level Go binding around an Ethereum contract. +type EntrypointRaw struct { + Contract *Entrypoint // Generic contract binding to access the raw methods on +} + +// EntrypointCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. +type EntrypointCallerRaw struct { + Contract *EntrypointCaller // Generic read-only contract binding to access the raw methods on +} + +// EntrypointTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. +type EntrypointTransactorRaw struct { + Contract *EntrypointTransactor // Generic write-only contract binding to access the raw methods on +} + +// NewEntrypoint creates a new instance of Entrypoint, bound to a specific deployed contract. +func NewEntrypoint(address common.Address, backend bind.ContractBackend) (*Entrypoint, error) { + contract, err := bindEntrypoint(address, backend, backend, backend) + if err != nil { + return nil, err + } + return &Entrypoint{EntrypointCaller: EntrypointCaller{contract: contract}, EntrypointTransactor: EntrypointTransactor{contract: contract}, EntrypointFilterer: EntrypointFilterer{contract: contract}}, nil +} + +// NewEntrypointCaller creates a new read-only instance of Entrypoint, bound to a specific deployed contract. +func NewEntrypointCaller(address common.Address, caller bind.ContractCaller) (*EntrypointCaller, error) { + contract, err := bindEntrypoint(address, caller, nil, nil) + if err != nil { + return nil, err + } + return &EntrypointCaller{contract: contract}, nil +} + +// NewEntrypointTransactor creates a new write-only instance of Entrypoint, bound to a specific deployed contract. +func NewEntrypointTransactor(address common.Address, transactor bind.ContractTransactor) (*EntrypointTransactor, error) { + contract, err := bindEntrypoint(address, nil, transactor, nil) + if err != nil { + return nil, err + } + return &EntrypointTransactor{contract: contract}, nil +} + +// NewEntrypointFilterer creates a new log filterer instance of Entrypoint, bound to a specific deployed contract. +func NewEntrypointFilterer(address common.Address, filterer bind.ContractFilterer) (*EntrypointFilterer, error) { + contract, err := bindEntrypoint(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &EntrypointFilterer{contract: contract}, nil +} + +// bindEntrypoint binds a generic wrapper to an already deployed contract. +func bindEntrypoint(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := abi.JSON(strings.NewReader(EntrypointABI)) + if err != nil { + return nil, err + } + return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_Entrypoint *EntrypointRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _Entrypoint.Contract.EntrypointCaller.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_Entrypoint *EntrypointRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Entrypoint.Contract.EntrypointTransactor.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_Entrypoint *EntrypointRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _Entrypoint.Contract.EntrypointTransactor.contract.Transact(opts, method, params...) +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_Entrypoint *EntrypointCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _Entrypoint.Contract.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_Entrypoint *EntrypointTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _Entrypoint.Contract.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_Entrypoint *EntrypointTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _Entrypoint.Contract.contract.Transact(opts, method, params...) +} + +// EcdsaValidatorStorage is a free data retrieval call binding the contract method 0x20709efc. +// +// Solidity: function ecdsaValidatorStorage(address ) view returns(address owner) +func (_Entrypoint *EntrypointCaller) EcdsaValidatorStorage(opts *bind.CallOpts, arg0 common.Address) (common.Address, error) { + var out []interface{} + err := _Entrypoint.contract.Call(opts, &out, "ecdsaValidatorStorage", arg0) + + if err != nil { + return *new(common.Address), err + } + + out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) + + return out0, err + +} + +// EcdsaValidatorStorage is a free data retrieval call binding the contract method 0x20709efc. +// +// Solidity: function ecdsaValidatorStorage(address ) view returns(address owner) +func (_Entrypoint *EntrypointSession) EcdsaValidatorStorage(arg0 common.Address) (common.Address, error) { + return _Entrypoint.Contract.EcdsaValidatorStorage(&_Entrypoint.CallOpts, arg0) +} + +// EcdsaValidatorStorage is a free data retrieval call binding the contract method 0x20709efc. +// +// Solidity: function ecdsaValidatorStorage(address ) view returns(address owner) +func (_Entrypoint *EntrypointCallerSession) EcdsaValidatorStorage(arg0 common.Address) (common.Address, error) { + return _Entrypoint.Contract.EcdsaValidatorStorage(&_Entrypoint.CallOpts, arg0) +} + +// IsInitialized is a free data retrieval call binding the contract method 0xd60b347f. +// +// Solidity: function isInitialized(address smartAccount) view returns(bool) +func (_Entrypoint *EntrypointCaller) IsInitialized(opts *bind.CallOpts, smartAccount common.Address) (bool, error) { + var out []interface{} + err := _Entrypoint.contract.Call(opts, &out, "isInitialized", smartAccount) + + if err != nil { + return *new(bool), err + } + + out0 := *abi.ConvertType(out[0], new(bool)).(*bool) + + return out0, err + +} + +// IsInitialized is a free data retrieval call binding the contract method 0xd60b347f. +// +// Solidity: function isInitialized(address smartAccount) view returns(bool) +func (_Entrypoint *EntrypointSession) IsInitialized(smartAccount common.Address) (bool, error) { + return _Entrypoint.Contract.IsInitialized(&_Entrypoint.CallOpts, smartAccount) +} + +// IsInitialized is a free data retrieval call binding the contract method 0xd60b347f. +// +// Solidity: function isInitialized(address smartAccount) view returns(bool) +func (_Entrypoint *EntrypointCallerSession) IsInitialized(smartAccount common.Address) (bool, error) { + return _Entrypoint.Contract.IsInitialized(&_Entrypoint.CallOpts, smartAccount) +} + +// IsModuleType is a free data retrieval call binding the contract method 0xecd05961. +// +// Solidity: function isModuleType(uint256 typeID) pure returns(bool) +func (_Entrypoint *EntrypointCaller) IsModuleType(opts *bind.CallOpts, typeID *big.Int) (bool, error) { + var out []interface{} + err := _Entrypoint.contract.Call(opts, &out, "isModuleType", typeID) + + if err != nil { + return *new(bool), err + } + + out0 := *abi.ConvertType(out[0], new(bool)).(*bool) + + return out0, err + +} + +// IsModuleType is a free data retrieval call binding the contract method 0xecd05961. +// +// Solidity: function isModuleType(uint256 typeID) pure returns(bool) +func (_Entrypoint *EntrypointSession) IsModuleType(typeID *big.Int) (bool, error) { + return _Entrypoint.Contract.IsModuleType(&_Entrypoint.CallOpts, typeID) +} + +// IsModuleType is a free data retrieval call binding the contract method 0xecd05961. +// +// Solidity: function isModuleType(uint256 typeID) pure returns(bool) +func (_Entrypoint *EntrypointCallerSession) IsModuleType(typeID *big.Int) (bool, error) { + return _Entrypoint.Contract.IsModuleType(&_Entrypoint.CallOpts, typeID) +} + +// IsValidSignatureWithSender is a free data retrieval call binding the contract method 0xf551e2ee. +// +// Solidity: function isValidSignatureWithSender(address , bytes32 hash, bytes sig) view returns(bytes4) +func (_Entrypoint *EntrypointCaller) IsValidSignatureWithSender(opts *bind.CallOpts, arg0 common.Address, hash [32]byte, sig []byte) ([4]byte, error) { + var out []interface{} + err := _Entrypoint.contract.Call(opts, &out, "isValidSignatureWithSender", arg0, hash, sig) + + if err != nil { + return *new([4]byte), err + } + + out0 := *abi.ConvertType(out[0], new([4]byte)).(*[4]byte) + + return out0, err + +} + +// IsValidSignatureWithSender is a free data retrieval call binding the contract method 0xf551e2ee. +// +// Solidity: function isValidSignatureWithSender(address , bytes32 hash, bytes sig) view returns(bytes4) +func (_Entrypoint *EntrypointSession) IsValidSignatureWithSender(arg0 common.Address, hash [32]byte, sig []byte) ([4]byte, error) { + return _Entrypoint.Contract.IsValidSignatureWithSender(&_Entrypoint.CallOpts, arg0, hash, sig) +} + +// IsValidSignatureWithSender is a free data retrieval call binding the contract method 0xf551e2ee. +// +// Solidity: function isValidSignatureWithSender(address , bytes32 hash, bytes sig) view returns(bytes4) +func (_Entrypoint *EntrypointCallerSession) IsValidSignatureWithSender(arg0 common.Address, hash [32]byte, sig []byte) ([4]byte, error) { + return _Entrypoint.Contract.IsValidSignatureWithSender(&_Entrypoint.CallOpts, arg0, hash, sig) +} + +// OnInstall is a paid mutator transaction binding the contract method 0x6d61fe70. +// +// Solidity: function onInstall(bytes _data) payable returns() +func (_Entrypoint *EntrypointTransactor) OnInstall(opts *bind.TransactOpts, _data []byte) (*types.Transaction, error) { + return _Entrypoint.contract.Transact(opts, "onInstall", _data) +} + +// OnInstall is a paid mutator transaction binding the contract method 0x6d61fe70. +// +// Solidity: function onInstall(bytes _data) payable returns() +func (_Entrypoint *EntrypointSession) OnInstall(_data []byte) (*types.Transaction, error) { + return _Entrypoint.Contract.OnInstall(&_Entrypoint.TransactOpts, _data) +} + +// OnInstall is a paid mutator transaction binding the contract method 0x6d61fe70. +// +// Solidity: function onInstall(bytes _data) payable returns() +func (_Entrypoint *EntrypointTransactorSession) OnInstall(_data []byte) (*types.Transaction, error) { + return _Entrypoint.Contract.OnInstall(&_Entrypoint.TransactOpts, _data) +} + +// OnUninstall is a paid mutator transaction binding the contract method 0x8a91b0e3. +// +// Solidity: function onUninstall(bytes ) payable returns() +func (_Entrypoint *EntrypointTransactor) OnUninstall(opts *bind.TransactOpts, arg0 []byte) (*types.Transaction, error) { + return _Entrypoint.contract.Transact(opts, "onUninstall", arg0) +} + +// OnUninstall is a paid mutator transaction binding the contract method 0x8a91b0e3. +// +// Solidity: function onUninstall(bytes ) payable returns() +func (_Entrypoint *EntrypointSession) OnUninstall(arg0 []byte) (*types.Transaction, error) { + return _Entrypoint.Contract.OnUninstall(&_Entrypoint.TransactOpts, arg0) +} + +// OnUninstall is a paid mutator transaction binding the contract method 0x8a91b0e3. +// +// Solidity: function onUninstall(bytes ) payable returns() +func (_Entrypoint *EntrypointTransactorSession) OnUninstall(arg0 []byte) (*types.Transaction, error) { + return _Entrypoint.Contract.OnUninstall(&_Entrypoint.TransactOpts, arg0) +} + +// PostCheck is a paid mutator transaction binding the contract method 0xaacbd72a. +// +// Solidity: function postCheck(bytes hookData, bool success, bytes res) payable returns() +func (_Entrypoint *EntrypointTransactor) PostCheck(opts *bind.TransactOpts, hookData []byte, success bool, res []byte) (*types.Transaction, error) { + return _Entrypoint.contract.Transact(opts, "postCheck", hookData, success, res) +} + +// PostCheck is a paid mutator transaction binding the contract method 0xaacbd72a. +// +// Solidity: function postCheck(bytes hookData, bool success, bytes res) payable returns() +func (_Entrypoint *EntrypointSession) PostCheck(hookData []byte, success bool, res []byte) (*types.Transaction, error) { + return _Entrypoint.Contract.PostCheck(&_Entrypoint.TransactOpts, hookData, success, res) +} + +// PostCheck is a paid mutator transaction binding the contract method 0xaacbd72a. +// +// Solidity: function postCheck(bytes hookData, bool success, bytes res) payable returns() +func (_Entrypoint *EntrypointTransactorSession) PostCheck(hookData []byte, success bool, res []byte) (*types.Transaction, error) { + return _Entrypoint.Contract.PostCheck(&_Entrypoint.TransactOpts, hookData, success, res) +} + +// PreCheck is a paid mutator transaction binding the contract method 0xd68f6025. +// +// Solidity: function preCheck(address msgSender, uint256 value, bytes ) payable returns(bytes) +func (_Entrypoint *EntrypointTransactor) PreCheck(opts *bind.TransactOpts, msgSender common.Address, value *big.Int, arg2 []byte) (*types.Transaction, error) { + return _Entrypoint.contract.Transact(opts, "preCheck", msgSender, value, arg2) +} + +// PreCheck is a paid mutator transaction binding the contract method 0xd68f6025. +// +// Solidity: function preCheck(address msgSender, uint256 value, bytes ) payable returns(bytes) +func (_Entrypoint *EntrypointSession) PreCheck(msgSender common.Address, value *big.Int, arg2 []byte) (*types.Transaction, error) { + return _Entrypoint.Contract.PreCheck(&_Entrypoint.TransactOpts, msgSender, value, arg2) +} + +// PreCheck is a paid mutator transaction binding the contract method 0xd68f6025. +// +// Solidity: function preCheck(address msgSender, uint256 value, bytes ) payable returns(bytes) +func (_Entrypoint *EntrypointTransactorSession) PreCheck(msgSender common.Address, value *big.Int, arg2 []byte) (*types.Transaction, error) { + return _Entrypoint.Contract.PreCheck(&_Entrypoint.TransactOpts, msgSender, value, arg2) +} + +// ValidateUserOp is a paid mutator transaction binding the contract method 0x97003203. +// +// Solidity: function validateUserOp((address,uint256,bytes,bytes,bytes32,uint256,bytes32,bytes,bytes) userOp, bytes32 userOpHash) payable returns(uint256) +func (_Entrypoint *EntrypointTransactor) ValidateUserOp(opts *bind.TransactOpts, userOp PackedUserOperation, userOpHash [32]byte) (*types.Transaction, error) { + return _Entrypoint.contract.Transact(opts, "validateUserOp", userOp, userOpHash) +} + +// ValidateUserOp is a paid mutator transaction binding the contract method 0x97003203. +// +// Solidity: function validateUserOp((address,uint256,bytes,bytes,bytes32,uint256,bytes32,bytes,bytes) userOp, bytes32 userOpHash) payable returns(uint256) +func (_Entrypoint *EntrypointSession) ValidateUserOp(userOp PackedUserOperation, userOpHash [32]byte) (*types.Transaction, error) { + return _Entrypoint.Contract.ValidateUserOp(&_Entrypoint.TransactOpts, userOp, userOpHash) +} + +// ValidateUserOp is a paid mutator transaction binding the contract method 0x97003203. +// +// Solidity: function validateUserOp((address,uint256,bytes,bytes,bytes32,uint256,bytes32,bytes,bytes) userOp, bytes32 userOpHash) payable returns(uint256) +func (_Entrypoint *EntrypointTransactorSession) ValidateUserOp(userOp PackedUserOperation, userOpHash [32]byte) (*types.Transaction, error) { + return _Entrypoint.Contract.ValidateUserOp(&_Entrypoint.TransactOpts, userOp, userOpHash) +} + +// EntrypointOwnerRegisteredIterator is returned from FilterOwnerRegistered and is used to iterate over the raw logs and unpacked data for OwnerRegistered events raised by the Entrypoint contract. +type EntrypointOwnerRegisteredIterator struct { + Event *EntrypointOwnerRegistered // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *EntrypointOwnerRegisteredIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(EntrypointOwnerRegistered) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(EntrypointOwnerRegistered) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *EntrypointOwnerRegisteredIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *EntrypointOwnerRegisteredIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// EntrypointOwnerRegistered represents a OwnerRegistered event raised by the Entrypoint contract. +type EntrypointOwnerRegistered struct { + Kernel common.Address + Owner common.Address + Raw types.Log // Blockchain specific contextual infos +} + +// FilterOwnerRegistered is a free log retrieval operation binding the contract event 0xa5e1f8b4009110f5525798d04ae2125421a12d0590aa52c13682ff1bd3c492ca. +// +// Solidity: event OwnerRegistered(address indexed kernel, address indexed owner) +func (_Entrypoint *EntrypointFilterer) FilterOwnerRegistered(opts *bind.FilterOpts, kernel []common.Address, owner []common.Address) (*EntrypointOwnerRegisteredIterator, error) { + + var kernelRule []interface{} + for _, kernelItem := range kernel { + kernelRule = append(kernelRule, kernelItem) + } + var ownerRule []interface{} + for _, ownerItem := range owner { + ownerRule = append(ownerRule, ownerItem) + } + + logs, sub, err := _Entrypoint.contract.FilterLogs(opts, "OwnerRegistered", kernelRule, ownerRule) + if err != nil { + return nil, err + } + return &EntrypointOwnerRegisteredIterator{contract: _Entrypoint.contract, event: "OwnerRegistered", logs: logs, sub: sub}, nil +} + +// WatchOwnerRegistered is a free log subscription operation binding the contract event 0xa5e1f8b4009110f5525798d04ae2125421a12d0590aa52c13682ff1bd3c492ca. +// +// Solidity: event OwnerRegistered(address indexed kernel, address indexed owner) +func (_Entrypoint *EntrypointFilterer) WatchOwnerRegistered(opts *bind.WatchOpts, sink chan<- *EntrypointOwnerRegistered, kernel []common.Address, owner []common.Address) (event.Subscription, error) { + + var kernelRule []interface{} + for _, kernelItem := range kernel { + kernelRule = append(kernelRule, kernelItem) + } + var ownerRule []interface{} + for _, ownerItem := range owner { + ownerRule = append(ownerRule, ownerItem) + } + + logs, sub, err := _Entrypoint.contract.WatchLogs(opts, "OwnerRegistered", kernelRule, ownerRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(EntrypointOwnerRegistered) + if err := _Entrypoint.contract.UnpackLog(event, "OwnerRegistered", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseOwnerRegistered is a log parse operation binding the contract event 0xa5e1f8b4009110f5525798d04ae2125421a12d0590aa52c13682ff1bd3c492ca. +// +// Solidity: event OwnerRegistered(address indexed kernel, address indexed owner) +func (_Entrypoint *EntrypointFilterer) ParseOwnerRegistered(log types.Log) (*EntrypointOwnerRegistered, error) { + event := new(EntrypointOwnerRegistered) + if err := _Entrypoint.contract.UnpackLog(event, "OwnerRegistered", log); err != nil { + return nil, err + } + event.Raw = log + return event, nil +} diff --git a/internal/services/contracts_events_consumer.go b/internal/services/contracts_events_consumer.go index bae593ba..c4a9913d 100644 --- a/internal/services/contracts_events_consumer.go +++ b/internal/services/contracts_events_consumer.go @@ -68,6 +68,9 @@ const ( // Rewards. TokensTransferredForDevice EventName = "TokensTransferredForDevice" TokensTransferredForConnectionStreak EventName = "TokensTransferredForConnectionStreak" + + // Zerodev Entrypoint. + OwnerRegistered EventName = "OwnerRegistered" ) func (r EventName) String() string { @@ -103,6 +106,7 @@ func (c *ContractsEventsConsumer) Process(ctx context.Context, event *shared.Clo DCNRegistryAddr := common.HexToAddress(c.settings.DCNRegistryAddr) DCNResolverAddr := common.HexToAddress(c.settings.DCNResolverAddr) RewardsContractAddr := common.HexToAddress(c.settings.RewardsContractAddr) + entrypointAddr := common.HexToAddress(c.settings.EntryPointAddr) var data ContractEventData if err := json.Unmarshal(event.Data, &data); err != nil { @@ -162,7 +166,6 @@ func (c *ContractsEventsConsumer) Process(ctx context.Context, event *shared.Clo case Transfer: return c.handleAftermarketDeviceTransferredEvent(ctx, &data) } - case DCNRegistryAddr: switch eventName { case NewNode: @@ -184,6 +187,15 @@ func (c *ContractsEventsConsumer) Process(ctx context.Context, event *shared.Clo case TokensTransferredForConnectionStreak: return c.handleTokensTransferredForConnectionStreak(ctx, &data) } + case entrypointAddr: + + b, _ := json.MarshalIndent(data, "", " ") + fmt.Println(string(b)) + + switch eventName { + case OwnerRegistered: + return c.handleOwnerRegistered(ctx, &data) + } } c.log.Debug().Str("event", data.EventName).Msg("Handler not provided for event.") @@ -684,3 +696,17 @@ func (c *ContractsEventsConsumer) handleAftermarketDeviceAddressResetEvent(ctx c _, err = amd.Update(ctx, c.dbs.DBS().Writer, boil.Whitelist(models.AftermarketDeviceColumns.Address)) return err } + +func (c *ContractsEventsConsumer) handleOwnerRegistered(ctx context.Context, e *ContractEventData) error { + var args OwnerRegisteredData + if err := json.Unmarshal(e.Arguments, &args); err != nil { + return err + } + + kernal := models.KernalAccount{ + Kernal: args.Kernal.Bytes(), + OwnerAddress: args.Owner.Bytes(), + } + + return kernal.Insert(ctx, c.dbs.DBS().Writer, boil.Infer()) +} diff --git a/internal/services/event_data_models.go b/internal/services/event_data_models.go index 3061988f..8cff0159 100644 --- a/internal/services/event_data_models.go +++ b/internal/services/event_data_models.go @@ -168,3 +168,8 @@ type DeviceDefinitionTableCreatedData struct { ManufacturerId *big.Int TableId *big.Int } + +type OwnerRegisteredData struct { + Kernal common.Address + Owner common.Address +} diff --git a/migrations/00031_kernal_tbl.sql b/migrations/00031_kernal_tbl.sql new file mode 100644 index 00000000..1b9c4595 --- /dev/null +++ b/migrations/00031_kernal_tbl.sql @@ -0,0 +1,12 @@ +-- +goose Up +-- +goose StatementBegin +CREATE TABLE kernal_accounts( + kernal bytea CONSTRAINT kernal_accounts_kernal_address_check CHECK (length(kernal) = 20) PRIMARY KEY, + owner_address bytea CONSTRAINT kernal_accounts_owner_address_check CHECK (length(owner_address) = 20) NOT NULL -- TODO(ae): should this reference any other table? +); +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +DROP TABLE kernal_accounts; +-- +goose StatementEnd diff --git a/models/boil_table_names.go b/models/boil_table_names.go index 4e73b8ec..bcb02508 100644 --- a/models/boil_table_names.go +++ b/models/boil_table_names.go @@ -6,6 +6,7 @@ package models var TableNames = struct { AftermarketDevices string DCNS string + KernalAccounts string Manufacturers string Privileges string Rewards string @@ -14,6 +15,7 @@ var TableNames = struct { }{ AftermarketDevices: "aftermarket_devices", DCNS: "dcns", + KernalAccounts: "kernal_accounts", Manufacturers: "manufacturers", Privileges: "privileges", Rewards: "rewards", diff --git a/models/kernal_accounts.go b/models/kernal_accounts.go new file mode 100644 index 00000000..f673169f --- /dev/null +++ b/models/kernal_accounts.go @@ -0,0 +1,928 @@ +// Code generated by SQLBoiler 4.16.2 (https://github.com/volatiletech/sqlboiler). DO NOT EDIT. +// This file is meant to be re-generated in place and/or deleted at any time. + +package models + +import ( + "context" + "database/sql" + "fmt" + "reflect" + "strconv" + "strings" + "sync" + "time" + + "github.com/friendsofgo/errors" + "github.com/volatiletech/sqlboiler/v4/boil" + "github.com/volatiletech/sqlboiler/v4/queries" + "github.com/volatiletech/sqlboiler/v4/queries/qm" + "github.com/volatiletech/sqlboiler/v4/queries/qmhelper" + "github.com/volatiletech/strmangle" +) + +// KernalAccount is an object representing the database table. +type KernalAccount struct { + Kernal []byte `boil:"kernal" json:"kernal" toml:"kernal" yaml:"kernal"` + OwnerAddress []byte `boil:"owner_address" json:"owner_address" toml:"owner_address" yaml:"owner_address"` + + R *kernalAccountR `boil:"-" json:"-" toml:"-" yaml:"-"` + L kernalAccountL `boil:"-" json:"-" toml:"-" yaml:"-"` +} + +var KernalAccountColumns = struct { + Kernal string + OwnerAddress string +}{ + Kernal: "kernal", + OwnerAddress: "owner_address", +} + +var KernalAccountTableColumns = struct { + Kernal string + OwnerAddress string +}{ + Kernal: "kernal_accounts.kernal", + OwnerAddress: "kernal_accounts.owner_address", +} + +// Generated where + +var KernalAccountWhere = struct { + Kernal whereHelper__byte + OwnerAddress whereHelper__byte +}{ + Kernal: whereHelper__byte{field: "\"identity_api\".\"kernal_accounts\".\"kernal\""}, + OwnerAddress: whereHelper__byte{field: "\"identity_api\".\"kernal_accounts\".\"owner_address\""}, +} + +// KernalAccountRels is where relationship names are stored. +var KernalAccountRels = struct { +}{} + +// kernalAccountR is where relationships are stored. +type kernalAccountR struct { +} + +// NewStruct creates a new relationship struct +func (*kernalAccountR) NewStruct() *kernalAccountR { + return &kernalAccountR{} +} + +// kernalAccountL is where Load methods for each relationship are stored. +type kernalAccountL struct{} + +var ( + kernalAccountAllColumns = []string{"kernal", "owner_address"} + kernalAccountColumnsWithoutDefault = []string{"kernal", "owner_address"} + kernalAccountColumnsWithDefault = []string{} + kernalAccountPrimaryKeyColumns = []string{"kernal"} + kernalAccountGeneratedColumns = []string{} +) + +type ( + // KernalAccountSlice is an alias for a slice of pointers to KernalAccount. + // This should almost always be used instead of []KernalAccount. + KernalAccountSlice []*KernalAccount + // KernalAccountHook is the signature for custom KernalAccount hook methods + KernalAccountHook func(context.Context, boil.ContextExecutor, *KernalAccount) error + + kernalAccountQuery struct { + *queries.Query + } +) + +// Cache for insert, update and upsert +var ( + kernalAccountType = reflect.TypeOf(&KernalAccount{}) + kernalAccountMapping = queries.MakeStructMapping(kernalAccountType) + kernalAccountPrimaryKeyMapping, _ = queries.BindMapping(kernalAccountType, kernalAccountMapping, kernalAccountPrimaryKeyColumns) + kernalAccountInsertCacheMut sync.RWMutex + kernalAccountInsertCache = make(map[string]insertCache) + kernalAccountUpdateCacheMut sync.RWMutex + kernalAccountUpdateCache = make(map[string]updateCache) + kernalAccountUpsertCacheMut sync.RWMutex + kernalAccountUpsertCache = make(map[string]insertCache) +) + +var ( + // Force time package dependency for automated UpdatedAt/CreatedAt. + _ = time.Second + // Force qmhelper dependency for where clause generation (which doesn't + // always happen) + _ = qmhelper.Where +) + +var kernalAccountAfterSelectMu sync.Mutex +var kernalAccountAfterSelectHooks []KernalAccountHook + +var kernalAccountBeforeInsertMu sync.Mutex +var kernalAccountBeforeInsertHooks []KernalAccountHook +var kernalAccountAfterInsertMu sync.Mutex +var kernalAccountAfterInsertHooks []KernalAccountHook + +var kernalAccountBeforeUpdateMu sync.Mutex +var kernalAccountBeforeUpdateHooks []KernalAccountHook +var kernalAccountAfterUpdateMu sync.Mutex +var kernalAccountAfterUpdateHooks []KernalAccountHook + +var kernalAccountBeforeDeleteMu sync.Mutex +var kernalAccountBeforeDeleteHooks []KernalAccountHook +var kernalAccountAfterDeleteMu sync.Mutex +var kernalAccountAfterDeleteHooks []KernalAccountHook + +var kernalAccountBeforeUpsertMu sync.Mutex +var kernalAccountBeforeUpsertHooks []KernalAccountHook +var kernalAccountAfterUpsertMu sync.Mutex +var kernalAccountAfterUpsertHooks []KernalAccountHook + +// doAfterSelectHooks executes all "after Select" hooks. +func (o *KernalAccount) doAfterSelectHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range kernalAccountAfterSelectHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doBeforeInsertHooks executes all "before insert" hooks. +func (o *KernalAccount) doBeforeInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range kernalAccountBeforeInsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterInsertHooks executes all "after Insert" hooks. +func (o *KernalAccount) doAfterInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range kernalAccountAfterInsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doBeforeUpdateHooks executes all "before Update" hooks. +func (o *KernalAccount) doBeforeUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range kernalAccountBeforeUpdateHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterUpdateHooks executes all "after Update" hooks. +func (o *KernalAccount) doAfterUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range kernalAccountAfterUpdateHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doBeforeDeleteHooks executes all "before Delete" hooks. +func (o *KernalAccount) doBeforeDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range kernalAccountBeforeDeleteHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterDeleteHooks executes all "after Delete" hooks. +func (o *KernalAccount) doAfterDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range kernalAccountAfterDeleteHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doBeforeUpsertHooks executes all "before Upsert" hooks. +func (o *KernalAccount) doBeforeUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range kernalAccountBeforeUpsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterUpsertHooks executes all "after Upsert" hooks. +func (o *KernalAccount) doAfterUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range kernalAccountAfterUpsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// AddKernalAccountHook registers your hook function for all future operations. +func AddKernalAccountHook(hookPoint boil.HookPoint, kernalAccountHook KernalAccountHook) { + switch hookPoint { + case boil.AfterSelectHook: + kernalAccountAfterSelectMu.Lock() + kernalAccountAfterSelectHooks = append(kernalAccountAfterSelectHooks, kernalAccountHook) + kernalAccountAfterSelectMu.Unlock() + case boil.BeforeInsertHook: + kernalAccountBeforeInsertMu.Lock() + kernalAccountBeforeInsertHooks = append(kernalAccountBeforeInsertHooks, kernalAccountHook) + kernalAccountBeforeInsertMu.Unlock() + case boil.AfterInsertHook: + kernalAccountAfterInsertMu.Lock() + kernalAccountAfterInsertHooks = append(kernalAccountAfterInsertHooks, kernalAccountHook) + kernalAccountAfterInsertMu.Unlock() + case boil.BeforeUpdateHook: + kernalAccountBeforeUpdateMu.Lock() + kernalAccountBeforeUpdateHooks = append(kernalAccountBeforeUpdateHooks, kernalAccountHook) + kernalAccountBeforeUpdateMu.Unlock() + case boil.AfterUpdateHook: + kernalAccountAfterUpdateMu.Lock() + kernalAccountAfterUpdateHooks = append(kernalAccountAfterUpdateHooks, kernalAccountHook) + kernalAccountAfterUpdateMu.Unlock() + case boil.BeforeDeleteHook: + kernalAccountBeforeDeleteMu.Lock() + kernalAccountBeforeDeleteHooks = append(kernalAccountBeforeDeleteHooks, kernalAccountHook) + kernalAccountBeforeDeleteMu.Unlock() + case boil.AfterDeleteHook: + kernalAccountAfterDeleteMu.Lock() + kernalAccountAfterDeleteHooks = append(kernalAccountAfterDeleteHooks, kernalAccountHook) + kernalAccountAfterDeleteMu.Unlock() + case boil.BeforeUpsertHook: + kernalAccountBeforeUpsertMu.Lock() + kernalAccountBeforeUpsertHooks = append(kernalAccountBeforeUpsertHooks, kernalAccountHook) + kernalAccountBeforeUpsertMu.Unlock() + case boil.AfterUpsertHook: + kernalAccountAfterUpsertMu.Lock() + kernalAccountAfterUpsertHooks = append(kernalAccountAfterUpsertHooks, kernalAccountHook) + kernalAccountAfterUpsertMu.Unlock() + } +} + +// One returns a single kernalAccount record from the query. +func (q kernalAccountQuery) One(ctx context.Context, exec boil.ContextExecutor) (*KernalAccount, error) { + o := &KernalAccount{} + + queries.SetLimit(q.Query, 1) + + err := q.Bind(ctx, exec, o) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, sql.ErrNoRows + } + return nil, errors.Wrap(err, "models: failed to execute a one query for kernal_accounts") + } + + if err := o.doAfterSelectHooks(ctx, exec); err != nil { + return o, err + } + + return o, nil +} + +// All returns all KernalAccount records from the query. +func (q kernalAccountQuery) All(ctx context.Context, exec boil.ContextExecutor) (KernalAccountSlice, error) { + var o []*KernalAccount + + err := q.Bind(ctx, exec, &o) + if err != nil { + return nil, errors.Wrap(err, "models: failed to assign all query results to KernalAccount slice") + } + + if len(kernalAccountAfterSelectHooks) != 0 { + for _, obj := range o { + if err := obj.doAfterSelectHooks(ctx, exec); err != nil { + return o, err + } + } + } + + return o, nil +} + +// Count returns the count of all KernalAccount records in the query. +func (q kernalAccountQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + var count int64 + + queries.SetSelect(q.Query, nil) + queries.SetCount(q.Query) + + err := q.Query.QueryRowContext(ctx, exec).Scan(&count) + if err != nil { + return 0, errors.Wrap(err, "models: failed to count kernal_accounts rows") + } + + return count, nil +} + +// Exists checks if the row exists in the table. +func (q kernalAccountQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) { + var count int64 + + queries.SetSelect(q.Query, nil) + queries.SetCount(q.Query) + queries.SetLimit(q.Query, 1) + + err := q.Query.QueryRowContext(ctx, exec).Scan(&count) + if err != nil { + return false, errors.Wrap(err, "models: failed to check if kernal_accounts exists") + } + + return count > 0, nil +} + +// KernalAccounts retrieves all the records using an executor. +func KernalAccounts(mods ...qm.QueryMod) kernalAccountQuery { + mods = append(mods, qm.From("\"identity_api\".\"kernal_accounts\"")) + q := NewQuery(mods...) + if len(queries.GetSelect(q)) == 0 { + queries.SetSelect(q, []string{"\"identity_api\".\"kernal_accounts\".*"}) + } + + return kernalAccountQuery{q} +} + +// FindKernalAccount retrieves a single record by ID with an executor. +// If selectCols is empty Find will return all columns. +func FindKernalAccount(ctx context.Context, exec boil.ContextExecutor, kernal []byte, selectCols ...string) (*KernalAccount, error) { + kernalAccountObj := &KernalAccount{} + + sel := "*" + if len(selectCols) > 0 { + sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",") + } + query := fmt.Sprintf( + "select %s from \"identity_api\".\"kernal_accounts\" where \"kernal\"=$1", sel, + ) + + q := queries.Raw(query, kernal) + + err := q.Bind(ctx, exec, kernalAccountObj) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, sql.ErrNoRows + } + return nil, errors.Wrap(err, "models: unable to select from kernal_accounts") + } + + if err = kernalAccountObj.doAfterSelectHooks(ctx, exec); err != nil { + return kernalAccountObj, err + } + + return kernalAccountObj, nil +} + +// Insert a single record using an executor. +// See boil.Columns.InsertColumnSet documentation to understand column list inference for inserts. +func (o *KernalAccount) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error { + if o == nil { + return errors.New("models: no kernal_accounts provided for insertion") + } + + var err error + + if err := o.doBeforeInsertHooks(ctx, exec); err != nil { + return err + } + + nzDefaults := queries.NonZeroDefaultSet(kernalAccountColumnsWithDefault, o) + + key := makeCacheKey(columns, nzDefaults) + kernalAccountInsertCacheMut.RLock() + cache, cached := kernalAccountInsertCache[key] + kernalAccountInsertCacheMut.RUnlock() + + if !cached { + wl, returnColumns := columns.InsertColumnSet( + kernalAccountAllColumns, + kernalAccountColumnsWithDefault, + kernalAccountColumnsWithoutDefault, + nzDefaults, + ) + + cache.valueMapping, err = queries.BindMapping(kernalAccountType, kernalAccountMapping, wl) + if err != nil { + return err + } + cache.retMapping, err = queries.BindMapping(kernalAccountType, kernalAccountMapping, returnColumns) + if err != nil { + return err + } + if len(wl) != 0 { + cache.query = fmt.Sprintf("INSERT INTO \"identity_api\".\"kernal_accounts\" (\"%s\") %%sVALUES (%s)%%s", strings.Join(wl, "\",\""), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1)) + } else { + cache.query = "INSERT INTO \"identity_api\".\"kernal_accounts\" %sDEFAULT VALUES%s" + } + + var queryOutput, queryReturning string + + if len(cache.retMapping) != 0 { + queryReturning = fmt.Sprintf(" RETURNING \"%s\"", strings.Join(returnColumns, "\",\"")) + } + + cache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning) + } + + value := reflect.Indirect(reflect.ValueOf(o)) + vals := queries.ValuesFromMapping(value, cache.valueMapping) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, cache.query) + fmt.Fprintln(writer, vals) + } + + if len(cache.retMapping) != 0 { + err = exec.QueryRowContext(ctx, cache.query, vals...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...) + } else { + _, err = exec.ExecContext(ctx, cache.query, vals...) + } + + if err != nil { + return errors.Wrap(err, "models: unable to insert into kernal_accounts") + } + + if !cached { + kernalAccountInsertCacheMut.Lock() + kernalAccountInsertCache[key] = cache + kernalAccountInsertCacheMut.Unlock() + } + + return o.doAfterInsertHooks(ctx, exec) +} + +// Update uses an executor to update the KernalAccount. +// See boil.Columns.UpdateColumnSet documentation to understand column list inference for updates. +// Update does not automatically update the record in case of default values. Use .Reload() to refresh the records. +func (o *KernalAccount) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) { + var err error + if err = o.doBeforeUpdateHooks(ctx, exec); err != nil { + return 0, err + } + key := makeCacheKey(columns, nil) + kernalAccountUpdateCacheMut.RLock() + cache, cached := kernalAccountUpdateCache[key] + kernalAccountUpdateCacheMut.RUnlock() + + if !cached { + wl := columns.UpdateColumnSet( + kernalAccountAllColumns, + kernalAccountPrimaryKeyColumns, + ) + + if !columns.IsWhitelist() { + wl = strmangle.SetComplement(wl, []string{"created_at"}) + } + if len(wl) == 0 { + return 0, errors.New("models: unable to update kernal_accounts, could not build whitelist") + } + + cache.query = fmt.Sprintf("UPDATE \"identity_api\".\"kernal_accounts\" SET %s WHERE %s", + strmangle.SetParamNames("\"", "\"", 1, wl), + strmangle.WhereClause("\"", "\"", len(wl)+1, kernalAccountPrimaryKeyColumns), + ) + cache.valueMapping, err = queries.BindMapping(kernalAccountType, kernalAccountMapping, append(wl, kernalAccountPrimaryKeyColumns...)) + if err != nil { + return 0, err + } + } + + values := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, cache.query) + fmt.Fprintln(writer, values) + } + var result sql.Result + result, err = exec.ExecContext(ctx, cache.query, values...) + if err != nil { + return 0, errors.Wrap(err, "models: unable to update kernal_accounts row") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: failed to get rows affected by update for kernal_accounts") + } + + if !cached { + kernalAccountUpdateCacheMut.Lock() + kernalAccountUpdateCache[key] = cache + kernalAccountUpdateCacheMut.Unlock() + } + + return rowsAff, o.doAfterUpdateHooks(ctx, exec) +} + +// UpdateAll updates all rows with the specified column values. +func (q kernalAccountQuery) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { + queries.SetUpdate(q.Query, cols) + + result, err := q.Query.ExecContext(ctx, exec) + if err != nil { + return 0, errors.Wrap(err, "models: unable to update all for kernal_accounts") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: unable to retrieve rows affected for kernal_accounts") + } + + return rowsAff, nil +} + +// UpdateAll updates all rows with the specified column values, using an executor. +func (o KernalAccountSlice) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { + ln := int64(len(o)) + if ln == 0 { + return 0, nil + } + + if len(cols) == 0 { + return 0, errors.New("models: update all requires at least one column argument") + } + + colNames := make([]string, len(cols)) + args := make([]interface{}, len(cols)) + + i := 0 + for name, value := range cols { + colNames[i] = name + args[i] = value + i++ + } + + // Append all of the primary key values for each column + for _, obj := range o { + pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), kernalAccountPrimaryKeyMapping) + args = append(args, pkeyArgs...) + } + + sql := fmt.Sprintf("UPDATE \"identity_api\".\"kernal_accounts\" SET %s WHERE %s", + strmangle.SetParamNames("\"", "\"", 1, colNames), + strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), len(colNames)+1, kernalAccountPrimaryKeyColumns, len(o))) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, args...) + } + result, err := exec.ExecContext(ctx, sql, args...) + if err != nil { + return 0, errors.Wrap(err, "models: unable to update all in kernalAccount slice") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: unable to retrieve rows affected all in update all kernalAccount") + } + return rowsAff, nil +} + +// Upsert attempts an insert using an executor, and does an update or ignore on conflict. +// See boil.Columns documentation for how to properly use updateColumns and insertColumns. +func (o *KernalAccount) Upsert(ctx context.Context, exec boil.ContextExecutor, updateOnConflict bool, conflictColumns []string, updateColumns, insertColumns boil.Columns, opts ...UpsertOptionFunc) error { + if o == nil { + return errors.New("models: no kernal_accounts provided for upsert") + } + + if err := o.doBeforeUpsertHooks(ctx, exec); err != nil { + return err + } + + nzDefaults := queries.NonZeroDefaultSet(kernalAccountColumnsWithDefault, o) + + // Build cache key in-line uglily - mysql vs psql problems + buf := strmangle.GetBuffer() + if updateOnConflict { + buf.WriteByte('t') + } else { + buf.WriteByte('f') + } + buf.WriteByte('.') + for _, c := range conflictColumns { + buf.WriteString(c) + } + buf.WriteByte('.') + buf.WriteString(strconv.Itoa(updateColumns.Kind)) + for _, c := range updateColumns.Cols { + buf.WriteString(c) + } + buf.WriteByte('.') + buf.WriteString(strconv.Itoa(insertColumns.Kind)) + for _, c := range insertColumns.Cols { + buf.WriteString(c) + } + buf.WriteByte('.') + for _, c := range nzDefaults { + buf.WriteString(c) + } + key := buf.String() + strmangle.PutBuffer(buf) + + kernalAccountUpsertCacheMut.RLock() + cache, cached := kernalAccountUpsertCache[key] + kernalAccountUpsertCacheMut.RUnlock() + + var err error + + if !cached { + insert, _ := insertColumns.InsertColumnSet( + kernalAccountAllColumns, + kernalAccountColumnsWithDefault, + kernalAccountColumnsWithoutDefault, + nzDefaults, + ) + + update := updateColumns.UpdateColumnSet( + kernalAccountAllColumns, + kernalAccountPrimaryKeyColumns, + ) + + if updateOnConflict && len(update) == 0 { + return errors.New("models: unable to upsert kernal_accounts, could not build update column list") + } + + ret := strmangle.SetComplement(kernalAccountAllColumns, strmangle.SetIntersect(insert, update)) + + conflict := conflictColumns + if len(conflict) == 0 && updateOnConflict && len(update) != 0 { + if len(kernalAccountPrimaryKeyColumns) == 0 { + return errors.New("models: unable to upsert kernal_accounts, could not build conflict column list") + } + + conflict = make([]string, len(kernalAccountPrimaryKeyColumns)) + copy(conflict, kernalAccountPrimaryKeyColumns) + } + cache.query = buildUpsertQueryPostgres(dialect, "\"identity_api\".\"kernal_accounts\"", updateOnConflict, ret, update, conflict, insert, opts...) + + cache.valueMapping, err = queries.BindMapping(kernalAccountType, kernalAccountMapping, insert) + if err != nil { + return err + } + if len(ret) != 0 { + cache.retMapping, err = queries.BindMapping(kernalAccountType, kernalAccountMapping, ret) + if err != nil { + return err + } + } + } + + value := reflect.Indirect(reflect.ValueOf(o)) + vals := queries.ValuesFromMapping(value, cache.valueMapping) + var returns []interface{} + if len(cache.retMapping) != 0 { + returns = queries.PtrsFromMapping(value, cache.retMapping) + } + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, cache.query) + fmt.Fprintln(writer, vals) + } + if len(cache.retMapping) != 0 { + err = exec.QueryRowContext(ctx, cache.query, vals...).Scan(returns...) + if errors.Is(err, sql.ErrNoRows) { + err = nil // Postgres doesn't return anything when there's no update + } + } else { + _, err = exec.ExecContext(ctx, cache.query, vals...) + } + if err != nil { + return errors.Wrap(err, "models: unable to upsert kernal_accounts") + } + + if !cached { + kernalAccountUpsertCacheMut.Lock() + kernalAccountUpsertCache[key] = cache + kernalAccountUpsertCacheMut.Unlock() + } + + return o.doAfterUpsertHooks(ctx, exec) +} + +// Delete deletes a single KernalAccount record with an executor. +// Delete will match against the primary key column to find the record to delete. +func (o *KernalAccount) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + if o == nil { + return 0, errors.New("models: no KernalAccount provided for delete") + } + + if err := o.doBeforeDeleteHooks(ctx, exec); err != nil { + return 0, err + } + + args := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), kernalAccountPrimaryKeyMapping) + sql := "DELETE FROM \"identity_api\".\"kernal_accounts\" WHERE \"kernal\"=$1" + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, args...) + } + result, err := exec.ExecContext(ctx, sql, args...) + if err != nil { + return 0, errors.Wrap(err, "models: unable to delete from kernal_accounts") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: failed to get rows affected by delete for kernal_accounts") + } + + if err := o.doAfterDeleteHooks(ctx, exec); err != nil { + return 0, err + } + + return rowsAff, nil +} + +// DeleteAll deletes all matching rows. +func (q kernalAccountQuery) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + if q.Query == nil { + return 0, errors.New("models: no kernalAccountQuery provided for delete all") + } + + queries.SetDelete(q.Query) + + result, err := q.Query.ExecContext(ctx, exec) + if err != nil { + return 0, errors.Wrap(err, "models: unable to delete all from kernal_accounts") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for kernal_accounts") + } + + return rowsAff, nil +} + +// DeleteAll deletes all rows in the slice, using an executor. +func (o KernalAccountSlice) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + if len(o) == 0 { + return 0, nil + } + + if len(kernalAccountBeforeDeleteHooks) != 0 { + for _, obj := range o { + if err := obj.doBeforeDeleteHooks(ctx, exec); err != nil { + return 0, err + } + } + } + + var args []interface{} + for _, obj := range o { + pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), kernalAccountPrimaryKeyMapping) + args = append(args, pkeyArgs...) + } + + sql := "DELETE FROM \"identity_api\".\"kernal_accounts\" WHERE " + + strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, kernalAccountPrimaryKeyColumns, len(o)) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, args) + } + result, err := exec.ExecContext(ctx, sql, args...) + if err != nil { + return 0, errors.Wrap(err, "models: unable to delete all from kernalAccount slice") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for kernal_accounts") + } + + if len(kernalAccountAfterDeleteHooks) != 0 { + for _, obj := range o { + if err := obj.doAfterDeleteHooks(ctx, exec); err != nil { + return 0, err + } + } + } + + return rowsAff, nil +} + +// Reload refetches the object from the database +// using the primary keys with an executor. +func (o *KernalAccount) Reload(ctx context.Context, exec boil.ContextExecutor) error { + ret, err := FindKernalAccount(ctx, exec, o.Kernal) + if err != nil { + return err + } + + *o = *ret + return nil +} + +// ReloadAll refetches every row with matching primary key column values +// and overwrites the original object slice with the newly updated slice. +func (o *KernalAccountSlice) ReloadAll(ctx context.Context, exec boil.ContextExecutor) error { + if o == nil || len(*o) == 0 { + return nil + } + + slice := KernalAccountSlice{} + var args []interface{} + for _, obj := range *o { + pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), kernalAccountPrimaryKeyMapping) + args = append(args, pkeyArgs...) + } + + sql := "SELECT \"identity_api\".\"kernal_accounts\".* FROM \"identity_api\".\"kernal_accounts\" WHERE " + + strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, kernalAccountPrimaryKeyColumns, len(*o)) + + q := queries.Raw(sql, args...) + + err := q.Bind(ctx, exec, &slice) + if err != nil { + return errors.Wrap(err, "models: unable to reload all in KernalAccountSlice") + } + + *o = slice + + return nil +} + +// KernalAccountExists checks if the KernalAccount row exists. +func KernalAccountExists(ctx context.Context, exec boil.ContextExecutor, kernal []byte) (bool, error) { + var exists bool + sql := "select exists(select 1 from \"identity_api\".\"kernal_accounts\" where \"kernal\"=$1 limit 1)" + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, kernal) + } + row := exec.QueryRowContext(ctx, sql, kernal) + + err := row.Scan(&exists) + if err != nil { + return false, errors.Wrap(err, "models: unable to check if kernal_accounts exists") + } + + return exists, nil +} + +// Exists checks if the KernalAccount row exists. +func (o *KernalAccount) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) { + return KernalAccountExists(ctx, exec, o.Kernal) +} diff --git a/settings.sample.yaml b/settings.sample.yaml index 27c48d12..d4458906 100644 --- a/settings.sample.yaml +++ b/settings.sample.yaml @@ -18,4 +18,5 @@ SYNTHETIC_DEVICE_CONTRACT_ADDRESS: "0x85226A67FF1b3Ec6cb033162f7df5038a6C3bAB2" REWARDS_CONTRACT_ADDRESS: "0x375885164266d48C48abbbb439Be98864Ae62bBE" BASE_IMAGE_URL: "https://devices-api.dev.dimo.zone/v1/" TABLELAND_API_GATEWAY: "https://testnets.tableland.network/" -ETHEREUM_RPC_URL: "http://127.0.0.1:8545" \ No newline at end of file +ETHEREUM_RPC_URL: "http://127.0.0.1:8545" +ENTRYPOINT_ADDR: "0x8104e3Ad430EA6d354d013A6789fDFc71E671c43" From 4cf3ecf5fb67905fe50c1847874aba20fd2d9675 Mon Sep 17 00:00:00 2001 From: Allyson-English Date: Wed, 10 Jul 2024 14:21:44 -0400 Subject: [PATCH 02/12] clean up --- internal/config/settings.go | 2 +- ...ntrypoint.go => kernal_ecdsa_validator.go} | 282 +++++++++--------- .../services/contracts_events_consumer.go | 16 +- internal/services/event_data_models.go | 2 +- settings.sample.yaml | 2 +- 5 files changed, 150 insertions(+), 154 deletions(-) rename internal/contracts/{entrypoint.go => kernal_ecdsa_validator.go} (54%) diff --git a/internal/config/settings.go b/internal/config/settings.go index edcc102b..2ec235c8 100644 --- a/internal/config/settings.go +++ b/internal/config/settings.go @@ -22,5 +22,5 @@ type Settings struct { BaseVehicleDataURI string `yaml:"BASE_VEHICLE_DATA_URI"` TablelandAPIGateway string `yaml:"TABLELAND_API_GATEWAY"` EthereumRPCURL string `yaml:"ETHEREUM_RPC_URL"` - EntryPointAddr string `yaml:"ENTRYPOINT_ADDR"` + KernalECDSAValidator string `yaml:"KERNAL_ECDSA_VALIDATOR"` } diff --git a/internal/contracts/entrypoint.go b/internal/contracts/kernal_ecdsa_validator.go similarity index 54% rename from internal/contracts/entrypoint.go rename to internal/contracts/kernal_ecdsa_validator.go index 86962001..b5d97ea6 100644 --- a/internal/contracts/entrypoint.go +++ b/internal/contracts/kernal_ecdsa_validator.go @@ -41,113 +41,113 @@ type PackedUserOperation struct { Signature []byte } -// EntrypointMetaData contains all meta data concerning the Entrypoint contract. -var EntrypointMetaData = &bind.MetaData{ +// ECDSAValidatorMetaData contains all meta data concerning the ECDSAValidator contract. +var ECDSAValidatorMetaData = &bind.MetaData{ ABI: "[{\"constant\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"smartAccount\",\"type\":\"address\"}],\"name\":\"AlreadyInitialized\",\"payable\":false,\"type\":\"error\"},{\"constant\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"target\",\"type\":\"address\"}],\"name\":\"InvalidTargetAddress\",\"payable\":false,\"type\":\"error\"},{\"constant\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"smartAccount\",\"type\":\"address\"}],\"name\":\"NotInitialized\",\"payable\":false,\"type\":\"error\"},{\"constant\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"kernel\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"OwnerRegistered\",\"payable\":false,\"type\":\"event\"},{\"constant\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"ecdsaValidatorStorage\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"smartAccount\",\"type\":\"address\"}],\"name\":\"isInitialized\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"typeID\",\"type\":\"uint256\"}],\"name\":\"isModuleType\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"pure\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"hash\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"sig\",\"type\":\"bytes\"}],\"name\":\"isValidSignatureWithSender\",\"outputs\":[{\"internalType\":\"bytes4\",\"name\":\"\",\"type\":\"bytes4\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"_data\",\"type\":\"bytes\"}],\"name\":\"onInstall\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"name\":\"onUninstall\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"hookData\",\"type\":\"bytes\"},{\"indexed\":false,\"internalType\":\"bool\",\"name\":\"success\",\"type\":\"bool\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"res\",\"type\":\"bytes\"}],\"name\":\"postCheck\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"msgSender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"name\":\"preCheck\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"payable\":false,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"components\":[{\"name\":\"sender\",\"type\":\"address\"},{\"name\":\"nonce\",\"type\":\"uint256\"},{\"name\":\"initCode\",\"type\":\"bytes\"},{\"name\":\"callData\",\"type\":\"bytes\"},{\"name\":\"accountGasLimits\",\"type\":\"bytes32\"},{\"name\":\"preVerificationGas\",\"type\":\"uint256\"},{\"name\":\"gasFees\",\"type\":\"bytes32\"},{\"name\":\"paymasterAndData\",\"type\":\"bytes\"},{\"name\":\"signature\",\"type\":\"bytes\"}],\"indexed\":false,\"internalType\":\"structPackedUserOperation\",\"name\":\"userOp\",\"type\":\"tuple\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"userOpHash\",\"type\":\"bytes32\"}],\"name\":\"validateUserOp\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"payable\",\"type\":\"function\"}]", } -// EntrypointABI is the input ABI used to generate the binding from. -// Deprecated: Use EntrypointMetaData.ABI instead. -var EntrypointABI = EntrypointMetaData.ABI +// ECDSAValidatorABI is the input ABI used to generate the binding from. +// Deprecated: Use ECDSAValidatorMetaData.ABI instead. +var ECDSAValidatorABI = ECDSAValidatorMetaData.ABI -// Entrypoint is an auto generated Go binding around an Ethereum contract. -type Entrypoint struct { - EntrypointCaller // Read-only binding to the contract - EntrypointTransactor // Write-only binding to the contract - EntrypointFilterer // Log filterer for contract events +// ECDSAValidator is an auto generated Go binding around an Ethereum contract. +type ECDSAValidator struct { + ECDSAValidatorCaller // Read-only binding to the contract + ECDSAValidatorTransactor // Write-only binding to the contract + ECDSAValidatorFilterer // Log filterer for contract events } -// EntrypointCaller is an auto generated read-only Go binding around an Ethereum contract. -type EntrypointCaller struct { +// ECDSAValidatorCaller is an auto generated read-only Go binding around an Ethereum contract. +type ECDSAValidatorCaller struct { contract *bind.BoundContract // Generic contract wrapper for the low level calls } -// EntrypointTransactor is an auto generated write-only Go binding around an Ethereum contract. -type EntrypointTransactor struct { +// ECDSAValidatorTransactor is an auto generated write-only Go binding around an Ethereum contract. +type ECDSAValidatorTransactor struct { contract *bind.BoundContract // Generic contract wrapper for the low level calls } -// EntrypointFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type EntrypointFilterer struct { +// ECDSAValidatorFilterer is an auto generated log filtering Go binding around an Ethereum contract events. +type ECDSAValidatorFilterer struct { contract *bind.BoundContract // Generic contract wrapper for the low level calls } -// EntrypointSession is an auto generated Go binding around an Ethereum contract, +// ECDSAValidatorSession is an auto generated Go binding around an Ethereum contract, // with pre-set call and transact options. -type EntrypointSession struct { - Contract *Entrypoint // Generic contract binding to set the session for +type ECDSAValidatorSession struct { + Contract *ECDSAValidator // Generic contract binding to set the session for CallOpts bind.CallOpts // Call options to use throughout this session TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session } -// EntrypointCallerSession is an auto generated read-only Go binding around an Ethereum contract, +// ECDSAValidatorCallerSession is an auto generated read-only Go binding around an Ethereum contract, // with pre-set call options. -type EntrypointCallerSession struct { - Contract *EntrypointCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session +type ECDSAValidatorCallerSession struct { + Contract *ECDSAValidatorCaller // Generic contract caller binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session } -// EntrypointTransactorSession is an auto generated write-only Go binding around an Ethereum contract, +// ECDSAValidatorTransactorSession is an auto generated write-only Go binding around an Ethereum contract, // with pre-set transact options. -type EntrypointTransactorSession struct { - Contract *EntrypointTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +type ECDSAValidatorTransactorSession struct { + Contract *ECDSAValidatorTransactor // Generic contract transactor binding to set the session for + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session } -// EntrypointRaw is an auto generated low-level Go binding around an Ethereum contract. -type EntrypointRaw struct { - Contract *Entrypoint // Generic contract binding to access the raw methods on +// ECDSAValidatorRaw is an auto generated low-level Go binding around an Ethereum contract. +type ECDSAValidatorRaw struct { + Contract *ECDSAValidator // Generic contract binding to access the raw methods on } -// EntrypointCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type EntrypointCallerRaw struct { - Contract *EntrypointCaller // Generic read-only contract binding to access the raw methods on +// ECDSAValidatorCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. +type ECDSAValidatorCallerRaw struct { + Contract *ECDSAValidatorCaller // Generic read-only contract binding to access the raw methods on } -// EntrypointTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type EntrypointTransactorRaw struct { - Contract *EntrypointTransactor // Generic write-only contract binding to access the raw methods on +// ECDSAValidatorTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. +type ECDSAValidatorTransactorRaw struct { + Contract *ECDSAValidatorTransactor // Generic write-only contract binding to access the raw methods on } -// NewEntrypoint creates a new instance of Entrypoint, bound to a specific deployed contract. -func NewEntrypoint(address common.Address, backend bind.ContractBackend) (*Entrypoint, error) { - contract, err := bindEntrypoint(address, backend, backend, backend) +// NewECDSAValidator creates a new instance of ECDSAValidator, bound to a specific deployed contract. +func NewECDSAValidator(address common.Address, backend bind.ContractBackend) (*ECDSAValidator, error) { + contract, err := bindECDSAValidator(address, backend, backend, backend) if err != nil { return nil, err } - return &Entrypoint{EntrypointCaller: EntrypointCaller{contract: contract}, EntrypointTransactor: EntrypointTransactor{contract: contract}, EntrypointFilterer: EntrypointFilterer{contract: contract}}, nil + return &ECDSAValidator{ECDSAValidatorCaller: ECDSAValidatorCaller{contract: contract}, ECDSAValidatorTransactor: ECDSAValidatorTransactor{contract: contract}, ECDSAValidatorFilterer: ECDSAValidatorFilterer{contract: contract}}, nil } -// NewEntrypointCaller creates a new read-only instance of Entrypoint, bound to a specific deployed contract. -func NewEntrypointCaller(address common.Address, caller bind.ContractCaller) (*EntrypointCaller, error) { - contract, err := bindEntrypoint(address, caller, nil, nil) +// NewECDSAValidatorCaller creates a new read-only instance of ECDSAValidator, bound to a specific deployed contract. +func NewECDSAValidatorCaller(address common.Address, caller bind.ContractCaller) (*ECDSAValidatorCaller, error) { + contract, err := bindECDSAValidator(address, caller, nil, nil) if err != nil { return nil, err } - return &EntrypointCaller{contract: contract}, nil + return &ECDSAValidatorCaller{contract: contract}, nil } -// NewEntrypointTransactor creates a new write-only instance of Entrypoint, bound to a specific deployed contract. -func NewEntrypointTransactor(address common.Address, transactor bind.ContractTransactor) (*EntrypointTransactor, error) { - contract, err := bindEntrypoint(address, nil, transactor, nil) +// NewECDSAValidatorTransactor creates a new write-only instance of ECDSAValidator, bound to a specific deployed contract. +func NewECDSAValidatorTransactor(address common.Address, transactor bind.ContractTransactor) (*ECDSAValidatorTransactor, error) { + contract, err := bindECDSAValidator(address, nil, transactor, nil) if err != nil { return nil, err } - return &EntrypointTransactor{contract: contract}, nil + return &ECDSAValidatorTransactor{contract: contract}, nil } -// NewEntrypointFilterer creates a new log filterer instance of Entrypoint, bound to a specific deployed contract. -func NewEntrypointFilterer(address common.Address, filterer bind.ContractFilterer) (*EntrypointFilterer, error) { - contract, err := bindEntrypoint(address, nil, nil, filterer) +// NewECDSAValidatorFilterer creates a new log filterer instance of ECDSAValidator, bound to a specific deployed contract. +func NewECDSAValidatorFilterer(address common.Address, filterer bind.ContractFilterer) (*ECDSAValidatorFilterer, error) { + contract, err := bindECDSAValidator(address, nil, nil, filterer) if err != nil { return nil, err } - return &EntrypointFilterer{contract: contract}, nil + return &ECDSAValidatorFilterer{contract: contract}, nil } -// bindEntrypoint binds a generic wrapper to an already deployed contract. -func bindEntrypoint(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(EntrypointABI)) +// bindECDSAValidator binds a generic wrapper to an already deployed contract. +func bindECDSAValidator(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := abi.JSON(strings.NewReader(ECDSAValidatorABI)) if err != nil { return nil, err } @@ -158,46 +158,46 @@ func bindEntrypoint(address common.Address, caller bind.ContractCaller, transact // sets the output to result. The result type might be a single field for simple // returns, a slice of interfaces for anonymous returns and a struct for named // returns. -func (_Entrypoint *EntrypointRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Entrypoint.Contract.EntrypointCaller.contract.Call(opts, result, method, params...) +func (_ECDSAValidator *ECDSAValidatorRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _ECDSAValidator.Contract.ECDSAValidatorCaller.contract.Call(opts, result, method, params...) } // Transfer initiates a plain transaction to move funds to the contract, calling // its default method if one is available. -func (_Entrypoint *EntrypointRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Entrypoint.Contract.EntrypointTransactor.contract.Transfer(opts) +func (_ECDSAValidator *ECDSAValidatorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _ECDSAValidator.Contract.ECDSAValidatorTransactor.contract.Transfer(opts) } // Transact invokes the (paid) contract method with params as input values. -func (_Entrypoint *EntrypointRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Entrypoint.Contract.EntrypointTransactor.contract.Transact(opts, method, params...) +func (_ECDSAValidator *ECDSAValidatorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _ECDSAValidator.Contract.ECDSAValidatorTransactor.contract.Transact(opts, method, params...) } // Call invokes the (constant) contract method with params as input values and // sets the output to result. The result type might be a single field for simple // returns, a slice of interfaces for anonymous returns and a struct for named // returns. -func (_Entrypoint *EntrypointCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Entrypoint.Contract.contract.Call(opts, result, method, params...) +func (_ECDSAValidator *ECDSAValidatorCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { + return _ECDSAValidator.Contract.contract.Call(opts, result, method, params...) } // Transfer initiates a plain transaction to move funds to the contract, calling // its default method if one is available. -func (_Entrypoint *EntrypointTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Entrypoint.Contract.contract.Transfer(opts) +func (_ECDSAValidator *ECDSAValidatorTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _ECDSAValidator.Contract.contract.Transfer(opts) } // Transact invokes the (paid) contract method with params as input values. -func (_Entrypoint *EntrypointTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Entrypoint.Contract.contract.Transact(opts, method, params...) +func (_ECDSAValidator *ECDSAValidatorTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _ECDSAValidator.Contract.contract.Transact(opts, method, params...) } // EcdsaValidatorStorage is a free data retrieval call binding the contract method 0x20709efc. // // Solidity: function ecdsaValidatorStorage(address ) view returns(address owner) -func (_Entrypoint *EntrypointCaller) EcdsaValidatorStorage(opts *bind.CallOpts, arg0 common.Address) (common.Address, error) { +func (_ECDSAValidator *ECDSAValidatorCaller) EcdsaValidatorStorage(opts *bind.CallOpts, arg0 common.Address) (common.Address, error) { var out []interface{} - err := _Entrypoint.contract.Call(opts, &out, "ecdsaValidatorStorage", arg0) + err := _ECDSAValidator.contract.Call(opts, &out, "ecdsaValidatorStorage", arg0) if err != nil { return *new(common.Address), err @@ -212,23 +212,23 @@ func (_Entrypoint *EntrypointCaller) EcdsaValidatorStorage(opts *bind.CallOpts, // EcdsaValidatorStorage is a free data retrieval call binding the contract method 0x20709efc. // // Solidity: function ecdsaValidatorStorage(address ) view returns(address owner) -func (_Entrypoint *EntrypointSession) EcdsaValidatorStorage(arg0 common.Address) (common.Address, error) { - return _Entrypoint.Contract.EcdsaValidatorStorage(&_Entrypoint.CallOpts, arg0) +func (_ECDSAValidator *ECDSAValidatorSession) EcdsaValidatorStorage(arg0 common.Address) (common.Address, error) { + return _ECDSAValidator.Contract.EcdsaValidatorStorage(&_ECDSAValidator.CallOpts, arg0) } // EcdsaValidatorStorage is a free data retrieval call binding the contract method 0x20709efc. // // Solidity: function ecdsaValidatorStorage(address ) view returns(address owner) -func (_Entrypoint *EntrypointCallerSession) EcdsaValidatorStorage(arg0 common.Address) (common.Address, error) { - return _Entrypoint.Contract.EcdsaValidatorStorage(&_Entrypoint.CallOpts, arg0) +func (_ECDSAValidator *ECDSAValidatorCallerSession) EcdsaValidatorStorage(arg0 common.Address) (common.Address, error) { + return _ECDSAValidator.Contract.EcdsaValidatorStorage(&_ECDSAValidator.CallOpts, arg0) } // IsInitialized is a free data retrieval call binding the contract method 0xd60b347f. // // Solidity: function isInitialized(address smartAccount) view returns(bool) -func (_Entrypoint *EntrypointCaller) IsInitialized(opts *bind.CallOpts, smartAccount common.Address) (bool, error) { +func (_ECDSAValidator *ECDSAValidatorCaller) IsInitialized(opts *bind.CallOpts, smartAccount common.Address) (bool, error) { var out []interface{} - err := _Entrypoint.contract.Call(opts, &out, "isInitialized", smartAccount) + err := _ECDSAValidator.contract.Call(opts, &out, "isInitialized", smartAccount) if err != nil { return *new(bool), err @@ -243,23 +243,23 @@ func (_Entrypoint *EntrypointCaller) IsInitialized(opts *bind.CallOpts, smartAcc // IsInitialized is a free data retrieval call binding the contract method 0xd60b347f. // // Solidity: function isInitialized(address smartAccount) view returns(bool) -func (_Entrypoint *EntrypointSession) IsInitialized(smartAccount common.Address) (bool, error) { - return _Entrypoint.Contract.IsInitialized(&_Entrypoint.CallOpts, smartAccount) +func (_ECDSAValidator *ECDSAValidatorSession) IsInitialized(smartAccount common.Address) (bool, error) { + return _ECDSAValidator.Contract.IsInitialized(&_ECDSAValidator.CallOpts, smartAccount) } // IsInitialized is a free data retrieval call binding the contract method 0xd60b347f. // // Solidity: function isInitialized(address smartAccount) view returns(bool) -func (_Entrypoint *EntrypointCallerSession) IsInitialized(smartAccount common.Address) (bool, error) { - return _Entrypoint.Contract.IsInitialized(&_Entrypoint.CallOpts, smartAccount) +func (_ECDSAValidator *ECDSAValidatorCallerSession) IsInitialized(smartAccount common.Address) (bool, error) { + return _ECDSAValidator.Contract.IsInitialized(&_ECDSAValidator.CallOpts, smartAccount) } // IsModuleType is a free data retrieval call binding the contract method 0xecd05961. // // Solidity: function isModuleType(uint256 typeID) pure returns(bool) -func (_Entrypoint *EntrypointCaller) IsModuleType(opts *bind.CallOpts, typeID *big.Int) (bool, error) { +func (_ECDSAValidator *ECDSAValidatorCaller) IsModuleType(opts *bind.CallOpts, typeID *big.Int) (bool, error) { var out []interface{} - err := _Entrypoint.contract.Call(opts, &out, "isModuleType", typeID) + err := _ECDSAValidator.contract.Call(opts, &out, "isModuleType", typeID) if err != nil { return *new(bool), err @@ -274,23 +274,23 @@ func (_Entrypoint *EntrypointCaller) IsModuleType(opts *bind.CallOpts, typeID *b // IsModuleType is a free data retrieval call binding the contract method 0xecd05961. // // Solidity: function isModuleType(uint256 typeID) pure returns(bool) -func (_Entrypoint *EntrypointSession) IsModuleType(typeID *big.Int) (bool, error) { - return _Entrypoint.Contract.IsModuleType(&_Entrypoint.CallOpts, typeID) +func (_ECDSAValidator *ECDSAValidatorSession) IsModuleType(typeID *big.Int) (bool, error) { + return _ECDSAValidator.Contract.IsModuleType(&_ECDSAValidator.CallOpts, typeID) } // IsModuleType is a free data retrieval call binding the contract method 0xecd05961. // // Solidity: function isModuleType(uint256 typeID) pure returns(bool) -func (_Entrypoint *EntrypointCallerSession) IsModuleType(typeID *big.Int) (bool, error) { - return _Entrypoint.Contract.IsModuleType(&_Entrypoint.CallOpts, typeID) +func (_ECDSAValidator *ECDSAValidatorCallerSession) IsModuleType(typeID *big.Int) (bool, error) { + return _ECDSAValidator.Contract.IsModuleType(&_ECDSAValidator.CallOpts, typeID) } // IsValidSignatureWithSender is a free data retrieval call binding the contract method 0xf551e2ee. // // Solidity: function isValidSignatureWithSender(address , bytes32 hash, bytes sig) view returns(bytes4) -func (_Entrypoint *EntrypointCaller) IsValidSignatureWithSender(opts *bind.CallOpts, arg0 common.Address, hash [32]byte, sig []byte) ([4]byte, error) { +func (_ECDSAValidator *ECDSAValidatorCaller) IsValidSignatureWithSender(opts *bind.CallOpts, arg0 common.Address, hash [32]byte, sig []byte) ([4]byte, error) { var out []interface{} - err := _Entrypoint.contract.Call(opts, &out, "isValidSignatureWithSender", arg0, hash, sig) + err := _ECDSAValidator.contract.Call(opts, &out, "isValidSignatureWithSender", arg0, hash, sig) if err != nil { return *new([4]byte), err @@ -305,125 +305,125 @@ func (_Entrypoint *EntrypointCaller) IsValidSignatureWithSender(opts *bind.CallO // IsValidSignatureWithSender is a free data retrieval call binding the contract method 0xf551e2ee. // // Solidity: function isValidSignatureWithSender(address , bytes32 hash, bytes sig) view returns(bytes4) -func (_Entrypoint *EntrypointSession) IsValidSignatureWithSender(arg0 common.Address, hash [32]byte, sig []byte) ([4]byte, error) { - return _Entrypoint.Contract.IsValidSignatureWithSender(&_Entrypoint.CallOpts, arg0, hash, sig) +func (_ECDSAValidator *ECDSAValidatorSession) IsValidSignatureWithSender(arg0 common.Address, hash [32]byte, sig []byte) ([4]byte, error) { + return _ECDSAValidator.Contract.IsValidSignatureWithSender(&_ECDSAValidator.CallOpts, arg0, hash, sig) } // IsValidSignatureWithSender is a free data retrieval call binding the contract method 0xf551e2ee. // // Solidity: function isValidSignatureWithSender(address , bytes32 hash, bytes sig) view returns(bytes4) -func (_Entrypoint *EntrypointCallerSession) IsValidSignatureWithSender(arg0 common.Address, hash [32]byte, sig []byte) ([4]byte, error) { - return _Entrypoint.Contract.IsValidSignatureWithSender(&_Entrypoint.CallOpts, arg0, hash, sig) +func (_ECDSAValidator *ECDSAValidatorCallerSession) IsValidSignatureWithSender(arg0 common.Address, hash [32]byte, sig []byte) ([4]byte, error) { + return _ECDSAValidator.Contract.IsValidSignatureWithSender(&_ECDSAValidator.CallOpts, arg0, hash, sig) } // OnInstall is a paid mutator transaction binding the contract method 0x6d61fe70. // // Solidity: function onInstall(bytes _data) payable returns() -func (_Entrypoint *EntrypointTransactor) OnInstall(opts *bind.TransactOpts, _data []byte) (*types.Transaction, error) { - return _Entrypoint.contract.Transact(opts, "onInstall", _data) +func (_ECDSAValidator *ECDSAValidatorTransactor) OnInstall(opts *bind.TransactOpts, _data []byte) (*types.Transaction, error) { + return _ECDSAValidator.contract.Transact(opts, "onInstall", _data) } // OnInstall is a paid mutator transaction binding the contract method 0x6d61fe70. // // Solidity: function onInstall(bytes _data) payable returns() -func (_Entrypoint *EntrypointSession) OnInstall(_data []byte) (*types.Transaction, error) { - return _Entrypoint.Contract.OnInstall(&_Entrypoint.TransactOpts, _data) +func (_ECDSAValidator *ECDSAValidatorSession) OnInstall(_data []byte) (*types.Transaction, error) { + return _ECDSAValidator.Contract.OnInstall(&_ECDSAValidator.TransactOpts, _data) } // OnInstall is a paid mutator transaction binding the contract method 0x6d61fe70. // // Solidity: function onInstall(bytes _data) payable returns() -func (_Entrypoint *EntrypointTransactorSession) OnInstall(_data []byte) (*types.Transaction, error) { - return _Entrypoint.Contract.OnInstall(&_Entrypoint.TransactOpts, _data) +func (_ECDSAValidator *ECDSAValidatorTransactorSession) OnInstall(_data []byte) (*types.Transaction, error) { + return _ECDSAValidator.Contract.OnInstall(&_ECDSAValidator.TransactOpts, _data) } // OnUninstall is a paid mutator transaction binding the contract method 0x8a91b0e3. // // Solidity: function onUninstall(bytes ) payable returns() -func (_Entrypoint *EntrypointTransactor) OnUninstall(opts *bind.TransactOpts, arg0 []byte) (*types.Transaction, error) { - return _Entrypoint.contract.Transact(opts, "onUninstall", arg0) +func (_ECDSAValidator *ECDSAValidatorTransactor) OnUninstall(opts *bind.TransactOpts, arg0 []byte) (*types.Transaction, error) { + return _ECDSAValidator.contract.Transact(opts, "onUninstall", arg0) } // OnUninstall is a paid mutator transaction binding the contract method 0x8a91b0e3. // // Solidity: function onUninstall(bytes ) payable returns() -func (_Entrypoint *EntrypointSession) OnUninstall(arg0 []byte) (*types.Transaction, error) { - return _Entrypoint.Contract.OnUninstall(&_Entrypoint.TransactOpts, arg0) +func (_ECDSAValidator *ECDSAValidatorSession) OnUninstall(arg0 []byte) (*types.Transaction, error) { + return _ECDSAValidator.Contract.OnUninstall(&_ECDSAValidator.TransactOpts, arg0) } // OnUninstall is a paid mutator transaction binding the contract method 0x8a91b0e3. // // Solidity: function onUninstall(bytes ) payable returns() -func (_Entrypoint *EntrypointTransactorSession) OnUninstall(arg0 []byte) (*types.Transaction, error) { - return _Entrypoint.Contract.OnUninstall(&_Entrypoint.TransactOpts, arg0) +func (_ECDSAValidator *ECDSAValidatorTransactorSession) OnUninstall(arg0 []byte) (*types.Transaction, error) { + return _ECDSAValidator.Contract.OnUninstall(&_ECDSAValidator.TransactOpts, arg0) } // PostCheck is a paid mutator transaction binding the contract method 0xaacbd72a. // // Solidity: function postCheck(bytes hookData, bool success, bytes res) payable returns() -func (_Entrypoint *EntrypointTransactor) PostCheck(opts *bind.TransactOpts, hookData []byte, success bool, res []byte) (*types.Transaction, error) { - return _Entrypoint.contract.Transact(opts, "postCheck", hookData, success, res) +func (_ECDSAValidator *ECDSAValidatorTransactor) PostCheck(opts *bind.TransactOpts, hookData []byte, success bool, res []byte) (*types.Transaction, error) { + return _ECDSAValidator.contract.Transact(opts, "postCheck", hookData, success, res) } // PostCheck is a paid mutator transaction binding the contract method 0xaacbd72a. // // Solidity: function postCheck(bytes hookData, bool success, bytes res) payable returns() -func (_Entrypoint *EntrypointSession) PostCheck(hookData []byte, success bool, res []byte) (*types.Transaction, error) { - return _Entrypoint.Contract.PostCheck(&_Entrypoint.TransactOpts, hookData, success, res) +func (_ECDSAValidator *ECDSAValidatorSession) PostCheck(hookData []byte, success bool, res []byte) (*types.Transaction, error) { + return _ECDSAValidator.Contract.PostCheck(&_ECDSAValidator.TransactOpts, hookData, success, res) } // PostCheck is a paid mutator transaction binding the contract method 0xaacbd72a. // // Solidity: function postCheck(bytes hookData, bool success, bytes res) payable returns() -func (_Entrypoint *EntrypointTransactorSession) PostCheck(hookData []byte, success bool, res []byte) (*types.Transaction, error) { - return _Entrypoint.Contract.PostCheck(&_Entrypoint.TransactOpts, hookData, success, res) +func (_ECDSAValidator *ECDSAValidatorTransactorSession) PostCheck(hookData []byte, success bool, res []byte) (*types.Transaction, error) { + return _ECDSAValidator.Contract.PostCheck(&_ECDSAValidator.TransactOpts, hookData, success, res) } // PreCheck is a paid mutator transaction binding the contract method 0xd68f6025. // // Solidity: function preCheck(address msgSender, uint256 value, bytes ) payable returns(bytes) -func (_Entrypoint *EntrypointTransactor) PreCheck(opts *bind.TransactOpts, msgSender common.Address, value *big.Int, arg2 []byte) (*types.Transaction, error) { - return _Entrypoint.contract.Transact(opts, "preCheck", msgSender, value, arg2) +func (_ECDSAValidator *ECDSAValidatorTransactor) PreCheck(opts *bind.TransactOpts, msgSender common.Address, value *big.Int, arg2 []byte) (*types.Transaction, error) { + return _ECDSAValidator.contract.Transact(opts, "preCheck", msgSender, value, arg2) } // PreCheck is a paid mutator transaction binding the contract method 0xd68f6025. // // Solidity: function preCheck(address msgSender, uint256 value, bytes ) payable returns(bytes) -func (_Entrypoint *EntrypointSession) PreCheck(msgSender common.Address, value *big.Int, arg2 []byte) (*types.Transaction, error) { - return _Entrypoint.Contract.PreCheck(&_Entrypoint.TransactOpts, msgSender, value, arg2) +func (_ECDSAValidator *ECDSAValidatorSession) PreCheck(msgSender common.Address, value *big.Int, arg2 []byte) (*types.Transaction, error) { + return _ECDSAValidator.Contract.PreCheck(&_ECDSAValidator.TransactOpts, msgSender, value, arg2) } // PreCheck is a paid mutator transaction binding the contract method 0xd68f6025. // // Solidity: function preCheck(address msgSender, uint256 value, bytes ) payable returns(bytes) -func (_Entrypoint *EntrypointTransactorSession) PreCheck(msgSender common.Address, value *big.Int, arg2 []byte) (*types.Transaction, error) { - return _Entrypoint.Contract.PreCheck(&_Entrypoint.TransactOpts, msgSender, value, arg2) +func (_ECDSAValidator *ECDSAValidatorTransactorSession) PreCheck(msgSender common.Address, value *big.Int, arg2 []byte) (*types.Transaction, error) { + return _ECDSAValidator.Contract.PreCheck(&_ECDSAValidator.TransactOpts, msgSender, value, arg2) } // ValidateUserOp is a paid mutator transaction binding the contract method 0x97003203. // // Solidity: function validateUserOp((address,uint256,bytes,bytes,bytes32,uint256,bytes32,bytes,bytes) userOp, bytes32 userOpHash) payable returns(uint256) -func (_Entrypoint *EntrypointTransactor) ValidateUserOp(opts *bind.TransactOpts, userOp PackedUserOperation, userOpHash [32]byte) (*types.Transaction, error) { - return _Entrypoint.contract.Transact(opts, "validateUserOp", userOp, userOpHash) +func (_ECDSAValidator *ECDSAValidatorTransactor) ValidateUserOp(opts *bind.TransactOpts, userOp PackedUserOperation, userOpHash [32]byte) (*types.Transaction, error) { + return _ECDSAValidator.contract.Transact(opts, "validateUserOp", userOp, userOpHash) } // ValidateUserOp is a paid mutator transaction binding the contract method 0x97003203. // // Solidity: function validateUserOp((address,uint256,bytes,bytes,bytes32,uint256,bytes32,bytes,bytes) userOp, bytes32 userOpHash) payable returns(uint256) -func (_Entrypoint *EntrypointSession) ValidateUserOp(userOp PackedUserOperation, userOpHash [32]byte) (*types.Transaction, error) { - return _Entrypoint.Contract.ValidateUserOp(&_Entrypoint.TransactOpts, userOp, userOpHash) +func (_ECDSAValidator *ECDSAValidatorSession) ValidateUserOp(userOp PackedUserOperation, userOpHash [32]byte) (*types.Transaction, error) { + return _ECDSAValidator.Contract.ValidateUserOp(&_ECDSAValidator.TransactOpts, userOp, userOpHash) } // ValidateUserOp is a paid mutator transaction binding the contract method 0x97003203. // // Solidity: function validateUserOp((address,uint256,bytes,bytes,bytes32,uint256,bytes32,bytes,bytes) userOp, bytes32 userOpHash) payable returns(uint256) -func (_Entrypoint *EntrypointTransactorSession) ValidateUserOp(userOp PackedUserOperation, userOpHash [32]byte) (*types.Transaction, error) { - return _Entrypoint.Contract.ValidateUserOp(&_Entrypoint.TransactOpts, userOp, userOpHash) +func (_ECDSAValidator *ECDSAValidatorTransactorSession) ValidateUserOp(userOp PackedUserOperation, userOpHash [32]byte) (*types.Transaction, error) { + return _ECDSAValidator.Contract.ValidateUserOp(&_ECDSAValidator.TransactOpts, userOp, userOpHash) } -// EntrypointOwnerRegisteredIterator is returned from FilterOwnerRegistered and is used to iterate over the raw logs and unpacked data for OwnerRegistered events raised by the Entrypoint contract. -type EntrypointOwnerRegisteredIterator struct { - Event *EntrypointOwnerRegistered // Event containing the contract specifics and raw log +// ECDSAValidatorOwnerRegisteredIterator is returned from FilterOwnerRegistered and is used to iterate over the raw logs and unpacked data for OwnerRegistered events raised by the ECDSAValidator contract. +type ECDSAValidatorOwnerRegisteredIterator struct { + Event *ECDSAValidatorOwnerRegistered // Event containing the contract specifics and raw log contract *bind.BoundContract // Generic contract to use for unpacking event data event string // Event name to use for unpacking event data @@ -437,7 +437,7 @@ type EntrypointOwnerRegisteredIterator struct { // Next advances the iterator to the subsequent event, returning whether there // are any more events found. In case of a retrieval or parsing error, false is // returned and Error() can be queried for the exact failure. -func (it *EntrypointOwnerRegisteredIterator) Next() bool { +func (it *ECDSAValidatorOwnerRegisteredIterator) Next() bool { // If the iterator failed, stop iterating if it.fail != nil { return false @@ -446,7 +446,7 @@ func (it *EntrypointOwnerRegisteredIterator) Next() bool { if it.done { select { case log := <-it.logs: - it.Event = new(EntrypointOwnerRegistered) + it.Event = new(ECDSAValidatorOwnerRegistered) if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { it.fail = err return false @@ -461,7 +461,7 @@ func (it *EntrypointOwnerRegisteredIterator) Next() bool { // Iterator still in progress, wait for either a data or an error event select { case log := <-it.logs: - it.Event = new(EntrypointOwnerRegistered) + it.Event = new(ECDSAValidatorOwnerRegistered) if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { it.fail = err return false @@ -477,19 +477,19 @@ func (it *EntrypointOwnerRegisteredIterator) Next() bool { } // Error returns any retrieval or parsing error occurred during filtering. -func (it *EntrypointOwnerRegisteredIterator) Error() error { +func (it *ECDSAValidatorOwnerRegisteredIterator) Error() error { return it.fail } // Close terminates the iteration process, releasing any pending underlying // resources. -func (it *EntrypointOwnerRegisteredIterator) Close() error { +func (it *ECDSAValidatorOwnerRegisteredIterator) Close() error { it.sub.Unsubscribe() return nil } -// EntrypointOwnerRegistered represents a OwnerRegistered event raised by the Entrypoint contract. -type EntrypointOwnerRegistered struct { +// ECDSAValidatorOwnerRegistered represents a OwnerRegistered event raised by the ECDSAValidator contract. +type ECDSAValidatorOwnerRegistered struct { Kernel common.Address Owner common.Address Raw types.Log // Blockchain specific contextual infos @@ -498,7 +498,7 @@ type EntrypointOwnerRegistered struct { // FilterOwnerRegistered is a free log retrieval operation binding the contract event 0xa5e1f8b4009110f5525798d04ae2125421a12d0590aa52c13682ff1bd3c492ca. // // Solidity: event OwnerRegistered(address indexed kernel, address indexed owner) -func (_Entrypoint *EntrypointFilterer) FilterOwnerRegistered(opts *bind.FilterOpts, kernel []common.Address, owner []common.Address) (*EntrypointOwnerRegisteredIterator, error) { +func (_ECDSAValidator *ECDSAValidatorFilterer) FilterOwnerRegistered(opts *bind.FilterOpts, kernel []common.Address, owner []common.Address) (*ECDSAValidatorOwnerRegisteredIterator, error) { var kernelRule []interface{} for _, kernelItem := range kernel { @@ -509,17 +509,17 @@ func (_Entrypoint *EntrypointFilterer) FilterOwnerRegistered(opts *bind.FilterOp ownerRule = append(ownerRule, ownerItem) } - logs, sub, err := _Entrypoint.contract.FilterLogs(opts, "OwnerRegistered", kernelRule, ownerRule) + logs, sub, err := _ECDSAValidator.contract.FilterLogs(opts, "OwnerRegistered", kernelRule, ownerRule) if err != nil { return nil, err } - return &EntrypointOwnerRegisteredIterator{contract: _Entrypoint.contract, event: "OwnerRegistered", logs: logs, sub: sub}, nil + return &ECDSAValidatorOwnerRegisteredIterator{contract: _ECDSAValidator.contract, event: "OwnerRegistered", logs: logs, sub: sub}, nil } // WatchOwnerRegistered is a free log subscription operation binding the contract event 0xa5e1f8b4009110f5525798d04ae2125421a12d0590aa52c13682ff1bd3c492ca. // // Solidity: event OwnerRegistered(address indexed kernel, address indexed owner) -func (_Entrypoint *EntrypointFilterer) WatchOwnerRegistered(opts *bind.WatchOpts, sink chan<- *EntrypointOwnerRegistered, kernel []common.Address, owner []common.Address) (event.Subscription, error) { +func (_ECDSAValidator *ECDSAValidatorFilterer) WatchOwnerRegistered(opts *bind.WatchOpts, sink chan<- *ECDSAValidatorOwnerRegistered, kernel []common.Address, owner []common.Address) (event.Subscription, error) { var kernelRule []interface{} for _, kernelItem := range kernel { @@ -530,7 +530,7 @@ func (_Entrypoint *EntrypointFilterer) WatchOwnerRegistered(opts *bind.WatchOpts ownerRule = append(ownerRule, ownerItem) } - logs, sub, err := _Entrypoint.contract.WatchLogs(opts, "OwnerRegistered", kernelRule, ownerRule) + logs, sub, err := _ECDSAValidator.contract.WatchLogs(opts, "OwnerRegistered", kernelRule, ownerRule) if err != nil { return nil, err } @@ -540,8 +540,8 @@ func (_Entrypoint *EntrypointFilterer) WatchOwnerRegistered(opts *bind.WatchOpts select { case log := <-logs: // New log arrived, parse the event and forward to the user - event := new(EntrypointOwnerRegistered) - if err := _Entrypoint.contract.UnpackLog(event, "OwnerRegistered", log); err != nil { + event := new(ECDSAValidatorOwnerRegistered) + if err := _ECDSAValidator.contract.UnpackLog(event, "OwnerRegistered", log); err != nil { return err } event.Raw = log @@ -565,9 +565,9 @@ func (_Entrypoint *EntrypointFilterer) WatchOwnerRegistered(opts *bind.WatchOpts // ParseOwnerRegistered is a log parse operation binding the contract event 0xa5e1f8b4009110f5525798d04ae2125421a12d0590aa52c13682ff1bd3c492ca. // // Solidity: event OwnerRegistered(address indexed kernel, address indexed owner) -func (_Entrypoint *EntrypointFilterer) ParseOwnerRegistered(log types.Log) (*EntrypointOwnerRegistered, error) { - event := new(EntrypointOwnerRegistered) - if err := _Entrypoint.contract.UnpackLog(event, "OwnerRegistered", log); err != nil { +func (_ECDSAValidator *ECDSAValidatorFilterer) ParseOwnerRegistered(log types.Log) (*ECDSAValidatorOwnerRegistered, error) { + event := new(ECDSAValidatorOwnerRegistered) + if err := _ECDSAValidator.contract.UnpackLog(event, "OwnerRegistered", log); err != nil { return nil, err } event.Raw = log diff --git a/internal/services/contracts_events_consumer.go b/internal/services/contracts_events_consumer.go index c4a9913d..37b2aca6 100644 --- a/internal/services/contracts_events_consumer.go +++ b/internal/services/contracts_events_consumer.go @@ -69,7 +69,7 @@ const ( TokensTransferredForDevice EventName = "TokensTransferredForDevice" TokensTransferredForConnectionStreak EventName = "TokensTransferredForConnectionStreak" - // Zerodev Entrypoint. + // Kernal ECDSA Validator. OwnerRegistered EventName = "OwnerRegistered" ) @@ -106,7 +106,7 @@ func (c *ContractsEventsConsumer) Process(ctx context.Context, event *shared.Clo DCNRegistryAddr := common.HexToAddress(c.settings.DCNRegistryAddr) DCNResolverAddr := common.HexToAddress(c.settings.DCNResolverAddr) RewardsContractAddr := common.HexToAddress(c.settings.RewardsContractAddr) - entrypointAddr := common.HexToAddress(c.settings.EntryPointAddr) + KernalECDSAValidator := common.HexToAddress(c.settings.KernalECDSAValidator) var data ContractEventData if err := json.Unmarshal(event.Data, &data); err != nil { @@ -187,14 +187,10 @@ func (c *ContractsEventsConsumer) Process(ctx context.Context, event *shared.Clo case TokensTransferredForConnectionStreak: return c.handleTokensTransferredForConnectionStreak(ctx, &data) } - case entrypointAddr: - - b, _ := json.MarshalIndent(data, "", " ") - fmt.Println(string(b)) - + case KernalECDSAValidator: switch eventName { case OwnerRegistered: - return c.handleOwnerRegistered(ctx, &data) + return c.handleOwnerRegisteredEvent(ctx, &data) } } @@ -697,14 +693,14 @@ func (c *ContractsEventsConsumer) handleAftermarketDeviceAddressResetEvent(ctx c return err } -func (c *ContractsEventsConsumer) handleOwnerRegistered(ctx context.Context, e *ContractEventData) error { +func (c *ContractsEventsConsumer) handleOwnerRegisteredEvent(ctx context.Context, e *ContractEventData) error { var args OwnerRegisteredData if err := json.Unmarshal(e.Arguments, &args); err != nil { return err } kernal := models.KernalAccount{ - Kernal: args.Kernal.Bytes(), + Kernal: args.Kernel.Bytes(), OwnerAddress: args.Owner.Bytes(), } diff --git a/internal/services/event_data_models.go b/internal/services/event_data_models.go index 8cff0159..e685fced 100644 --- a/internal/services/event_data_models.go +++ b/internal/services/event_data_models.go @@ -170,6 +170,6 @@ type DeviceDefinitionTableCreatedData struct { } type OwnerRegisteredData struct { - Kernal common.Address + Kernel common.Address Owner common.Address } diff --git a/settings.sample.yaml b/settings.sample.yaml index d4458906..9f61c4da 100644 --- a/settings.sample.yaml +++ b/settings.sample.yaml @@ -19,4 +19,4 @@ REWARDS_CONTRACT_ADDRESS: "0x375885164266d48C48abbbb439Be98864Ae62bBE" BASE_IMAGE_URL: "https://devices-api.dev.dimo.zone/v1/" TABLELAND_API_GATEWAY: "https://testnets.tableland.network/" ETHEREUM_RPC_URL: "http://127.0.0.1:8545" -ENTRYPOINT_ADDR: "0x8104e3Ad430EA6d354d013A6789fDFc71E671c43" +KERNAL_ECDSA_VALIDATOR: "0x8104e3Ad430EA6d354d013A6789fDFc71E671c43" From 593364eb595f59ecae03f5570be1dd04f2771520 Mon Sep 17 00:00:00 2001 From: Allyson-English Date: Wed, 10 Jul 2024 15:40:36 -0400 Subject: [PATCH 03/12] kernel --- ...31_kernal_tbl.sql => 00031_kernel_tbl.sql} | 8 +- models/boil_table_names.go | 4 +- ...{kernal_accounts.go => kernel_accounts.go} | 480 +++++++++--------- 3 files changed, 246 insertions(+), 246 deletions(-) rename migrations/{00031_kernal_tbl.sql => 00031_kernel_tbl.sql} (50%) rename models/{kernal_accounts.go => kernel_accounts.go} (54%) diff --git a/migrations/00031_kernal_tbl.sql b/migrations/00031_kernel_tbl.sql similarity index 50% rename from migrations/00031_kernal_tbl.sql rename to migrations/00031_kernel_tbl.sql index 1b9c4595..772cc308 100644 --- a/migrations/00031_kernal_tbl.sql +++ b/migrations/00031_kernel_tbl.sql @@ -1,12 +1,12 @@ -- +goose Up -- +goose StatementBegin -CREATE TABLE kernal_accounts( - kernal bytea CONSTRAINT kernal_accounts_kernal_address_check CHECK (length(kernal) = 20) PRIMARY KEY, - owner_address bytea CONSTRAINT kernal_accounts_owner_address_check CHECK (length(owner_address) = 20) NOT NULL -- TODO(ae): should this reference any other table? +CREATE TABLE kernel_accounts( + kernel bytea CONSTRAINT kernel_accounts_kernel_address_check CHECK (length(kernel) = 20) PRIMARY KEY, + owner_address bytea CONSTRAINT kernel_accounts_owner_address_check CHECK (length(owner_address) = 20) NOT NULL -- TODO(ae): should this reference any other table? ); -- +goose StatementEnd -- +goose Down -- +goose StatementBegin -DROP TABLE kernal_accounts; +DROP TABLE kernel_accounts; -- +goose StatementEnd diff --git a/models/boil_table_names.go b/models/boil_table_names.go index bcb02508..481f9c7a 100644 --- a/models/boil_table_names.go +++ b/models/boil_table_names.go @@ -6,7 +6,7 @@ package models var TableNames = struct { AftermarketDevices string DCNS string - KernalAccounts string + KernelAccounts string Manufacturers string Privileges string Rewards string @@ -15,7 +15,7 @@ var TableNames = struct { }{ AftermarketDevices: "aftermarket_devices", DCNS: "dcns", - KernalAccounts: "kernal_accounts", + KernelAccounts: "kernel_accounts", Manufacturers: "manufacturers", Privileges: "privileges", Rewards: "rewards", diff --git a/models/kernal_accounts.go b/models/kernel_accounts.go similarity index 54% rename from models/kernal_accounts.go rename to models/kernel_accounts.go index f673169f..8875a89f 100644 --- a/models/kernal_accounts.go +++ b/models/kernel_accounts.go @@ -21,88 +21,88 @@ import ( "github.com/volatiletech/strmangle" ) -// KernalAccount is an object representing the database table. -type KernalAccount struct { - Kernal []byte `boil:"kernal" json:"kernal" toml:"kernal" yaml:"kernal"` +// KernelAccount is an object representing the database table. +type KernelAccount struct { + Kernel []byte `boil:"kernel" json:"kernel" toml:"kernel" yaml:"kernel"` OwnerAddress []byte `boil:"owner_address" json:"owner_address" toml:"owner_address" yaml:"owner_address"` - R *kernalAccountR `boil:"-" json:"-" toml:"-" yaml:"-"` - L kernalAccountL `boil:"-" json:"-" toml:"-" yaml:"-"` + R *kernelAccountR `boil:"-" json:"-" toml:"-" yaml:"-"` + L kernelAccountL `boil:"-" json:"-" toml:"-" yaml:"-"` } -var KernalAccountColumns = struct { - Kernal string +var KernelAccountColumns = struct { + Kernel string OwnerAddress string }{ - Kernal: "kernal", + Kernel: "kernel", OwnerAddress: "owner_address", } -var KernalAccountTableColumns = struct { - Kernal string +var KernelAccountTableColumns = struct { + Kernel string OwnerAddress string }{ - Kernal: "kernal_accounts.kernal", - OwnerAddress: "kernal_accounts.owner_address", + Kernel: "kernel_accounts.kernel", + OwnerAddress: "kernel_accounts.owner_address", } // Generated where -var KernalAccountWhere = struct { - Kernal whereHelper__byte +var KernelAccountWhere = struct { + Kernel whereHelper__byte OwnerAddress whereHelper__byte }{ - Kernal: whereHelper__byte{field: "\"identity_api\".\"kernal_accounts\".\"kernal\""}, - OwnerAddress: whereHelper__byte{field: "\"identity_api\".\"kernal_accounts\".\"owner_address\""}, + Kernel: whereHelper__byte{field: "\"identity_api\".\"kernel_accounts\".\"kernel\""}, + OwnerAddress: whereHelper__byte{field: "\"identity_api\".\"kernel_accounts\".\"owner_address\""}, } -// KernalAccountRels is where relationship names are stored. -var KernalAccountRels = struct { +// KernelAccountRels is where relationship names are stored. +var KernelAccountRels = struct { }{} -// kernalAccountR is where relationships are stored. -type kernalAccountR struct { +// kernelAccountR is where relationships are stored. +type kernelAccountR struct { } // NewStruct creates a new relationship struct -func (*kernalAccountR) NewStruct() *kernalAccountR { - return &kernalAccountR{} +func (*kernelAccountR) NewStruct() *kernelAccountR { + return &kernelAccountR{} } -// kernalAccountL is where Load methods for each relationship are stored. -type kernalAccountL struct{} +// kernelAccountL is where Load methods for each relationship are stored. +type kernelAccountL struct{} var ( - kernalAccountAllColumns = []string{"kernal", "owner_address"} - kernalAccountColumnsWithoutDefault = []string{"kernal", "owner_address"} - kernalAccountColumnsWithDefault = []string{} - kernalAccountPrimaryKeyColumns = []string{"kernal"} - kernalAccountGeneratedColumns = []string{} + kernelAccountAllColumns = []string{"kernel", "owner_address"} + kernelAccountColumnsWithoutDefault = []string{"kernel", "owner_address"} + kernelAccountColumnsWithDefault = []string{} + kernelAccountPrimaryKeyColumns = []string{"kernel"} + kernelAccountGeneratedColumns = []string{} ) type ( - // KernalAccountSlice is an alias for a slice of pointers to KernalAccount. - // This should almost always be used instead of []KernalAccount. - KernalAccountSlice []*KernalAccount - // KernalAccountHook is the signature for custom KernalAccount hook methods - KernalAccountHook func(context.Context, boil.ContextExecutor, *KernalAccount) error + // KernelAccountSlice is an alias for a slice of pointers to KernelAccount. + // This should almost always be used instead of []KernelAccount. + KernelAccountSlice []*KernelAccount + // KernelAccountHook is the signature for custom KernelAccount hook methods + KernelAccountHook func(context.Context, boil.ContextExecutor, *KernelAccount) error - kernalAccountQuery struct { + kernelAccountQuery struct { *queries.Query } ) // Cache for insert, update and upsert var ( - kernalAccountType = reflect.TypeOf(&KernalAccount{}) - kernalAccountMapping = queries.MakeStructMapping(kernalAccountType) - kernalAccountPrimaryKeyMapping, _ = queries.BindMapping(kernalAccountType, kernalAccountMapping, kernalAccountPrimaryKeyColumns) - kernalAccountInsertCacheMut sync.RWMutex - kernalAccountInsertCache = make(map[string]insertCache) - kernalAccountUpdateCacheMut sync.RWMutex - kernalAccountUpdateCache = make(map[string]updateCache) - kernalAccountUpsertCacheMut sync.RWMutex - kernalAccountUpsertCache = make(map[string]insertCache) + kernelAccountType = reflect.TypeOf(&KernelAccount{}) + kernelAccountMapping = queries.MakeStructMapping(kernelAccountType) + kernelAccountPrimaryKeyMapping, _ = queries.BindMapping(kernelAccountType, kernelAccountMapping, kernelAccountPrimaryKeyColumns) + kernelAccountInsertCacheMut sync.RWMutex + kernelAccountInsertCache = make(map[string]insertCache) + kernelAccountUpdateCacheMut sync.RWMutex + kernelAccountUpdateCache = make(map[string]updateCache) + kernelAccountUpsertCacheMut sync.RWMutex + kernelAccountUpsertCache = make(map[string]insertCache) ) var ( @@ -113,36 +113,36 @@ var ( _ = qmhelper.Where ) -var kernalAccountAfterSelectMu sync.Mutex -var kernalAccountAfterSelectHooks []KernalAccountHook +var kernelAccountAfterSelectMu sync.Mutex +var kernelAccountAfterSelectHooks []KernelAccountHook -var kernalAccountBeforeInsertMu sync.Mutex -var kernalAccountBeforeInsertHooks []KernalAccountHook -var kernalAccountAfterInsertMu sync.Mutex -var kernalAccountAfterInsertHooks []KernalAccountHook +var kernelAccountBeforeInsertMu sync.Mutex +var kernelAccountBeforeInsertHooks []KernelAccountHook +var kernelAccountAfterInsertMu sync.Mutex +var kernelAccountAfterInsertHooks []KernelAccountHook -var kernalAccountBeforeUpdateMu sync.Mutex -var kernalAccountBeforeUpdateHooks []KernalAccountHook -var kernalAccountAfterUpdateMu sync.Mutex -var kernalAccountAfterUpdateHooks []KernalAccountHook +var kernelAccountBeforeUpdateMu sync.Mutex +var kernelAccountBeforeUpdateHooks []KernelAccountHook +var kernelAccountAfterUpdateMu sync.Mutex +var kernelAccountAfterUpdateHooks []KernelAccountHook -var kernalAccountBeforeDeleteMu sync.Mutex -var kernalAccountBeforeDeleteHooks []KernalAccountHook -var kernalAccountAfterDeleteMu sync.Mutex -var kernalAccountAfterDeleteHooks []KernalAccountHook +var kernelAccountBeforeDeleteMu sync.Mutex +var kernelAccountBeforeDeleteHooks []KernelAccountHook +var kernelAccountAfterDeleteMu sync.Mutex +var kernelAccountAfterDeleteHooks []KernelAccountHook -var kernalAccountBeforeUpsertMu sync.Mutex -var kernalAccountBeforeUpsertHooks []KernalAccountHook -var kernalAccountAfterUpsertMu sync.Mutex -var kernalAccountAfterUpsertHooks []KernalAccountHook +var kernelAccountBeforeUpsertMu sync.Mutex +var kernelAccountBeforeUpsertHooks []KernelAccountHook +var kernelAccountAfterUpsertMu sync.Mutex +var kernelAccountAfterUpsertHooks []KernelAccountHook // doAfterSelectHooks executes all "after Select" hooks. -func (o *KernalAccount) doAfterSelectHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { +func (o *KernelAccount) doAfterSelectHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { if boil.HooksAreSkipped(ctx) { return nil } - for _, hook := range kernalAccountAfterSelectHooks { + for _, hook := range kernelAccountAfterSelectHooks { if err := hook(ctx, exec, o); err != nil { return err } @@ -152,12 +152,12 @@ func (o *KernalAccount) doAfterSelectHooks(ctx context.Context, exec boil.Contex } // doBeforeInsertHooks executes all "before insert" hooks. -func (o *KernalAccount) doBeforeInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { +func (o *KernelAccount) doBeforeInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { if boil.HooksAreSkipped(ctx) { return nil } - for _, hook := range kernalAccountBeforeInsertHooks { + for _, hook := range kernelAccountBeforeInsertHooks { if err := hook(ctx, exec, o); err != nil { return err } @@ -167,12 +167,12 @@ func (o *KernalAccount) doBeforeInsertHooks(ctx context.Context, exec boil.Conte } // doAfterInsertHooks executes all "after Insert" hooks. -func (o *KernalAccount) doAfterInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { +func (o *KernelAccount) doAfterInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { if boil.HooksAreSkipped(ctx) { return nil } - for _, hook := range kernalAccountAfterInsertHooks { + for _, hook := range kernelAccountAfterInsertHooks { if err := hook(ctx, exec, o); err != nil { return err } @@ -182,12 +182,12 @@ func (o *KernalAccount) doAfterInsertHooks(ctx context.Context, exec boil.Contex } // doBeforeUpdateHooks executes all "before Update" hooks. -func (o *KernalAccount) doBeforeUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { +func (o *KernelAccount) doBeforeUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { if boil.HooksAreSkipped(ctx) { return nil } - for _, hook := range kernalAccountBeforeUpdateHooks { + for _, hook := range kernelAccountBeforeUpdateHooks { if err := hook(ctx, exec, o); err != nil { return err } @@ -197,12 +197,12 @@ func (o *KernalAccount) doBeforeUpdateHooks(ctx context.Context, exec boil.Conte } // doAfterUpdateHooks executes all "after Update" hooks. -func (o *KernalAccount) doAfterUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { +func (o *KernelAccount) doAfterUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { if boil.HooksAreSkipped(ctx) { return nil } - for _, hook := range kernalAccountAfterUpdateHooks { + for _, hook := range kernelAccountAfterUpdateHooks { if err := hook(ctx, exec, o); err != nil { return err } @@ -212,12 +212,12 @@ func (o *KernalAccount) doAfterUpdateHooks(ctx context.Context, exec boil.Contex } // doBeforeDeleteHooks executes all "before Delete" hooks. -func (o *KernalAccount) doBeforeDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { +func (o *KernelAccount) doBeforeDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { if boil.HooksAreSkipped(ctx) { return nil } - for _, hook := range kernalAccountBeforeDeleteHooks { + for _, hook := range kernelAccountBeforeDeleteHooks { if err := hook(ctx, exec, o); err != nil { return err } @@ -227,12 +227,12 @@ func (o *KernalAccount) doBeforeDeleteHooks(ctx context.Context, exec boil.Conte } // doAfterDeleteHooks executes all "after Delete" hooks. -func (o *KernalAccount) doAfterDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { +func (o *KernelAccount) doAfterDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { if boil.HooksAreSkipped(ctx) { return nil } - for _, hook := range kernalAccountAfterDeleteHooks { + for _, hook := range kernelAccountAfterDeleteHooks { if err := hook(ctx, exec, o); err != nil { return err } @@ -242,12 +242,12 @@ func (o *KernalAccount) doAfterDeleteHooks(ctx context.Context, exec boil.Contex } // doBeforeUpsertHooks executes all "before Upsert" hooks. -func (o *KernalAccount) doBeforeUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { +func (o *KernelAccount) doBeforeUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { if boil.HooksAreSkipped(ctx) { return nil } - for _, hook := range kernalAccountBeforeUpsertHooks { + for _, hook := range kernelAccountBeforeUpsertHooks { if err := hook(ctx, exec, o); err != nil { return err } @@ -257,12 +257,12 @@ func (o *KernalAccount) doBeforeUpsertHooks(ctx context.Context, exec boil.Conte } // doAfterUpsertHooks executes all "after Upsert" hooks. -func (o *KernalAccount) doAfterUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { +func (o *KernelAccount) doAfterUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { if boil.HooksAreSkipped(ctx) { return nil } - for _, hook := range kernalAccountAfterUpsertHooks { + for _, hook := range kernelAccountAfterUpsertHooks { if err := hook(ctx, exec, o); err != nil { return err } @@ -271,51 +271,51 @@ func (o *KernalAccount) doAfterUpsertHooks(ctx context.Context, exec boil.Contex return nil } -// AddKernalAccountHook registers your hook function for all future operations. -func AddKernalAccountHook(hookPoint boil.HookPoint, kernalAccountHook KernalAccountHook) { +// AddKernelAccountHook registers your hook function for all future operations. +func AddKernelAccountHook(hookPoint boil.HookPoint, kernelAccountHook KernelAccountHook) { switch hookPoint { case boil.AfterSelectHook: - kernalAccountAfterSelectMu.Lock() - kernalAccountAfterSelectHooks = append(kernalAccountAfterSelectHooks, kernalAccountHook) - kernalAccountAfterSelectMu.Unlock() + kernelAccountAfterSelectMu.Lock() + kernelAccountAfterSelectHooks = append(kernelAccountAfterSelectHooks, kernelAccountHook) + kernelAccountAfterSelectMu.Unlock() case boil.BeforeInsertHook: - kernalAccountBeforeInsertMu.Lock() - kernalAccountBeforeInsertHooks = append(kernalAccountBeforeInsertHooks, kernalAccountHook) - kernalAccountBeforeInsertMu.Unlock() + kernelAccountBeforeInsertMu.Lock() + kernelAccountBeforeInsertHooks = append(kernelAccountBeforeInsertHooks, kernelAccountHook) + kernelAccountBeforeInsertMu.Unlock() case boil.AfterInsertHook: - kernalAccountAfterInsertMu.Lock() - kernalAccountAfterInsertHooks = append(kernalAccountAfterInsertHooks, kernalAccountHook) - kernalAccountAfterInsertMu.Unlock() + kernelAccountAfterInsertMu.Lock() + kernelAccountAfterInsertHooks = append(kernelAccountAfterInsertHooks, kernelAccountHook) + kernelAccountAfterInsertMu.Unlock() case boil.BeforeUpdateHook: - kernalAccountBeforeUpdateMu.Lock() - kernalAccountBeforeUpdateHooks = append(kernalAccountBeforeUpdateHooks, kernalAccountHook) - kernalAccountBeforeUpdateMu.Unlock() + kernelAccountBeforeUpdateMu.Lock() + kernelAccountBeforeUpdateHooks = append(kernelAccountBeforeUpdateHooks, kernelAccountHook) + kernelAccountBeforeUpdateMu.Unlock() case boil.AfterUpdateHook: - kernalAccountAfterUpdateMu.Lock() - kernalAccountAfterUpdateHooks = append(kernalAccountAfterUpdateHooks, kernalAccountHook) - kernalAccountAfterUpdateMu.Unlock() + kernelAccountAfterUpdateMu.Lock() + kernelAccountAfterUpdateHooks = append(kernelAccountAfterUpdateHooks, kernelAccountHook) + kernelAccountAfterUpdateMu.Unlock() case boil.BeforeDeleteHook: - kernalAccountBeforeDeleteMu.Lock() - kernalAccountBeforeDeleteHooks = append(kernalAccountBeforeDeleteHooks, kernalAccountHook) - kernalAccountBeforeDeleteMu.Unlock() + kernelAccountBeforeDeleteMu.Lock() + kernelAccountBeforeDeleteHooks = append(kernelAccountBeforeDeleteHooks, kernelAccountHook) + kernelAccountBeforeDeleteMu.Unlock() case boil.AfterDeleteHook: - kernalAccountAfterDeleteMu.Lock() - kernalAccountAfterDeleteHooks = append(kernalAccountAfterDeleteHooks, kernalAccountHook) - kernalAccountAfterDeleteMu.Unlock() + kernelAccountAfterDeleteMu.Lock() + kernelAccountAfterDeleteHooks = append(kernelAccountAfterDeleteHooks, kernelAccountHook) + kernelAccountAfterDeleteMu.Unlock() case boil.BeforeUpsertHook: - kernalAccountBeforeUpsertMu.Lock() - kernalAccountBeforeUpsertHooks = append(kernalAccountBeforeUpsertHooks, kernalAccountHook) - kernalAccountBeforeUpsertMu.Unlock() + kernelAccountBeforeUpsertMu.Lock() + kernelAccountBeforeUpsertHooks = append(kernelAccountBeforeUpsertHooks, kernelAccountHook) + kernelAccountBeforeUpsertMu.Unlock() case boil.AfterUpsertHook: - kernalAccountAfterUpsertMu.Lock() - kernalAccountAfterUpsertHooks = append(kernalAccountAfterUpsertHooks, kernalAccountHook) - kernalAccountAfterUpsertMu.Unlock() + kernelAccountAfterUpsertMu.Lock() + kernelAccountAfterUpsertHooks = append(kernelAccountAfterUpsertHooks, kernelAccountHook) + kernelAccountAfterUpsertMu.Unlock() } } -// One returns a single kernalAccount record from the query. -func (q kernalAccountQuery) One(ctx context.Context, exec boil.ContextExecutor) (*KernalAccount, error) { - o := &KernalAccount{} +// One returns a single kernelAccount record from the query. +func (q kernelAccountQuery) One(ctx context.Context, exec boil.ContextExecutor) (*KernelAccount, error) { + o := &KernelAccount{} queries.SetLimit(q.Query, 1) @@ -324,7 +324,7 @@ func (q kernalAccountQuery) One(ctx context.Context, exec boil.ContextExecutor) if errors.Is(err, sql.ErrNoRows) { return nil, sql.ErrNoRows } - return nil, errors.Wrap(err, "models: failed to execute a one query for kernal_accounts") + return nil, errors.Wrap(err, "models: failed to execute a one query for kernel_accounts") } if err := o.doAfterSelectHooks(ctx, exec); err != nil { @@ -334,16 +334,16 @@ func (q kernalAccountQuery) One(ctx context.Context, exec boil.ContextExecutor) return o, nil } -// All returns all KernalAccount records from the query. -func (q kernalAccountQuery) All(ctx context.Context, exec boil.ContextExecutor) (KernalAccountSlice, error) { - var o []*KernalAccount +// All returns all KernelAccount records from the query. +func (q kernelAccountQuery) All(ctx context.Context, exec boil.ContextExecutor) (KernelAccountSlice, error) { + var o []*KernelAccount err := q.Bind(ctx, exec, &o) if err != nil { - return nil, errors.Wrap(err, "models: failed to assign all query results to KernalAccount slice") + return nil, errors.Wrap(err, "models: failed to assign all query results to KernelAccount slice") } - if len(kernalAccountAfterSelectHooks) != 0 { + if len(kernelAccountAfterSelectHooks) != 0 { for _, obj := range o { if err := obj.doAfterSelectHooks(ctx, exec); err != nil { return o, err @@ -354,8 +354,8 @@ func (q kernalAccountQuery) All(ctx context.Context, exec boil.ContextExecutor) return o, nil } -// Count returns the count of all KernalAccount records in the query. -func (q kernalAccountQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) { +// Count returns the count of all KernelAccount records in the query. +func (q kernelAccountQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) { var count int64 queries.SetSelect(q.Query, nil) @@ -363,14 +363,14 @@ func (q kernalAccountQuery) Count(ctx context.Context, exec boil.ContextExecutor err := q.Query.QueryRowContext(ctx, exec).Scan(&count) if err != nil { - return 0, errors.Wrap(err, "models: failed to count kernal_accounts rows") + return 0, errors.Wrap(err, "models: failed to count kernel_accounts rows") } return count, nil } // Exists checks if the row exists in the table. -func (q kernalAccountQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) { +func (q kernelAccountQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) { var count int64 queries.SetSelect(q.Query, nil) @@ -379,58 +379,58 @@ func (q kernalAccountQuery) Exists(ctx context.Context, exec boil.ContextExecuto err := q.Query.QueryRowContext(ctx, exec).Scan(&count) if err != nil { - return false, errors.Wrap(err, "models: failed to check if kernal_accounts exists") + return false, errors.Wrap(err, "models: failed to check if kernel_accounts exists") } return count > 0, nil } -// KernalAccounts retrieves all the records using an executor. -func KernalAccounts(mods ...qm.QueryMod) kernalAccountQuery { - mods = append(mods, qm.From("\"identity_api\".\"kernal_accounts\"")) +// KernelAccounts retrieves all the records using an executor. +func KernelAccounts(mods ...qm.QueryMod) kernelAccountQuery { + mods = append(mods, qm.From("\"identity_api\".\"kernel_accounts\"")) q := NewQuery(mods...) if len(queries.GetSelect(q)) == 0 { - queries.SetSelect(q, []string{"\"identity_api\".\"kernal_accounts\".*"}) + queries.SetSelect(q, []string{"\"identity_api\".\"kernel_accounts\".*"}) } - return kernalAccountQuery{q} + return kernelAccountQuery{q} } -// FindKernalAccount retrieves a single record by ID with an executor. +// FindKernelAccount retrieves a single record by ID with an executor. // If selectCols is empty Find will return all columns. -func FindKernalAccount(ctx context.Context, exec boil.ContextExecutor, kernal []byte, selectCols ...string) (*KernalAccount, error) { - kernalAccountObj := &KernalAccount{} +func FindKernelAccount(ctx context.Context, exec boil.ContextExecutor, kernel []byte, selectCols ...string) (*KernelAccount, error) { + kernelAccountObj := &KernelAccount{} sel := "*" if len(selectCols) > 0 { sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",") } query := fmt.Sprintf( - "select %s from \"identity_api\".\"kernal_accounts\" where \"kernal\"=$1", sel, + "select %s from \"identity_api\".\"kernel_accounts\" where \"kernel\"=$1", sel, ) - q := queries.Raw(query, kernal) + q := queries.Raw(query, kernel) - err := q.Bind(ctx, exec, kernalAccountObj) + err := q.Bind(ctx, exec, kernelAccountObj) if err != nil { if errors.Is(err, sql.ErrNoRows) { return nil, sql.ErrNoRows } - return nil, errors.Wrap(err, "models: unable to select from kernal_accounts") + return nil, errors.Wrap(err, "models: unable to select from kernel_accounts") } - if err = kernalAccountObj.doAfterSelectHooks(ctx, exec); err != nil { - return kernalAccountObj, err + if err = kernelAccountObj.doAfterSelectHooks(ctx, exec); err != nil { + return kernelAccountObj, err } - return kernalAccountObj, nil + return kernelAccountObj, nil } // Insert a single record using an executor. // See boil.Columns.InsertColumnSet documentation to understand column list inference for inserts. -func (o *KernalAccount) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error { +func (o *KernelAccount) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error { if o == nil { - return errors.New("models: no kernal_accounts provided for insertion") + return errors.New("models: no kernel_accounts provided for insertion") } var err error @@ -439,33 +439,33 @@ func (o *KernalAccount) Insert(ctx context.Context, exec boil.ContextExecutor, c return err } - nzDefaults := queries.NonZeroDefaultSet(kernalAccountColumnsWithDefault, o) + nzDefaults := queries.NonZeroDefaultSet(kernelAccountColumnsWithDefault, o) key := makeCacheKey(columns, nzDefaults) - kernalAccountInsertCacheMut.RLock() - cache, cached := kernalAccountInsertCache[key] - kernalAccountInsertCacheMut.RUnlock() + kernelAccountInsertCacheMut.RLock() + cache, cached := kernelAccountInsertCache[key] + kernelAccountInsertCacheMut.RUnlock() if !cached { wl, returnColumns := columns.InsertColumnSet( - kernalAccountAllColumns, - kernalAccountColumnsWithDefault, - kernalAccountColumnsWithoutDefault, + kernelAccountAllColumns, + kernelAccountColumnsWithDefault, + kernelAccountColumnsWithoutDefault, nzDefaults, ) - cache.valueMapping, err = queries.BindMapping(kernalAccountType, kernalAccountMapping, wl) + cache.valueMapping, err = queries.BindMapping(kernelAccountType, kernelAccountMapping, wl) if err != nil { return err } - cache.retMapping, err = queries.BindMapping(kernalAccountType, kernalAccountMapping, returnColumns) + cache.retMapping, err = queries.BindMapping(kernelAccountType, kernelAccountMapping, returnColumns) if err != nil { return err } if len(wl) != 0 { - cache.query = fmt.Sprintf("INSERT INTO \"identity_api\".\"kernal_accounts\" (\"%s\") %%sVALUES (%s)%%s", strings.Join(wl, "\",\""), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1)) + cache.query = fmt.Sprintf("INSERT INTO \"identity_api\".\"kernel_accounts\" (\"%s\") %%sVALUES (%s)%%s", strings.Join(wl, "\",\""), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1)) } else { - cache.query = "INSERT INTO \"identity_api\".\"kernal_accounts\" %sDEFAULT VALUES%s" + cache.query = "INSERT INTO \"identity_api\".\"kernel_accounts\" %sDEFAULT VALUES%s" } var queryOutput, queryReturning string @@ -493,49 +493,49 @@ func (o *KernalAccount) Insert(ctx context.Context, exec boil.ContextExecutor, c } if err != nil { - return errors.Wrap(err, "models: unable to insert into kernal_accounts") + return errors.Wrap(err, "models: unable to insert into kernel_accounts") } if !cached { - kernalAccountInsertCacheMut.Lock() - kernalAccountInsertCache[key] = cache - kernalAccountInsertCacheMut.Unlock() + kernelAccountInsertCacheMut.Lock() + kernelAccountInsertCache[key] = cache + kernelAccountInsertCacheMut.Unlock() } return o.doAfterInsertHooks(ctx, exec) } -// Update uses an executor to update the KernalAccount. +// Update uses an executor to update the KernelAccount. // See boil.Columns.UpdateColumnSet documentation to understand column list inference for updates. // Update does not automatically update the record in case of default values. Use .Reload() to refresh the records. -func (o *KernalAccount) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) { +func (o *KernelAccount) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) { var err error if err = o.doBeforeUpdateHooks(ctx, exec); err != nil { return 0, err } key := makeCacheKey(columns, nil) - kernalAccountUpdateCacheMut.RLock() - cache, cached := kernalAccountUpdateCache[key] - kernalAccountUpdateCacheMut.RUnlock() + kernelAccountUpdateCacheMut.RLock() + cache, cached := kernelAccountUpdateCache[key] + kernelAccountUpdateCacheMut.RUnlock() if !cached { wl := columns.UpdateColumnSet( - kernalAccountAllColumns, - kernalAccountPrimaryKeyColumns, + kernelAccountAllColumns, + kernelAccountPrimaryKeyColumns, ) if !columns.IsWhitelist() { wl = strmangle.SetComplement(wl, []string{"created_at"}) } if len(wl) == 0 { - return 0, errors.New("models: unable to update kernal_accounts, could not build whitelist") + return 0, errors.New("models: unable to update kernel_accounts, could not build whitelist") } - cache.query = fmt.Sprintf("UPDATE \"identity_api\".\"kernal_accounts\" SET %s WHERE %s", + cache.query = fmt.Sprintf("UPDATE \"identity_api\".\"kernel_accounts\" SET %s WHERE %s", strmangle.SetParamNames("\"", "\"", 1, wl), - strmangle.WhereClause("\"", "\"", len(wl)+1, kernalAccountPrimaryKeyColumns), + strmangle.WhereClause("\"", "\"", len(wl)+1, kernelAccountPrimaryKeyColumns), ) - cache.valueMapping, err = queries.BindMapping(kernalAccountType, kernalAccountMapping, append(wl, kernalAccountPrimaryKeyColumns...)) + cache.valueMapping, err = queries.BindMapping(kernelAccountType, kernelAccountMapping, append(wl, kernelAccountPrimaryKeyColumns...)) if err != nil { return 0, err } @@ -551,42 +551,42 @@ func (o *KernalAccount) Update(ctx context.Context, exec boil.ContextExecutor, c var result sql.Result result, err = exec.ExecContext(ctx, cache.query, values...) if err != nil { - return 0, errors.Wrap(err, "models: unable to update kernal_accounts row") + return 0, errors.Wrap(err, "models: unable to update kernel_accounts row") } rowsAff, err := result.RowsAffected() if err != nil { - return 0, errors.Wrap(err, "models: failed to get rows affected by update for kernal_accounts") + return 0, errors.Wrap(err, "models: failed to get rows affected by update for kernel_accounts") } if !cached { - kernalAccountUpdateCacheMut.Lock() - kernalAccountUpdateCache[key] = cache - kernalAccountUpdateCacheMut.Unlock() + kernelAccountUpdateCacheMut.Lock() + kernelAccountUpdateCache[key] = cache + kernelAccountUpdateCacheMut.Unlock() } return rowsAff, o.doAfterUpdateHooks(ctx, exec) } // UpdateAll updates all rows with the specified column values. -func (q kernalAccountQuery) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { +func (q kernelAccountQuery) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { queries.SetUpdate(q.Query, cols) result, err := q.Query.ExecContext(ctx, exec) if err != nil { - return 0, errors.Wrap(err, "models: unable to update all for kernal_accounts") + return 0, errors.Wrap(err, "models: unable to update all for kernel_accounts") } rowsAff, err := result.RowsAffected() if err != nil { - return 0, errors.Wrap(err, "models: unable to retrieve rows affected for kernal_accounts") + return 0, errors.Wrap(err, "models: unable to retrieve rows affected for kernel_accounts") } return rowsAff, nil } // UpdateAll updates all rows with the specified column values, using an executor. -func (o KernalAccountSlice) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { +func (o KernelAccountSlice) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { ln := int64(len(o)) if ln == 0 { return 0, nil @@ -608,13 +608,13 @@ func (o KernalAccountSlice) UpdateAll(ctx context.Context, exec boil.ContextExec // Append all of the primary key values for each column for _, obj := range o { - pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), kernalAccountPrimaryKeyMapping) + pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), kernelAccountPrimaryKeyMapping) args = append(args, pkeyArgs...) } - sql := fmt.Sprintf("UPDATE \"identity_api\".\"kernal_accounts\" SET %s WHERE %s", + sql := fmt.Sprintf("UPDATE \"identity_api\".\"kernel_accounts\" SET %s WHERE %s", strmangle.SetParamNames("\"", "\"", 1, colNames), - strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), len(colNames)+1, kernalAccountPrimaryKeyColumns, len(o))) + strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), len(colNames)+1, kernelAccountPrimaryKeyColumns, len(o))) if boil.IsDebug(ctx) { writer := boil.DebugWriterFrom(ctx) @@ -623,28 +623,28 @@ func (o KernalAccountSlice) UpdateAll(ctx context.Context, exec boil.ContextExec } result, err := exec.ExecContext(ctx, sql, args...) if err != nil { - return 0, errors.Wrap(err, "models: unable to update all in kernalAccount slice") + return 0, errors.Wrap(err, "models: unable to update all in kernelAccount slice") } rowsAff, err := result.RowsAffected() if err != nil { - return 0, errors.Wrap(err, "models: unable to retrieve rows affected all in update all kernalAccount") + return 0, errors.Wrap(err, "models: unable to retrieve rows affected all in update all kernelAccount") } return rowsAff, nil } // Upsert attempts an insert using an executor, and does an update or ignore on conflict. // See boil.Columns documentation for how to properly use updateColumns and insertColumns. -func (o *KernalAccount) Upsert(ctx context.Context, exec boil.ContextExecutor, updateOnConflict bool, conflictColumns []string, updateColumns, insertColumns boil.Columns, opts ...UpsertOptionFunc) error { +func (o *KernelAccount) Upsert(ctx context.Context, exec boil.ContextExecutor, updateOnConflict bool, conflictColumns []string, updateColumns, insertColumns boil.Columns, opts ...UpsertOptionFunc) error { if o == nil { - return errors.New("models: no kernal_accounts provided for upsert") + return errors.New("models: no kernel_accounts provided for upsert") } if err := o.doBeforeUpsertHooks(ctx, exec); err != nil { return err } - nzDefaults := queries.NonZeroDefaultSet(kernalAccountColumnsWithDefault, o) + nzDefaults := queries.NonZeroDefaultSet(kernelAccountColumnsWithDefault, o) // Build cache key in-line uglily - mysql vs psql problems buf := strmangle.GetBuffer() @@ -674,48 +674,48 @@ func (o *KernalAccount) Upsert(ctx context.Context, exec boil.ContextExecutor, u key := buf.String() strmangle.PutBuffer(buf) - kernalAccountUpsertCacheMut.RLock() - cache, cached := kernalAccountUpsertCache[key] - kernalAccountUpsertCacheMut.RUnlock() + kernelAccountUpsertCacheMut.RLock() + cache, cached := kernelAccountUpsertCache[key] + kernelAccountUpsertCacheMut.RUnlock() var err error if !cached { insert, _ := insertColumns.InsertColumnSet( - kernalAccountAllColumns, - kernalAccountColumnsWithDefault, - kernalAccountColumnsWithoutDefault, + kernelAccountAllColumns, + kernelAccountColumnsWithDefault, + kernelAccountColumnsWithoutDefault, nzDefaults, ) update := updateColumns.UpdateColumnSet( - kernalAccountAllColumns, - kernalAccountPrimaryKeyColumns, + kernelAccountAllColumns, + kernelAccountPrimaryKeyColumns, ) if updateOnConflict && len(update) == 0 { - return errors.New("models: unable to upsert kernal_accounts, could not build update column list") + return errors.New("models: unable to upsert kernel_accounts, could not build update column list") } - ret := strmangle.SetComplement(kernalAccountAllColumns, strmangle.SetIntersect(insert, update)) + ret := strmangle.SetComplement(kernelAccountAllColumns, strmangle.SetIntersect(insert, update)) conflict := conflictColumns if len(conflict) == 0 && updateOnConflict && len(update) != 0 { - if len(kernalAccountPrimaryKeyColumns) == 0 { - return errors.New("models: unable to upsert kernal_accounts, could not build conflict column list") + if len(kernelAccountPrimaryKeyColumns) == 0 { + return errors.New("models: unable to upsert kernel_accounts, could not build conflict column list") } - conflict = make([]string, len(kernalAccountPrimaryKeyColumns)) - copy(conflict, kernalAccountPrimaryKeyColumns) + conflict = make([]string, len(kernelAccountPrimaryKeyColumns)) + copy(conflict, kernelAccountPrimaryKeyColumns) } - cache.query = buildUpsertQueryPostgres(dialect, "\"identity_api\".\"kernal_accounts\"", updateOnConflict, ret, update, conflict, insert, opts...) + cache.query = buildUpsertQueryPostgres(dialect, "\"identity_api\".\"kernel_accounts\"", updateOnConflict, ret, update, conflict, insert, opts...) - cache.valueMapping, err = queries.BindMapping(kernalAccountType, kernalAccountMapping, insert) + cache.valueMapping, err = queries.BindMapping(kernelAccountType, kernelAccountMapping, insert) if err != nil { return err } if len(ret) != 0 { - cache.retMapping, err = queries.BindMapping(kernalAccountType, kernalAccountMapping, ret) + cache.retMapping, err = queries.BindMapping(kernelAccountType, kernelAccountMapping, ret) if err != nil { return err } @@ -743,31 +743,31 @@ func (o *KernalAccount) Upsert(ctx context.Context, exec boil.ContextExecutor, u _, err = exec.ExecContext(ctx, cache.query, vals...) } if err != nil { - return errors.Wrap(err, "models: unable to upsert kernal_accounts") + return errors.Wrap(err, "models: unable to upsert kernel_accounts") } if !cached { - kernalAccountUpsertCacheMut.Lock() - kernalAccountUpsertCache[key] = cache - kernalAccountUpsertCacheMut.Unlock() + kernelAccountUpsertCacheMut.Lock() + kernelAccountUpsertCache[key] = cache + kernelAccountUpsertCacheMut.Unlock() } return o.doAfterUpsertHooks(ctx, exec) } -// Delete deletes a single KernalAccount record with an executor. +// Delete deletes a single KernelAccount record with an executor. // Delete will match against the primary key column to find the record to delete. -func (o *KernalAccount) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) { +func (o *KernelAccount) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) { if o == nil { - return 0, errors.New("models: no KernalAccount provided for delete") + return 0, errors.New("models: no KernelAccount provided for delete") } if err := o.doBeforeDeleteHooks(ctx, exec); err != nil { return 0, err } - args := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), kernalAccountPrimaryKeyMapping) - sql := "DELETE FROM \"identity_api\".\"kernal_accounts\" WHERE \"kernal\"=$1" + args := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), kernelAccountPrimaryKeyMapping) + sql := "DELETE FROM \"identity_api\".\"kernel_accounts\" WHERE \"kernel\"=$1" if boil.IsDebug(ctx) { writer := boil.DebugWriterFrom(ctx) @@ -776,12 +776,12 @@ func (o *KernalAccount) Delete(ctx context.Context, exec boil.ContextExecutor) ( } result, err := exec.ExecContext(ctx, sql, args...) if err != nil { - return 0, errors.Wrap(err, "models: unable to delete from kernal_accounts") + return 0, errors.Wrap(err, "models: unable to delete from kernel_accounts") } rowsAff, err := result.RowsAffected() if err != nil { - return 0, errors.Wrap(err, "models: failed to get rows affected by delete for kernal_accounts") + return 0, errors.Wrap(err, "models: failed to get rows affected by delete for kernel_accounts") } if err := o.doAfterDeleteHooks(ctx, exec); err != nil { @@ -792,33 +792,33 @@ func (o *KernalAccount) Delete(ctx context.Context, exec boil.ContextExecutor) ( } // DeleteAll deletes all matching rows. -func (q kernalAccountQuery) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { +func (q kernelAccountQuery) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { if q.Query == nil { - return 0, errors.New("models: no kernalAccountQuery provided for delete all") + return 0, errors.New("models: no kernelAccountQuery provided for delete all") } queries.SetDelete(q.Query) result, err := q.Query.ExecContext(ctx, exec) if err != nil { - return 0, errors.Wrap(err, "models: unable to delete all from kernal_accounts") + return 0, errors.Wrap(err, "models: unable to delete all from kernel_accounts") } rowsAff, err := result.RowsAffected() if err != nil { - return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for kernal_accounts") + return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for kernel_accounts") } return rowsAff, nil } // DeleteAll deletes all rows in the slice, using an executor. -func (o KernalAccountSlice) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { +func (o KernelAccountSlice) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { if len(o) == 0 { return 0, nil } - if len(kernalAccountBeforeDeleteHooks) != 0 { + if len(kernelAccountBeforeDeleteHooks) != 0 { for _, obj := range o { if err := obj.doBeforeDeleteHooks(ctx, exec); err != nil { return 0, err @@ -828,12 +828,12 @@ func (o KernalAccountSlice) DeleteAll(ctx context.Context, exec boil.ContextExec var args []interface{} for _, obj := range o { - pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), kernalAccountPrimaryKeyMapping) + pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), kernelAccountPrimaryKeyMapping) args = append(args, pkeyArgs...) } - sql := "DELETE FROM \"identity_api\".\"kernal_accounts\" WHERE " + - strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, kernalAccountPrimaryKeyColumns, len(o)) + sql := "DELETE FROM \"identity_api\".\"kernel_accounts\" WHERE " + + strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, kernelAccountPrimaryKeyColumns, len(o)) if boil.IsDebug(ctx) { writer := boil.DebugWriterFrom(ctx) @@ -842,15 +842,15 @@ func (o KernalAccountSlice) DeleteAll(ctx context.Context, exec boil.ContextExec } result, err := exec.ExecContext(ctx, sql, args...) if err != nil { - return 0, errors.Wrap(err, "models: unable to delete all from kernalAccount slice") + return 0, errors.Wrap(err, "models: unable to delete all from kernelAccount slice") } rowsAff, err := result.RowsAffected() if err != nil { - return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for kernal_accounts") + return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for kernel_accounts") } - if len(kernalAccountAfterDeleteHooks) != 0 { + if len(kernelAccountAfterDeleteHooks) != 0 { for _, obj := range o { if err := obj.doAfterDeleteHooks(ctx, exec); err != nil { return 0, err @@ -863,8 +863,8 @@ func (o KernalAccountSlice) DeleteAll(ctx context.Context, exec boil.ContextExec // Reload refetches the object from the database // using the primary keys with an executor. -func (o *KernalAccount) Reload(ctx context.Context, exec boil.ContextExecutor) error { - ret, err := FindKernalAccount(ctx, exec, o.Kernal) +func (o *KernelAccount) Reload(ctx context.Context, exec boil.ContextExecutor) error { + ret, err := FindKernelAccount(ctx, exec, o.Kernel) if err != nil { return err } @@ -875,26 +875,26 @@ func (o *KernalAccount) Reload(ctx context.Context, exec boil.ContextExecutor) e // ReloadAll refetches every row with matching primary key column values // and overwrites the original object slice with the newly updated slice. -func (o *KernalAccountSlice) ReloadAll(ctx context.Context, exec boil.ContextExecutor) error { +func (o *KernelAccountSlice) ReloadAll(ctx context.Context, exec boil.ContextExecutor) error { if o == nil || len(*o) == 0 { return nil } - slice := KernalAccountSlice{} + slice := KernelAccountSlice{} var args []interface{} for _, obj := range *o { - pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), kernalAccountPrimaryKeyMapping) + pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), kernelAccountPrimaryKeyMapping) args = append(args, pkeyArgs...) } - sql := "SELECT \"identity_api\".\"kernal_accounts\".* FROM \"identity_api\".\"kernal_accounts\" WHERE " + - strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, kernalAccountPrimaryKeyColumns, len(*o)) + sql := "SELECT \"identity_api\".\"kernel_accounts\".* FROM \"identity_api\".\"kernel_accounts\" WHERE " + + strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, kernelAccountPrimaryKeyColumns, len(*o)) q := queries.Raw(sql, args...) err := q.Bind(ctx, exec, &slice) if err != nil { - return errors.Wrap(err, "models: unable to reload all in KernalAccountSlice") + return errors.Wrap(err, "models: unable to reload all in KernelAccountSlice") } *o = slice @@ -902,27 +902,27 @@ func (o *KernalAccountSlice) ReloadAll(ctx context.Context, exec boil.ContextExe return nil } -// KernalAccountExists checks if the KernalAccount row exists. -func KernalAccountExists(ctx context.Context, exec boil.ContextExecutor, kernal []byte) (bool, error) { +// KernelAccountExists checks if the KernelAccount row exists. +func KernelAccountExists(ctx context.Context, exec boil.ContextExecutor, kernel []byte) (bool, error) { var exists bool - sql := "select exists(select 1 from \"identity_api\".\"kernal_accounts\" where \"kernal\"=$1 limit 1)" + sql := "select exists(select 1 from \"identity_api\".\"kernel_accounts\" where \"kernel\"=$1 limit 1)" if boil.IsDebug(ctx) { writer := boil.DebugWriterFrom(ctx) fmt.Fprintln(writer, sql) - fmt.Fprintln(writer, kernal) + fmt.Fprintln(writer, kernel) } - row := exec.QueryRowContext(ctx, sql, kernal) + row := exec.QueryRowContext(ctx, sql, kernel) err := row.Scan(&exists) if err != nil { - return false, errors.Wrap(err, "models: unable to check if kernal_accounts exists") + return false, errors.Wrap(err, "models: unable to check if kernel_accounts exists") } return exists, nil } -// Exists checks if the KernalAccount row exists. -func (o *KernalAccount) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) { - return KernalAccountExists(ctx, exec, o.Kernal) +// Exists checks if the KernelAccount row exists. +func (o *KernelAccount) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) { + return KernelAccountExists(ctx, exec, o.Kernel) } From 1b055b51f136f8a577447cb4e844df946537f40e Mon Sep 17 00:00:00 2001 From: Allyson-English Date: Wed, 10 Jul 2024 15:40:55 -0400 Subject: [PATCH 04/12] kernel --- internal/services/contracts_events_consumer.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/services/contracts_events_consumer.go b/internal/services/contracts_events_consumer.go index 37b2aca6..7bfb0e91 100644 --- a/internal/services/contracts_events_consumer.go +++ b/internal/services/contracts_events_consumer.go @@ -699,8 +699,8 @@ func (c *ContractsEventsConsumer) handleOwnerRegisteredEvent(ctx context.Context return err } - kernal := models.KernalAccount{ - Kernal: args.Kernel.Bytes(), + kernal := models.KernelAccount{ + Kernel: args.Kernel.Bytes(), OwnerAddress: args.Owner.Bytes(), } From 7ae67a7d956f90826d8d46bbb77a2f4bf9d8524d Mon Sep 17 00:00:00 2001 From: Allyson-English Date: Thu, 11 Jul 2024 16:09:12 -0400 Subject: [PATCH 05/12] query --- gqlgen.yml | 4 + graph/accounts.resolvers.go | 21 + graph/generated.go | 1134 ++++++++++++++++- graph/model/models_gen.go | 40 + graph/resolver.go | 8 + graph/schema/accounts.graphqls | 102 ++ internal/config/settings.go | 2 +- internal/repositories/account/account.go | 163 +++ .../services/contracts_events_consumer.go | 10 +- 9 files changed, 1463 insertions(+), 21 deletions(-) create mode 100644 graph/accounts.resolvers.go create mode 100644 graph/schema/accounts.graphqls create mode 100644 internal/repositories/account/account.go diff --git a/gqlgen.yml b/gqlgen.yml index 09c819d8..eef30436 100644 --- a/gqlgen.yml +++ b/gqlgen.yml @@ -181,3 +181,7 @@ models: type: "*int" VehicleID: type: "int" + Account: + extraFields: + kernel: + type: "github.com/ethereum/go-ethereum/common.Address" diff --git a/graph/accounts.resolvers.go b/graph/accounts.resolvers.go new file mode 100644 index 00000000..f5cc5b19 --- /dev/null +++ b/graph/accounts.resolvers.go @@ -0,0 +1,21 @@ +package graph + +// This file will be automatically regenerated based on the schema, any resolver implementations +// will be copied through when generating and any unknown code will be moved to the end. +// Code generated by github.com/99designs/gqlgen version v0.17.49 + +import ( + "context" + + "github.com/DIMO-Network/identity-api/graph/model" +) + +// Account is the resolver for the Account field. +func (r *queryResolver) Account(ctx context.Context, by model.AccountBy) (*model.Account, error) { + return r.account.GetAccount(ctx, by) +} + +// Accounts is the resolver for the Accounts field. +func (r *queryResolver) Accounts(ctx context.Context, first *int, after *string, last *int, before *string, filterBy *model.AccountFilter) (*model.AccountConnection, error) { + return r.account.GetAccounts(ctx, first, after, last, before, filterBy) +} diff --git a/graph/generated.go b/graph/generated.go index da5caa97..e0644289 100644 --- a/graph/generated.go +++ b/graph/generated.go @@ -61,6 +61,23 @@ type DirectiveRoot struct { } type ComplexityRoot struct { + Account struct { + Kernel func(childComplexity int) int + Owner func(childComplexity int) int + } + + AccountConnection struct { + Edges func(childComplexity int) int + Nodes func(childComplexity int) int + PageInfo func(childComplexity int) int + TotalCount func(childComplexity int) int + } + + AccountEdge struct { + Cursor func(childComplexity int) int + Node func(childComplexity int) int + } + AftermarketDevice struct { Address func(childComplexity int) int Beneficiary func(childComplexity int) int @@ -216,6 +233,8 @@ type ComplexityRoot struct { } Query struct { + Account func(childComplexity int, by model.AccountBy) int + Accounts func(childComplexity int, first *int, after *string, last *int, before *string, filterBy *model.AccountFilter) int AftermarketDevice func(childComplexity int, by model.AftermarketDeviceBy) int AftermarketDevices func(childComplexity int, first *int, after *string, last *int, before *string, filterBy *model.AftermarketDevicesFilter) int Dcn func(childComplexity int, by model.DCNBy) int @@ -319,6 +338,8 @@ type ManufacturerResolver interface { } type QueryResolver interface { Node(ctx context.Context, id string) (model.Node, error) + Account(ctx context.Context, by model.AccountBy) (*model.Account, error) + Accounts(ctx context.Context, first *int, after *string, last *int, before *string, filterBy *model.AccountFilter) (*model.AccountConnection, error) AftermarketDevice(ctx context.Context, by model.AftermarketDeviceBy) (*model.AftermarketDevice, error) AftermarketDevices(ctx context.Context, first *int, after *string, last *int, before *string, filterBy *model.AftermarketDevicesFilter) (*model.AftermarketDeviceConnection, error) Dcn(ctx context.Context, by model.DCNBy) (*model.Dcn, error) @@ -371,6 +392,62 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in _ = ec switch typeName + "." + field { + case "Account.kernel": + if e.complexity.Account.Kernel == nil { + break + } + + return e.complexity.Account.Kernel(childComplexity), true + + case "Account.owner": + if e.complexity.Account.Owner == nil { + break + } + + return e.complexity.Account.Owner(childComplexity), true + + case "AccountConnection.edges": + if e.complexity.AccountConnection.Edges == nil { + break + } + + return e.complexity.AccountConnection.Edges(childComplexity), true + + case "AccountConnection.nodes": + if e.complexity.AccountConnection.Nodes == nil { + break + } + + return e.complexity.AccountConnection.Nodes(childComplexity), true + + case "AccountConnection.pageInfo": + if e.complexity.AccountConnection.PageInfo == nil { + break + } + + return e.complexity.AccountConnection.PageInfo(childComplexity), true + + case "AccountConnection.totalCount": + if e.complexity.AccountConnection.TotalCount == nil { + break + } + + return e.complexity.AccountConnection.TotalCount(childComplexity), true + + case "AccountEdge.cursor": + if e.complexity.AccountEdge.Cursor == nil { + break + } + + return e.complexity.AccountEdge.Cursor(childComplexity), true + + case "AccountEdge.node": + if e.complexity.AccountEdge.Node == nil { + break + } + + return e.complexity.AccountEdge.Node(childComplexity), true + case "AftermarketDevice.address": if e.complexity.AftermarketDevice.Address == nil { break @@ -1044,6 +1121,30 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.PrivilegesConnection.TotalCount(childComplexity), true + case "Query.account": + if e.complexity.Query.Account == nil { + break + } + + args, err := ec.field_Query_account_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Query.Account(childComplexity, args["by"].(model.AccountBy)), true + + case "Query.accounts": + if e.complexity.Query.Accounts == nil { + break + } + + args, err := ec.field_Query_accounts_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Query.Accounts(childComplexity, args["first"].(*int), args["after"].(*string), args["last"].(*int), args["before"].(*string), args["filterBy"].(*model.AccountFilter)), true + case "Query.aftermarketDevice": if e.complexity.Query.AftermarketDevice == nil { break @@ -1477,6 +1578,8 @@ func (e *executableSchema) Exec(ctx context.Context) graphql.ResponseHandler { rc := graphql.GetOperationContext(ctx) ec := executionContext{rc, e, 0, 0, make(chan graphql.DeferredResult)} inputUnmarshalMap := graphql.BuildUnmarshalerMap( + ec.unmarshalInputAccountBy, + ec.unmarshalInputAccountFilter, ec.unmarshalInputAftermarketDeviceBy, ec.unmarshalInputAftermarketDevicesFilter, ec.unmarshalInputDCNBy, @@ -1569,7 +1672,7 @@ func (ec *executionContext) introspectType(name string) (*introspection.Type, er return introspection.WrapTypeFromDef(ec.Schema(), ec.Schema().Types[name]), nil } -//go:embed "schema/aftermarket.graphqls" "schema/dcn.graphqls" "schema/devicedefinition.graphqls" "schema/manufacturer.graphqls" "schema/privilege.graphqls" "schema/reward.graphqls" "schema/schema.graphqls" "schema/synthetic.graphqls" "schema/vehicle.graphqls" +//go:embed "schema/accounts.graphqls" "schema/aftermarket.graphqls" "schema/dcn.graphqls" "schema/devicedefinition.graphqls" "schema/manufacturer.graphqls" "schema/privilege.graphqls" "schema/reward.graphqls" "schema/schema.graphqls" "schema/synthetic.graphqls" "schema/vehicle.graphqls" var sourcesFS embed.FS func sourceData(filename string) string { @@ -1581,6 +1684,7 @@ func sourceData(filename string) string { } var sources = []*ast.Source{ + {Name: "schema/accounts.graphqls", Input: sourceData("schema/accounts.graphqls"), BuiltIn: false}, {Name: "schema/aftermarket.graphqls", Input: sourceData("schema/aftermarket.graphqls"), BuiltIn: false}, {Name: "schema/dcn.graphqls", Input: sourceData("schema/dcn.graphqls"), BuiltIn: false}, {Name: "schema/devicedefinition.graphqls", Input: sourceData("schema/devicedefinition.graphqls"), BuiltIn: false}, @@ -1756,6 +1860,72 @@ func (ec *executionContext) field_Query___type_args(ctx context.Context, rawArgs return args, nil } +func (ec *executionContext) field_Query_account_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { + var err error + args := map[string]interface{}{} + var arg0 model.AccountBy + if tmp, ok := rawArgs["by"]; ok { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("by")) + arg0, err = ec.unmarshalNAccountBy2githubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐAccountBy(ctx, tmp) + if err != nil { + return nil, err + } + } + args["by"] = arg0 + return args, nil +} + +func (ec *executionContext) field_Query_accounts_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { + var err error + args := map[string]interface{}{} + var arg0 *int + if tmp, ok := rawArgs["first"]; ok { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("first")) + arg0, err = ec.unmarshalOInt2ᚖint(ctx, tmp) + if err != nil { + return nil, err + } + } + args["first"] = arg0 + var arg1 *string + if tmp, ok := rawArgs["after"]; ok { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("after")) + arg1, err = ec.unmarshalOString2ᚖstring(ctx, tmp) + if err != nil { + return nil, err + } + } + args["after"] = arg1 + var arg2 *int + if tmp, ok := rawArgs["last"]; ok { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("last")) + arg2, err = ec.unmarshalOInt2ᚖint(ctx, tmp) + if err != nil { + return nil, err + } + } + args["last"] = arg2 + var arg3 *string + if tmp, ok := rawArgs["before"]; ok { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("before")) + arg3, err = ec.unmarshalOString2ᚖstring(ctx, tmp) + if err != nil { + return nil, err + } + } + args["before"] = arg3 + var arg4 *model.AccountFilter + if tmp, ok := rawArgs["filterBy"]; ok { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("filterBy")) + arg4, err = ec.unmarshalOAccountFilter2ᚖgithubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐAccountFilter(ctx, tmp) + if err != nil { + return nil, err + } + } + args["filterBy"] = arg4 + return args, nil +} + func (ec *executionContext) field_Query_aftermarketDevice_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { var err error args := map[string]interface{}{} @@ -2241,17 +2411,394 @@ func (ec *executionContext) field___Type_fields_args(ctx context.Context, rawArg return nil, err } } - args["includeDeprecated"] = arg0 - return args, nil + args["includeDeprecated"] = arg0 + return args, nil +} + +// endregion ***************************** args.gotpl ***************************** + +// region ************************** directives.gotpl ************************** + +// endregion ************************** directives.gotpl ************************** + +// region **************************** field.gotpl ***************************** + +func (ec *executionContext) _Account_kernel(ctx context.Context, field graphql.CollectedField, obj *model.Account) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Account_kernel(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Kernel, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.([]common.Address) + fc.Result = res + return ec.marshalOAddress2ᚕgithubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddressᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Account_kernel(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Account", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Address does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Account_owner(ctx context.Context, field graphql.CollectedField, obj *model.Account) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Account_owner(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Owner, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(common.Address) + fc.Result = res + return ec.marshalNAddress2githubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddress(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Account_owner(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Account", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Address does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _AccountConnection_totalCount(ctx context.Context, field graphql.CollectedField, obj *model.AccountConnection) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_AccountConnection_totalCount(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.TotalCount, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNInt2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_AccountConnection_totalCount(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AccountConnection", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Int does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _AccountConnection_edges(ctx context.Context, field graphql.CollectedField, obj *model.AccountConnection) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_AccountConnection_edges(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Edges, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.([]*model.AccountEdge) + fc.Result = res + return ec.marshalNAccountEdge2ᚕᚖgithubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐAccountEdgeᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_AccountConnection_edges(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AccountConnection", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "cursor": + return ec.fieldContext_AccountEdge_cursor(ctx, field) + case "node": + return ec.fieldContext_AccountEdge_node(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type AccountEdge", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _AccountConnection_nodes(ctx context.Context, field graphql.CollectedField, obj *model.AccountConnection) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_AccountConnection_nodes(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Nodes, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.([]*model.Account) + fc.Result = res + return ec.marshalNAccount2ᚕᚖgithubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐAccountᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_AccountConnection_nodes(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AccountConnection", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kernel": + return ec.fieldContext_Account_kernel(ctx, field) + case "owner": + return ec.fieldContext_Account_owner(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type Account", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _AccountConnection_pageInfo(ctx context.Context, field graphql.CollectedField, obj *model.AccountConnection) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_AccountConnection_pageInfo(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.PageInfo, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*model.PageInfo) + fc.Result = res + return ec.marshalNPageInfo2ᚖgithubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐPageInfo(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_AccountConnection_pageInfo(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AccountConnection", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "startCursor": + return ec.fieldContext_PageInfo_startCursor(ctx, field) + case "endCursor": + return ec.fieldContext_PageInfo_endCursor(ctx, field) + case "hasPreviousPage": + return ec.fieldContext_PageInfo_hasPreviousPage(ctx, field) + case "hasNextPage": + return ec.fieldContext_PageInfo_hasNextPage(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type PageInfo", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _AccountEdge_cursor(ctx context.Context, field graphql.CollectedField, obj *model.AccountEdge) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_AccountEdge_cursor(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Cursor, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_AccountEdge_cursor(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AccountEdge", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _AccountEdge_node(ctx context.Context, field graphql.CollectedField, obj *model.AccountEdge) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_AccountEdge_node(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Node, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*model.Account) + fc.Result = res + return ec.marshalNAccount2ᚖgithubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐAccount(ctx, field.Selections, res) } -// endregion ***************************** args.gotpl ***************************** - -// region ************************** directives.gotpl ************************** - -// endregion ************************** directives.gotpl ************************** - -// region **************************** field.gotpl ***************************** +func (ec *executionContext) fieldContext_AccountEdge_node(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "AccountEdge", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kernel": + return ec.fieldContext_Account_kernel(ctx, field) + case "owner": + return ec.fieldContext_Account_owner(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type Account", field.Name) + }, + } + return fc, nil +} func (ec *executionContext) _AftermarketDevice_id(ctx context.Context, field graphql.CollectedField, obj *model.AftermarketDevice) (ret graphql.Marshaler) { fc, err := ec.fieldContext_AftermarketDevice_id(ctx, field) @@ -6885,6 +7432,132 @@ func (ec *executionContext) fieldContext_Query_node(ctx context.Context, field g return fc, nil } +func (ec *executionContext) _Query_account(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Query_account(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Query().Account(rctx, fc.Args["by"].(model.AccountBy)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*model.Account) + fc.Result = res + return ec.marshalNAccount2ᚖgithubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐAccount(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Query_account(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kernel": + return ec.fieldContext_Account_kernel(ctx, field) + case "owner": + return ec.fieldContext_Account_owner(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type Account", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_account_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Query_accounts(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Query_accounts(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Query().Accounts(rctx, fc.Args["first"].(*int), fc.Args["after"].(*string), fc.Args["last"].(*int), fc.Args["before"].(*string), fc.Args["filterBy"].(*model.AccountFilter)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*model.AccountConnection) + fc.Result = res + return ec.marshalNAccountConnection2ᚖgithubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐAccountConnection(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Query_accounts(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "totalCount": + return ec.fieldContext_AccountConnection_totalCount(ctx, field) + case "edges": + return ec.fieldContext_AccountConnection_edges(ctx, field) + case "nodes": + return ec.fieldContext_AccountConnection_nodes(ctx, field) + case "pageInfo": + return ec.fieldContext_AccountConnection_pageInfo(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type AccountConnection", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_accounts_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + func (ec *executionContext) _Query_aftermarketDevice(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { fc, err := ec.fieldContext_Query_aftermarketDevice(ctx, field) if err != nil { @@ -11547,6 +12220,77 @@ func (ec *executionContext) fieldContext___Type_specifiedByURL(_ context.Context // region **************************** input.gotpl ***************************** +func (ec *executionContext) unmarshalInputAccountBy(ctx context.Context, obj interface{}) (model.AccountBy, error) { + var it model.AccountBy + asMap := map[string]interface{}{} + for k, v := range obj.(map[string]interface{}) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"owner"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "owner": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("owner")) + directive0 := func(ctx context.Context) (interface{}, error) { + return ec.unmarshalOAddress2ᚖgithubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddress(ctx, v) + } + directive1 := func(ctx context.Context) (interface{}, error) { + if ec.directives.OneOf == nil { + return nil, errors.New("directive oneOf is not implemented") + } + return ec.directives.OneOf(ctx, obj, directive0) + } + + tmp, err := directive1(ctx) + if err != nil { + return it, graphql.ErrorOnPath(ctx, err) + } + if data, ok := tmp.(*common.Address); ok { + it.Owner = data + } else if tmp == nil { + it.Owner = nil + } else { + err := fmt.Errorf(`unexpected type %T from directive, should be *github.com/ethereum/go-ethereum/common.Address`, tmp) + return it, graphql.ErrorOnPath(ctx, err) + } + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputAccountFilter(ctx context.Context, obj interface{}) (model.AccountFilter, error) { + var it model.AccountFilter + asMap := map[string]interface{}{} + for k, v := range obj.(map[string]interface{}) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"owner"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "owner": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("owner")) + data, err := ec.unmarshalOAddress2ᚖgithubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddress(ctx, v) + if err != nil { + return it, err + } + it.Owner = data + } + } + + return it, nil +} + func (ec *executionContext) unmarshalInputAftermarketDeviceBy(ctx context.Context, obj interface{}) (model.AftermarketDeviceBy, error) { var it model.AftermarketDeviceBy asMap := map[string]interface{}{} @@ -12150,15 +12894,154 @@ func (ec *executionContext) _Node(ctx context.Context, sel ast.SelectionSet, obj if obj == nil { return graphql.Null } - return ec._Vehicle(ctx, sel, obj) - default: - panic(fmt.Errorf("unexpected type %T", obj)) + return ec._Vehicle(ctx, sel, obj) + default: + panic(fmt.Errorf("unexpected type %T", obj)) + } +} + +// endregion ************************** interface.gotpl *************************** + +// region **************************** object.gotpl **************************** + +var accountImplementors = []string{"Account"} + +func (ec *executionContext) _Account(ctx context.Context, sel ast.SelectionSet, obj *model.Account) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, accountImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("Account") + case "kernel": + out.Values[i] = ec._Account_kernel(ctx, field, obj) + case "owner": + out.Values[i] = ec._Account_owner(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var accountConnectionImplementors = []string{"AccountConnection"} + +func (ec *executionContext) _AccountConnection(ctx context.Context, sel ast.SelectionSet, obj *model.AccountConnection) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, accountConnectionImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("AccountConnection") + case "totalCount": + out.Values[i] = ec._AccountConnection_totalCount(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "edges": + out.Values[i] = ec._AccountConnection_edges(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "nodes": + out.Values[i] = ec._AccountConnection_nodes(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "pageInfo": + out.Values[i] = ec._AccountConnection_pageInfo(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) } + + return out } -// endregion ************************** interface.gotpl *************************** +var accountEdgeImplementors = []string{"AccountEdge"} -// region **************************** object.gotpl **************************** +func (ec *executionContext) _AccountEdge(ctx context.Context, sel ast.SelectionSet, obj *model.AccountEdge) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, accountEdgeImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("AccountEdge") + case "cursor": + out.Values[i] = ec._AccountEdge_cursor(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "node": + out.Values[i] = ec._AccountEdge_node(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} var aftermarketDeviceImplementors = []string{"AftermarketDevice", "Node"} @@ -13588,6 +14471,50 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) } + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "account": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_account(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "accounts": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_accounts(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) case "aftermarketDevice": field := field @@ -14911,6 +15838,137 @@ func (ec *executionContext) ___Type(ctx context.Context, sel ast.SelectionSet, o // region ***************************** type.gotpl ***************************** +func (ec *executionContext) marshalNAccount2githubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐAccount(ctx context.Context, sel ast.SelectionSet, v model.Account) graphql.Marshaler { + return ec._Account(ctx, sel, &v) +} + +func (ec *executionContext) marshalNAccount2ᚕᚖgithubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐAccountᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.Account) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalNAccount2ᚖgithubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐAccount(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalNAccount2ᚖgithubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐAccount(ctx context.Context, sel ast.SelectionSet, v *model.Account) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._Account(ctx, sel, v) +} + +func (ec *executionContext) unmarshalNAccountBy2githubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐAccountBy(ctx context.Context, v interface{}) (model.AccountBy, error) { + res, err := ec.unmarshalInputAccountBy(ctx, v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNAccountConnection2githubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐAccountConnection(ctx context.Context, sel ast.SelectionSet, v model.AccountConnection) graphql.Marshaler { + return ec._AccountConnection(ctx, sel, &v) +} + +func (ec *executionContext) marshalNAccountConnection2ᚖgithubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐAccountConnection(ctx context.Context, sel ast.SelectionSet, v *model.AccountConnection) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._AccountConnection(ctx, sel, v) +} + +func (ec *executionContext) marshalNAccountEdge2ᚕᚖgithubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐAccountEdgeᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.AccountEdge) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalNAccountEdge2ᚖgithubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐAccountEdge(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalNAccountEdge2ᚖgithubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐAccountEdge(ctx context.Context, sel ast.SelectionSet, v *model.AccountEdge) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._AccountEdge(ctx, sel, v) +} + func (ec *executionContext) unmarshalNAddress2githubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddress(ctx context.Context, v interface{}) (common.Address, error) { res, err := types.UnmarshalAddress(v) return res, graphql.ErrorOnPath(ctx, err) @@ -16294,6 +17352,52 @@ func (ec *executionContext) marshalN__TypeKind2string(ctx context.Context, sel a return res } +func (ec *executionContext) unmarshalOAccountFilter2ᚖgithubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐAccountFilter(ctx context.Context, v interface{}) (*model.AccountFilter, error) { + if v == nil { + return nil, nil + } + res, err := ec.unmarshalInputAccountFilter(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalOAddress2ᚕgithubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddressᚄ(ctx context.Context, v interface{}) ([]common.Address, error) { + if v == nil { + return nil, nil + } + var vSlice []interface{} + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]common.Address, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNAddress2githubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddress(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) marshalOAddress2ᚕgithubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddressᚄ(ctx context.Context, sel ast.SelectionSet, v []common.Address) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + for i := range v { + ret[i] = ec.marshalNAddress2githubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddress(ctx, sel, v[i]) + } + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + func (ec *executionContext) unmarshalOAddress2ᚖgithubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddress(ctx context.Context, v interface{}) (*common.Address, error) { if v == nil { return nil, nil diff --git a/graph/model/models_gen.go b/graph/model/models_gen.go index c1657ee2..19b4b89c 100644 --- a/graph/model/models_gen.go +++ b/graph/model/models_gen.go @@ -15,6 +15,46 @@ type Node interface { GetID() string } +// Represents a DIMO Account. This is a unique identifier for a vehicle. +type Account struct { + // Kernel addresses made from the owner account. + Kernel []common.Address `json:"kernel,omitempty"` + // Ethereum address of account owner. + Owner common.Address `json:"owner"` + kernel common.Address `json:"-"` +} + +// Input used to specify a unique Account to query. +type AccountBy struct { + Owner *common.Address `json:"owner,omitempty"` +} + +// The Connection type for Account. +type AccountConnection struct { + // The total count of accounts in the connection. + TotalCount int `json:"totalCount"` + // A list of edges. + Edges []*AccountEdge `json:"edges"` + // A list of nodes in the connection + Nodes []*Account `json:"nodes"` + // Information to aid in pagination. + PageInfo *PageInfo `json:"pageInfo"` +} + +// An edge in a AccountConnection. +type AccountEdge struct { + // A cursor for use in pagination. + Cursor string `json:"cursor"` + // The item at the end of the edge. + Node *Account `json:"node"` +} + +// Filter for Account. +type AccountFilter struct { + // Filter for Account owned by this address. + Owner *common.Address `json:"owner,omitempty"` +} + type AftermarketDevice struct { // An opaque global identifier for this aftermarket device. ID string `json:"id"` diff --git a/graph/resolver.go b/graph/resolver.go index a201e1ed..5d17fbe6 100644 --- a/graph/resolver.go +++ b/graph/resolver.go @@ -4,6 +4,7 @@ import ( "context" "github.com/DIMO-Network/identity-api/graph/model" + "github.com/DIMO-Network/identity-api/internal/repositories/account" "github.com/DIMO-Network/identity-api/internal/repositories/aftermarket" "github.com/DIMO-Network/identity-api/internal/repositories/base" "github.com/DIMO-Network/identity-api/internal/repositories/dcn" @@ -31,6 +32,11 @@ type AftermarketDeviceRepository interface { GetAftermarketDevicesForManufacturer(ctx context.Context, obj *model.Manufacturer, first *int, after *string, last *int, before *string, filterBy *model.AftermarketDevicesFilter) (*model.AftermarketDeviceConnection, error) } +type AccountRepository interface { + GetAccount(ctx context.Context, by model.AccountBy) (*model.Account, error) + GetAccounts(ctx context.Context, first *int, after *string, last *int, before *string, filterBy *model.AccountFilter) (*model.AccountConnection, error) +} + // DCNRepository interface for mocking dcn.Repository. // //go:generate mockgen -destination=./mock_dcn_test.go -package=graph github.com/DIMO-Network/identity-api/graph DCNRepository @@ -82,6 +88,7 @@ type Resolver struct { vehicle VehicleRepository vehicleprivilege vehicleprivilege.Repository deviceDefinition DeviceDefinitionRepository + account AccountRepository } // NewResolver creates a new Resolver with allocated repositories. @@ -99,5 +106,6 @@ func NewResolver(baseRepo *base.Repository) *Resolver { deviceDefinition: &devicedefinition.Repository{Repository: baseRepo, TablelandApiService: tablelandApiService, }, + account: &account.Repository{Repository: baseRepo}, } } diff --git a/graph/schema/accounts.graphqls b/graph/schema/accounts.graphqls new file mode 100644 index 00000000..fa4e87ac --- /dev/null +++ b/graph/schema/accounts.graphqls @@ -0,0 +1,102 @@ +# DIMO Account related schema + +extend type Query { + """ + View a particular DIMO Account. + """ + account(by: AccountBy!): Account! + + """ + List DIMO accounts. + """ + accounts( + """ + Returns the first n elements from the list. + Mutually exclusive with `last`. + """ + first: Int + """ + A cursor for pagination. Retrieve accounts after this cursor. + """ + after: String + """ + Returns the last n elements from the list. + """ + last: Int + """ + A cursor for pagination. Retrieve accounts before this cursor. + """ + before: String + """ + Filters the accounts based on the specified criteria. + """ + filterBy: AccountFilter + ): AccountConnection! +} + +""" +Represents a DIMO Account. This is a unique identifier for a vehicle. +""" +type Account { + """ + Kernel addresses made from the owner account. + """ + kernel: [Address!] + """ + Ethereum address of account owner. + """ + owner: Address! +} + +""" +An edge in a AccountConnection. +""" +type AccountEdge { + """ + A cursor for use in pagination. + """ + cursor: String! + """ + The item at the end of the edge. + """ + node: Account! +} + +""" +The Connection type for Account. +""" +type AccountConnection { + """ + The total count of accounts in the connection. + """ + totalCount: Int! + """ + A list of edges. + """ + edges: [AccountEdge!]! + """ + A list of nodes in the connection + """ + nodes: [Account!]! + """ + Information to aid in pagination. + """ + pageInfo: PageInfo! +} + +""" +Filter for Account. +""" +input AccountFilter { + """ + Filter for Account owned by this address. + """ + owner: Address +} + +""" +Input used to specify a unique Account to query. +""" +input AccountBy @oneOf { + owner: Address +} diff --git a/internal/config/settings.go b/internal/config/settings.go index 2ec235c8..1150f615 100644 --- a/internal/config/settings.go +++ b/internal/config/settings.go @@ -22,5 +22,5 @@ type Settings struct { BaseVehicleDataURI string `yaml:"BASE_VEHICLE_DATA_URI"` TablelandAPIGateway string `yaml:"TABLELAND_API_GATEWAY"` EthereumRPCURL string `yaml:"ETHEREUM_RPC_URL"` - KernalECDSAValidator string `yaml:"KERNAL_ECDSA_VALIDATOR"` + KernelECDSAValidator string `yaml:"KERNEL_ECDSA_VALIDATOR"` } diff --git a/internal/repositories/account/account.go b/internal/repositories/account/account.go new file mode 100644 index 00000000..b4377f97 --- /dev/null +++ b/internal/repositories/account/account.go @@ -0,0 +1,163 @@ +package account + +import ( + "context" + "fmt" + + gmodel "github.com/DIMO-Network/identity-api/graph/model" + "github.com/DIMO-Network/identity-api/internal/helpers" + "github.com/DIMO-Network/identity-api/internal/repositories/base" + "github.com/DIMO-Network/identity-api/models" + "github.com/ethereum/go-ethereum/common" + "github.com/vektah/gqlparser/v2/gqlerror" + "github.com/volatiletech/sqlboiler/v4/queries/qm" + "golang.org/x/exp/slices" +) + +// AccountPrefix is the prefix for a global token id for Accounts. +const AccountPrefix = "Acct" + +type Repository struct { + *base.Repository +} + +type AccountCursor struct { + OwnerAddress []byte + Kernel []byte +} + +// ToAPI converts a Account database row to a Account API model. +func ToAPI(d *models.KernelAccount) (*gmodel.Account, error) { + return &gmodel.Account{ + Kernel: []common.Address{common.BytesToAddress(d.Kernel)}, + Owner: common.BytesToAddress(d.OwnerAddress), + }, nil +} + +var accountCursorColumnsTuple = "(" + models.KernelAccountColumns.OwnerAddress + ", " + models.KernelAccountColumns.Kernel + ")" + +func (r *Repository) GetAccount(ctx context.Context, by gmodel.AccountBy) (*gmodel.Account, error) { + if by.Owner == nil { + return nil, gqlerror.Errorf("Provide exactly one of `owner`.") + } + + return r.GetAccountByOwner(ctx, *by.Owner) +} + +func (r *Repository) GetAccountByOwner(ctx context.Context, owner common.Address) (*gmodel.Account, error) { + acc, err := models.KernelAccounts(models.KernelAccountWhere.OwnerAddress.EQ(owner.Bytes())).One(ctx, r.PDB.DBS().Reader) + if err != nil { + return nil, err + } + return ToAPI(acc) +} + +func (r *Repository) GetAccounts(ctx context.Context, first *int, after *string, last *int, before *string, filterBy *gmodel.AccountFilter) (*gmodel.AccountConnection, error) { + fmt.Println("Getting lots of accounts: ", first, after, last, before, filterBy) + limit, err := helpers.ValidateFirstLast(first, last, base.MaxPageSize) + if err != nil { + return nil, err + } + + queryMods := []qm.QueryMod{} + if filterBy != nil && filterBy.Owner != nil { + queryMods = append(queryMods, models.KernelAccountWhere.OwnerAddress.EQ(filterBy.Owner.Bytes())) + } + + accountCount, err := models.KernelAccounts(queryMods...).Count(ctx, r.PDB.DBS().Reader) + if err != nil { + return nil, err + } + + orderBy := " DESC" + if last != nil { + orderBy = " ASC" + } + + queryMods = append(queryMods, + qm.Limit(limit+1), + qm.OrderBy(models.KernelAccountColumns.OwnerAddress+orderBy+", "+models.KernelAccountColumns.Kernel+orderBy), + ) + + pHelp := &helpers.PaginationHelper[AccountCursor]{} + if after != nil { + afterT, err := pHelp.DecodeCursor(*after) + if err != nil { + return nil, err + } + queryMods = append(queryMods, + qm.Where(accountCursorColumnsTuple+" < (?, ?)", afterT.OwnerAddress, afterT.Kernel), + ) + } else if before != nil { + beforeT, err := pHelp.DecodeCursor(*before) + if err != nil { + return nil, err + } + queryMods = append(queryMods, + qm.Where(accountCursorColumnsTuple+" < (?, ?)", beforeT.OwnerAddress, beforeT.Kernel), + ) + } + + all, err := models.KernelAccounts(queryMods...).All(ctx, r.PDB.DBS().Reader) + if err != nil { + return nil, err + } + + hasNext := before != nil + hasPrevious := after != nil + + if first != nil && len(all) == limit+1 { + hasNext = true + all = all[:limit] + } else if last != nil && len(all) == limit+1 { + hasPrevious = true + all = all[:limit] + } + + if last != nil { + slices.Reverse(all) + } + + edges := make([]*gmodel.AccountEdge, len(all)) + nodes := make([]*gmodel.Account, len(all)) + var errList gqlerror.List + for i, acct := range all { + c, err := pHelp.EncodeCursor(AccountCursor{OwnerAddress: acct.OwnerAddress, Kernel: acct.Kernel}) + if err != nil { + return nil, err + } + apiAccount, err := ToAPI(acct) + if err != nil { + errList = append(errList, gqlerror.Errorf("error converting account to api: %v", err)) + continue + } + edges[i] = &gmodel.AccountEdge{ + Node: apiAccount, + Cursor: c, + } + nodes[i] = edges[i].Node + } + + var endCur, startCur *string + + if len(all) != 0 { + startCur = &edges[0].Cursor + endCur = &edges[len(edges)-1].Cursor + } + + res := &gmodel.AccountConnection{ + TotalCount: int(accountCount), + Edges: edges, + Nodes: nodes, + PageInfo: &gmodel.PageInfo{ + StartCursor: startCur, + EndCursor: endCur, + HasNextPage: hasNext, + HasPreviousPage: hasPrevious, + }, + } + if errList != nil { + return res, errList + } + return res, nil +} diff --git a/internal/services/contracts_events_consumer.go b/internal/services/contracts_events_consumer.go index 7bfb0e91..91c46521 100644 --- a/internal/services/contracts_events_consumer.go +++ b/internal/services/contracts_events_consumer.go @@ -69,7 +69,7 @@ const ( TokensTransferredForDevice EventName = "TokensTransferredForDevice" TokensTransferredForConnectionStreak EventName = "TokensTransferredForConnectionStreak" - // Kernal ECDSA Validator. + // Kernel ECDSA Validator. OwnerRegistered EventName = "OwnerRegistered" ) @@ -106,7 +106,7 @@ func (c *ContractsEventsConsumer) Process(ctx context.Context, event *shared.Clo DCNRegistryAddr := common.HexToAddress(c.settings.DCNRegistryAddr) DCNResolverAddr := common.HexToAddress(c.settings.DCNResolverAddr) RewardsContractAddr := common.HexToAddress(c.settings.RewardsContractAddr) - KernalECDSAValidator := common.HexToAddress(c.settings.KernalECDSAValidator) + KernelECDSAValidatorAddr := common.HexToAddress(c.settings.KernelECDSAValidator) var data ContractEventData if err := json.Unmarshal(event.Data, &data); err != nil { @@ -187,7 +187,7 @@ func (c *ContractsEventsConsumer) Process(ctx context.Context, event *shared.Clo case TokensTransferredForConnectionStreak: return c.handleTokensTransferredForConnectionStreak(ctx, &data) } - case KernalECDSAValidator: + case KernelECDSAValidatorAddr: switch eventName { case OwnerRegistered: return c.handleOwnerRegisteredEvent(ctx, &data) @@ -699,10 +699,10 @@ func (c *ContractsEventsConsumer) handleOwnerRegisteredEvent(ctx context.Context return err } - kernal := models.KernelAccount{ + kernel := models.KernelAccount{ Kernel: args.Kernel.Bytes(), OwnerAddress: args.Owner.Bytes(), } - return kernal.Insert(ctx, c.dbs.DBS().Writer, boil.Infer()) + return kernel.Insert(ctx, c.dbs.DBS().Writer, boil.Infer()) } From 6e5033eaa1457845111931ca2339f51c634549c7 Mon Sep 17 00:00:00 2001 From: Allyson-English Date: Thu, 11 Jul 2024 16:10:02 -0400 Subject: [PATCH 06/12] query --- internal/repositories/account/account.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/internal/repositories/account/account.go b/internal/repositories/account/account.go index b4377f97..a83b1481 100644 --- a/internal/repositories/account/account.go +++ b/internal/repositories/account/account.go @@ -2,7 +2,6 @@ package account import ( "context" - "fmt" gmodel "github.com/DIMO-Network/identity-api/graph/model" "github.com/DIMO-Network/identity-api/internal/helpers" @@ -53,7 +52,6 @@ func (r *Repository) GetAccountByOwner(ctx context.Context, owner common.Address } func (r *Repository) GetAccounts(ctx context.Context, first *int, after *string, last *int, before *string, filterBy *gmodel.AccountFilter) (*gmodel.AccountConnection, error) { - fmt.Println("Getting lots of accounts: ", first, after, last, before, filterBy) limit, err := helpers.ValidateFirstLast(first, last, base.MaxPageSize) if err != nil { return nil, err From ee6a4829f0638b800ae82bca2382796eb02cadd3 Mon Sep 17 00:00:00 2001 From: Allyson-English Date: Thu, 11 Jul 2024 16:49:39 -0400 Subject: [PATCH 07/12] kernel --- settings.sample.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/settings.sample.yaml b/settings.sample.yaml index 9f61c4da..2e6c3385 100644 --- a/settings.sample.yaml +++ b/settings.sample.yaml @@ -19,4 +19,4 @@ REWARDS_CONTRACT_ADDRESS: "0x375885164266d48C48abbbb439Be98864Ae62bBE" BASE_IMAGE_URL: "https://devices-api.dev.dimo.zone/v1/" TABLELAND_API_GATEWAY: "https://testnets.tableland.network/" ETHEREUM_RPC_URL: "http://127.0.0.1:8545" -KERNAL_ECDSA_VALIDATOR: "0x8104e3Ad430EA6d354d013A6789fDFc71E671c43" +KERNEL_ECDSA_VALIDATOR: "0x8104e3Ad430EA6d354d013A6789fDFc71E671c43" From 5717a723553db591de59bafa58f76b64e4c7b961 Mon Sep 17 00:00:00 2001 From: Allyson-English Date: Wed, 17 Jul 2024 14:24:33 -0400 Subject: [PATCH 08/12] all kernels returned for signer --- graph/generated.go | 582 ++++++++++++++++++++--- graph/model/models_gen.go | 28 +- graph/schema/accounts.graphqls | 38 +- internal/repositories/account/account.go | 163 +++++-- migrations/00031_kernel_tbl.sql | 2 + models/kernel_accounts.go | 36 +- 6 files changed, 739 insertions(+), 110 deletions(-) diff --git a/graph/generated.go b/graph/generated.go index e0644289..f018c5cb 100644 --- a/graph/generated.go +++ b/graph/generated.go @@ -63,7 +63,7 @@ type DirectiveRoot struct { type ComplexityRoot struct { Account struct { Kernel func(childComplexity int) int - Owner func(childComplexity int) int + Signer func(childComplexity int) int } AccountConnection struct { @@ -195,6 +195,12 @@ type ComplexityRoot struct { Node func(childComplexity int) int } + Kernel struct { + Address func(childComplexity int) int + CreatedAt func(childComplexity int) int + Signer func(childComplexity int) int + } + Manufacturer struct { AftermarketDevices func(childComplexity int, first *int, after *string, last *int, before *string, filterBy *model.AftermarketDevicesFilter) int DeviceDefinitions func(childComplexity int, first *int, after *string, last *int, before *string, filterBy *model.DeviceDefinitionFilter) int @@ -249,6 +255,11 @@ type ComplexityRoot struct { Vehicles func(childComplexity int, first *int, after *string, last *int, before *string, filterBy *model.VehiclesFilter) int } + Signer struct { + Address func(childComplexity int) int + SignerAdded func(childComplexity int) int + } + SyntheticDevice struct { Address func(childComplexity int) int ID func(childComplexity int) int @@ -399,12 +410,12 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.Account.Kernel(childComplexity), true - case "Account.owner": - if e.complexity.Account.Owner == nil { + case "Account.signer": + if e.complexity.Account.Signer == nil { break } - return e.complexity.Account.Owner(childComplexity), true + return e.complexity.Account.Signer(childComplexity), true case "AccountConnection.edges": if e.complexity.AccountConnection.Edges == nil { @@ -957,6 +968,27 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.EarningsEdge.Node(childComplexity), true + case "Kernel.address": + if e.complexity.Kernel.Address == nil { + break + } + + return e.complexity.Kernel.Address(childComplexity), true + + case "Kernel.createdAt": + if e.complexity.Kernel.CreatedAt == nil { + break + } + + return e.complexity.Kernel.CreatedAt(childComplexity), true + + case "Kernel.signer": + if e.complexity.Kernel.Signer == nil { + break + } + + return e.complexity.Kernel.Signer(childComplexity), true + case "Manufacturer.aftermarketDevices": if e.complexity.Manufacturer.AftermarketDevices == nil { break @@ -1289,6 +1321,20 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in return e.complexity.Query.Vehicles(childComplexity, args["first"].(*int), args["after"].(*string), args["last"].(*int), args["before"].(*string), args["filterBy"].(*model.VehiclesFilter)), true + case "Signer.address": + if e.complexity.Signer.Address == nil { + break + } + + return e.complexity.Signer.Address(childComplexity), true + + case "Signer.signerAdded": + if e.complexity.Signer.SignerAdded == nil { + break + } + + return e.complexity.Signer.SignerAdded(childComplexity), true + case "SyntheticDevice.address": if e.complexity.SyntheticDevice.Address == nil { break @@ -2446,9 +2492,9 @@ func (ec *executionContext) _Account_kernel(ctx context.Context, field graphql.C if resTmp == nil { return graphql.Null } - res := resTmp.([]common.Address) + res := resTmp.([]*model.Kernel) fc.Result = res - return ec.marshalOAddress2ᚕgithubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddressᚄ(ctx, field.Selections, res) + return ec.marshalOKernel2ᚕᚖgithubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐKernelᚄ(ctx, field.Selections, res) } func (ec *executionContext) fieldContext_Account_kernel(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { @@ -2458,14 +2504,22 @@ func (ec *executionContext) fieldContext_Account_kernel(_ context.Context, field IsMethod: false, IsResolver: false, Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return nil, errors.New("field of type Address does not have child fields") + switch field.Name { + case "address": + return ec.fieldContext_Kernel_address(ctx, field) + case "createdAt": + return ec.fieldContext_Kernel_createdAt(ctx, field) + case "signer": + return ec.fieldContext_Kernel_signer(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type Kernel", field.Name) }, } return fc, nil } -func (ec *executionContext) _Account_owner(ctx context.Context, field graphql.CollectedField, obj *model.Account) (ret graphql.Marshaler) { - fc, err := ec.fieldContext_Account_owner(ctx, field) +func (ec *executionContext) _Account_signer(ctx context.Context, field graphql.CollectedField, obj *model.Account) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Account_signer(ctx, field) if err != nil { return graphql.Null } @@ -2478,7 +2532,7 @@ func (ec *executionContext) _Account_owner(ctx context.Context, field graphql.Co }() resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { ctx = rctx // use context from middleware stack in children - return obj.Owner, nil + return obj.Signer, nil }) if err != nil { ec.Error(ctx, err) @@ -2495,7 +2549,7 @@ func (ec *executionContext) _Account_owner(ctx context.Context, field graphql.Co return ec.marshalNAddress2githubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddress(ctx, field.Selections, res) } -func (ec *executionContext) fieldContext_Account_owner(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { +func (ec *executionContext) fieldContext_Account_signer(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { fc = &graphql.FieldContext{ Object: "Account", Field: field, @@ -2643,8 +2697,8 @@ func (ec *executionContext) fieldContext_AccountConnection_nodes(_ context.Conte switch field.Name { case "kernel": return ec.fieldContext_Account_kernel(ctx, field) - case "owner": - return ec.fieldContext_Account_owner(ctx, field) + case "signer": + return ec.fieldContext_Account_signer(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type Account", field.Name) }, @@ -2791,8 +2845,8 @@ func (ec *executionContext) fieldContext_AccountEdge_node(_ context.Context, fie switch field.Name { case "kernel": return ec.fieldContext_Account_kernel(ctx, field) - case "owner": - return ec.fieldContext_Account_owner(ctx, field) + case "signer": + return ec.fieldContext_Account_signer(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type Account", field.Name) }, @@ -6343,6 +6397,144 @@ func (ec *executionContext) fieldContext_EarningsEdge_cursor(_ context.Context, return fc, nil } +func (ec *executionContext) _Kernel_address(ctx context.Context, field graphql.CollectedField, obj *model.Kernel) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Kernel_address(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Address, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(common.Address) + fc.Result = res + return ec.marshalNAddress2githubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddress(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Kernel_address(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Kernel", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Address does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Kernel_createdAt(ctx context.Context, field graphql.CollectedField, obj *model.Kernel) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Kernel_createdAt(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.CreatedAt, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(time.Time) + fc.Result = res + return ec.marshalNTime2timeᚐTime(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Kernel_createdAt(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Kernel", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Time does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Kernel_signer(ctx context.Context, field graphql.CollectedField, obj *model.Kernel) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Kernel_signer(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Signer, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*model.Signer) + fc.Result = res + return ec.marshalNSigner2ᚖgithubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐSigner(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Kernel_signer(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Kernel", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "address": + return ec.fieldContext_Signer_address(ctx, field) + case "signerAdded": + return ec.fieldContext_Signer_signerAdded(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type Signer", field.Name) + }, + } + return fc, nil +} + func (ec *executionContext) _Manufacturer_id(ctx context.Context, field graphql.CollectedField, obj *model.Manufacturer) (ret graphql.Marshaler) { fc, err := ec.fieldContext_Manufacturer_id(ctx, field) if err != nil { @@ -7473,8 +7665,8 @@ func (ec *executionContext) fieldContext_Query_account(ctx context.Context, fiel switch field.Name { case "kernel": return ec.fieldContext_Account_kernel(ctx, field) - case "owner": - return ec.fieldContext_Account_owner(ctx, field) + case "signer": + return ec.fieldContext_Account_signer(ctx, field) } return nil, fmt.Errorf("no field named %q was found under type Account", field.Name) }, @@ -8467,6 +8659,94 @@ func (ec *executionContext) fieldContext_Query___schema(_ context.Context, field return fc, nil } +func (ec *executionContext) _Signer_address(ctx context.Context, field graphql.CollectedField, obj *model.Signer) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Signer_address(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Address, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(common.Address) + fc.Result = res + return ec.marshalNAddress2githubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddress(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Signer_address(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Signer", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Address does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Signer_signerAdded(ctx context.Context, field graphql.CollectedField, obj *model.Signer) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Signer_signerAdded(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.SignerAdded, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(time.Time) + fc.Result = res + return ec.marshalNTime2timeᚐTime(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Signer_signerAdded(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Signer", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Time does not have child fields") + }, + } + return fc, nil +} + func (ec *executionContext) _SyntheticDevice_id(ctx context.Context, field graphql.CollectedField, obj *model.SyntheticDevice) (ret graphql.Marshaler) { fc, err := ec.fieldContext_SyntheticDevice_id(ctx, field) if err != nil { @@ -12227,15 +12507,15 @@ func (ec *executionContext) unmarshalInputAccountBy(ctx context.Context, obj int asMap[k] = v } - fieldsInOrder := [...]string{"owner"} + fieldsInOrder := [...]string{"signer", "kernel", "address"} for _, k := range fieldsInOrder { v, ok := asMap[k] if !ok { continue } switch k { - case "owner": - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("owner")) + case "signer": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("signer")) directive0 := func(ctx context.Context) (interface{}, error) { return ec.unmarshalOAddress2ᚖgithubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddress(ctx, v) } @@ -12251,9 +12531,57 @@ func (ec *executionContext) unmarshalInputAccountBy(ctx context.Context, obj int return it, graphql.ErrorOnPath(ctx, err) } if data, ok := tmp.(*common.Address); ok { - it.Owner = data + it.Signer = data } else if tmp == nil { - it.Owner = nil + it.Signer = nil + } else { + err := fmt.Errorf(`unexpected type %T from directive, should be *github.com/ethereum/go-ethereum/common.Address`, tmp) + return it, graphql.ErrorOnPath(ctx, err) + } + case "kernel": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("kernel")) + directive0 := func(ctx context.Context) (interface{}, error) { + return ec.unmarshalOAddress2ᚖgithubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddress(ctx, v) + } + directive1 := func(ctx context.Context) (interface{}, error) { + if ec.directives.OneOf == nil { + return nil, errors.New("directive oneOf is not implemented") + } + return ec.directives.OneOf(ctx, obj, directive0) + } + + tmp, err := directive1(ctx) + if err != nil { + return it, graphql.ErrorOnPath(ctx, err) + } + if data, ok := tmp.(*common.Address); ok { + it.Kernel = data + } else if tmp == nil { + it.Kernel = nil + } else { + err := fmt.Errorf(`unexpected type %T from directive, should be *github.com/ethereum/go-ethereum/common.Address`, tmp) + return it, graphql.ErrorOnPath(ctx, err) + } + case "address": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("address")) + directive0 := func(ctx context.Context) (interface{}, error) { + return ec.unmarshalOAddress2ᚖgithubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddress(ctx, v) + } + directive1 := func(ctx context.Context) (interface{}, error) { + if ec.directives.OneOf == nil { + return nil, errors.New("directive oneOf is not implemented") + } + return ec.directives.OneOf(ctx, obj, directive0) + } + + tmp, err := directive1(ctx) + if err != nil { + return it, graphql.ErrorOnPath(ctx, err) + } + if data, ok := tmp.(*common.Address); ok { + it.Address = data + } else if tmp == nil { + it.Address = nil } else { err := fmt.Errorf(`unexpected type %T from directive, should be *github.com/ethereum/go-ethereum/common.Address`, tmp) return it, graphql.ErrorOnPath(ctx, err) @@ -12271,20 +12599,20 @@ func (ec *executionContext) unmarshalInputAccountFilter(ctx context.Context, obj asMap[k] = v } - fieldsInOrder := [...]string{"owner"} + fieldsInOrder := [...]string{"signer"} for _, k := range fieldsInOrder { v, ok := asMap[k] if !ok { continue } switch k { - case "owner": - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("owner")) + case "signer": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("signer")) data, err := ec.unmarshalOAddress2ᚖgithubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddress(ctx, v) if err != nil { return it, err } - it.Owner = data + it.Signer = data } } @@ -12917,8 +13245,8 @@ func (ec *executionContext) _Account(ctx context.Context, sel ast.SelectionSet, out.Values[i] = graphql.MarshalString("Account") case "kernel": out.Values[i] = ec._Account_kernel(ctx, field, obj) - case "owner": - out.Values[i] = ec._Account_owner(ctx, field, obj) + case "signer": + out.Values[i] = ec._Account_signer(ctx, field, obj) if out.Values[i] == graphql.Null { out.Invalids++ } @@ -14101,6 +14429,55 @@ func (ec *executionContext) _EarningsEdge(ctx context.Context, sel ast.Selection return out } +var kernelImplementors = []string{"Kernel"} + +func (ec *executionContext) _Kernel(ctx context.Context, sel ast.SelectionSet, obj *model.Kernel) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, kernelImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("Kernel") + case "address": + out.Values[i] = ec._Kernel_address(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "createdAt": + out.Values[i] = ec._Kernel_createdAt(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "signer": + out.Values[i] = ec._Kernel_signer(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + var manufacturerImplementors = []string{"Manufacturer", "Node"} func (ec *executionContext) _Manufacturer(ctx context.Context, sel ast.SelectionSet, obj *model.Manufacturer) graphql.Marshaler { @@ -14786,6 +15163,50 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr return out } +var signerImplementors = []string{"Signer"} + +func (ec *executionContext) _Signer(ctx context.Context, sel ast.SelectionSet, obj *model.Signer) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, signerImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("Signer") + case "address": + out.Values[i] = ec._Signer_address(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "signerAdded": + out.Values[i] = ec._Signer_signerAdded(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + var syntheticDeviceImplementors = []string{"SyntheticDevice", "Node"} func (ec *executionContext) _SyntheticDevice(ctx context.Context, sel ast.SelectionSet, obj *model.SyntheticDevice) graphql.Marshaler { @@ -16661,6 +17082,16 @@ func (ec *executionContext) marshalNInt2int(ctx context.Context, sel ast.Selecti return res } +func (ec *executionContext) marshalNKernel2ᚖgithubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐKernel(ctx context.Context, sel ast.SelectionSet, v *model.Kernel) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._Kernel(ctx, sel, v) +} + func (ec *executionContext) marshalNManufacturer2githubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐManufacturer(ctx context.Context, sel ast.SelectionSet, v model.Manufacturer) graphql.Marshaler { return ec._Manufacturer(ctx, sel, &v) } @@ -16812,6 +17243,16 @@ func (ec *executionContext) marshalNPrivilegesConnection2ᚖgithubᚗcomᚋDIMO return ec._PrivilegesConnection(ctx, sel, v) } +func (ec *executionContext) marshalNSigner2ᚖgithubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐSigner(ctx context.Context, sel ast.SelectionSet, v *model.Signer) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._Signer(ctx, sel, v) +} + func (ec *executionContext) unmarshalNString2string(ctx context.Context, v interface{}) (string, error) { res, err := graphql.UnmarshalString(v) return res, graphql.ErrorOnPath(ctx, err) @@ -17360,44 +17801,6 @@ func (ec *executionContext) unmarshalOAccountFilter2ᚖgithubᚗcomᚋDIMOᚑNet return &res, graphql.ErrorOnPath(ctx, err) } -func (ec *executionContext) unmarshalOAddress2ᚕgithubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddressᚄ(ctx context.Context, v interface{}) ([]common.Address, error) { - if v == nil { - return nil, nil - } - var vSlice []interface{} - if v != nil { - vSlice = graphql.CoerceList(v) - } - var err error - res := make([]common.Address, len(vSlice)) - for i := range vSlice { - ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) - res[i], err = ec.unmarshalNAddress2githubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddress(ctx, vSlice[i]) - if err != nil { - return nil, err - } - } - return res, nil -} - -func (ec *executionContext) marshalOAddress2ᚕgithubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddressᚄ(ctx context.Context, sel ast.SelectionSet, v []common.Address) graphql.Marshaler { - if v == nil { - return graphql.Null - } - ret := make(graphql.Array, len(v)) - for i := range v { - ret[i] = ec.marshalNAddress2githubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddress(ctx, sel, v[i]) - } - - for _, e := range ret { - if e == graphql.Null { - return graphql.Null - } - } - - return ret -} - func (ec *executionContext) unmarshalOAddress2ᚖgithubᚗcomᚋethereumᚋgoᚑethereumᚋcommonᚐAddress(ctx context.Context, v interface{}) (*common.Address, error) { if v == nil { return nil, nil @@ -17524,6 +17927,53 @@ func (ec *executionContext) marshalOInt2ᚖint(ctx context.Context, sel ast.Sele return res } +func (ec *executionContext) marshalOKernel2ᚕᚖgithubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐKernelᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.Kernel) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalNKernel2ᚖgithubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐKernel(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + func (ec *executionContext) marshalONode2githubᚗcomᚋDIMOᚑNetworkᚋidentityᚑapiᚋgraphᚋmodelᚐNode(ctx context.Context, sel ast.SelectionSet, v model.Node) graphql.Marshaler { if v == nil { return graphql.Null diff --git a/graph/model/models_gen.go b/graph/model/models_gen.go index 19b4b89c..e985b86e 100644 --- a/graph/model/models_gen.go +++ b/graph/model/models_gen.go @@ -18,15 +18,17 @@ type Node interface { // Represents a DIMO Account. This is a unique identifier for a vehicle. type Account struct { // Kernel addresses made from the owner account. - Kernel []common.Address `json:"kernel,omitempty"` - // Ethereum address of account owner. - Owner common.Address `json:"owner"` + Kernel []*Kernel `json:"kernel,omitempty"` + // Ethereum address of account signer. + Signer common.Address `json:"signer"` kernel common.Address `json:"-"` } // Input used to specify a unique Account to query. type AccountBy struct { - Owner *common.Address `json:"owner,omitempty"` + Signer *common.Address `json:"signer,omitempty"` + Kernel *common.Address `json:"kernel,omitempty"` + Address *common.Address `json:"address,omitempty"` } // The Connection type for Account. @@ -52,7 +54,7 @@ type AccountEdge struct { // Filter for Account. type AccountFilter struct { // Filter for Account owned by this address. - Owner *common.Address `json:"owner,omitempty"` + Signer *common.Address `json:"signer,omitempty"` } type AftermarketDevice struct { @@ -291,6 +293,15 @@ type EarningsEdge struct { Cursor string `json:"cursor"` } +type Kernel struct { + // Kernel addresses made from the owner account. + Address common.Address `json:"address"` + // When the kernal account was created + CreatedAt time.Time `json:"createdAt"` + // Signer information for Kernel + Signer *Signer `json:"signer"` +} + type Manufacturer struct { // An opaque global identifier for this manufacturer. ID string `json:"id"` @@ -358,6 +369,13 @@ type PrivilegesConnection struct { type Query struct { } +type Signer struct { + // Kernel signer (owner) account. + Address common.Address `json:"address"` + // When signer was added + SignerAdded time.Time `json:"signerAdded"` +} + // The SyntheticDevice is a software connection established to connect the vehicle to the DIMO network. type SyntheticDevice struct { // An opaque global identifier for this syntheticDevice. diff --git a/graph/schema/accounts.graphqls b/graph/schema/accounts.graphqls index fa4e87ac..15ce92a4 100644 --- a/graph/schema/accounts.graphqls +++ b/graph/schema/accounts.graphqls @@ -41,11 +41,37 @@ type Account { """ Kernel addresses made from the owner account. """ - kernel: [Address!] + kernel: [Kernel!] """ - Ethereum address of account owner. + Ethereum address of account signer. """ - owner: Address! + signer: Address! +} + +type Kernel { + """ + Kernel addresses made from the owner account. + """ + address: Address! + """ + When the kernal account was created + """ + createdAt: Time! + """ + Signer information for Kernel + """ + signer: Signer! +} + +type Signer { + """ + Kernel signer (owner) account. + """ + address: Address! + """ + When signer was added + """ + signerAdded: Time! } """ @@ -91,12 +117,14 @@ input AccountFilter { """ Filter for Account owned by this address. """ - owner: Address + signer: Address } """ Input used to specify a unique Account to query. """ input AccountBy @oneOf { - owner: Address + signer: Address + kernel: Address + address: Address } diff --git a/internal/repositories/account/account.go b/internal/repositories/account/account.go index a83b1481..5f105870 100644 --- a/internal/repositories/account/account.go +++ b/internal/repositories/account/account.go @@ -25,41 +25,110 @@ type AccountCursor struct { Kernel []byte } -// ToAPI converts a Account database row to a Account API model. -func ToAPI(d *models.KernelAccount) (*gmodel.Account, error) { - return &gmodel.Account{ - Kernel: []common.Address{common.BytesToAddress(d.Kernel)}, - Owner: common.BytesToAddress(d.OwnerAddress), - }, nil -} - var accountCursorColumnsTuple = "(" + models.KernelAccountColumns.OwnerAddress + ", " + models.KernelAccountColumns.Kernel + ")" func (r *Repository) GetAccount(ctx context.Context, by gmodel.AccountBy) (*gmodel.Account, error) { - if by.Owner == nil { - return nil, gqlerror.Errorf("Provide exactly one of `owner`.") + if by.Signer != nil && by.Kernel == nil && by.Address == nil { + return r.GetAccountBySigner(ctx, *by.Signer), nil + } + + if by.Kernel != nil && by.Signer == nil && by.Address == nil { + return r.GetAccountByKernel(ctx, *by.Kernel), nil + } + + if by.Address != nil && by.Signer == nil && by.Kernel == nil { + return r.GetAccountAddress(ctx, *by.Address), nil } - return r.GetAccountByOwner(ctx, *by.Owner) + return nil, gqlerror.Errorf("Provide exactly one of `signer`, `kernel` or `address`.") } -func (r *Repository) GetAccountByOwner(ctx context.Context, owner common.Address) (*gmodel.Account, error) { - acc, err := models.KernelAccounts(models.KernelAccountWhere.OwnerAddress.EQ(owner.Bytes())).One(ctx, r.PDB.DBS().Reader) +func (r *Repository) GetAccountBySigner(ctx context.Context, signer common.Address) *gmodel.Account { + all, err := models.KernelAccounts(models.KernelAccountWhere.OwnerAddress.EQ(signer.Bytes())).All(ctx, r.PDB.DBS().Reader) if err != nil { - return nil, err + return nil + } + + apiAccount := &gmodel.Account{ + Signer: common.BytesToAddress(signer.Bytes()), + } + + for _, acct := range all { + apiAccount.Kernel = append(apiAccount.Kernel, &gmodel.Kernel{ + Address: common.BytesToAddress(acct.Kernel), + CreatedAt: acct.CreatedAt, + Signer: &gmodel.Signer{ + Address: common.BytesToAddress(signer.Bytes()), + SignerAdded: acct.SignerAdded, + }, + }) } - return ToAPI(acc) + + return apiAccount +} + +func (r *Repository) GetAccountByKernel(ctx context.Context, kernel common.Address) *gmodel.Account { + all, err := models.KernelAccounts(models.KernelAccountWhere.Kernel.EQ(kernel.Bytes())).All(ctx, r.PDB.DBS().Reader) + if err != nil { + return nil + } + + var apiAccount gmodel.Account + for idx, acct := range all { + if idx == 0 { + apiAccount.Signer = common.BytesToAddress(acct.OwnerAddress) + } + apiAccount.Kernel = append(apiAccount.Kernel, &gmodel.Kernel{ + Address: common.BytesToAddress(acct.Kernel), + CreatedAt: acct.CreatedAt, + Signer: &gmodel.Signer{ + Address: common.BytesToAddress(kernel.Bytes()), + SignerAdded: acct.SignerAdded, + }, + }) + } + + return &apiAccount +} + +func (r *Repository) GetAccountAddress(ctx context.Context, address common.Address) *gmodel.Account { + all, err := models.KernelAccounts( + qm.Expr( + qm.Or2(models.KernelAccountWhere.Kernel.EQ(address.Bytes())), + qm.Or2(models.KernelAccountWhere.OwnerAddress.EQ(address.Bytes())), + ), + ).All(ctx, r.PDB.DBS().Reader) + if err != nil { + return nil + } + + var apiAccount gmodel.Account + for idx, acct := range all { + if idx == 0 { + apiAccount.Signer = common.BytesToAddress(acct.OwnerAddress) + } + apiAccount.Kernel = append(apiAccount.Kernel, &gmodel.Kernel{ + Address: common.BytesToAddress(acct.Kernel), + CreatedAt: acct.CreatedAt, + Signer: &gmodel.Signer{ + Address: common.BytesToAddress(acct.OwnerAddress), + SignerAdded: acct.SignerAdded, + }, + }) + } + + return &apiAccount } func (r *Repository) GetAccounts(ctx context.Context, first *int, after *string, last *int, before *string, filterBy *gmodel.AccountFilter) (*gmodel.AccountConnection, error) { - limit, err := helpers.ValidateFirstLast(first, last, base.MaxPageSize) + limit, err := helpers.ValidateFirstLast(first, last, 30) if err != nil { return nil, err } queryMods := []qm.QueryMod{} - if filterBy != nil && filterBy.Owner != nil { - queryMods = append(queryMods, models.KernelAccountWhere.OwnerAddress.EQ(filterBy.Owner.Bytes())) + if filterBy != nil && filterBy.Signer != nil { + queryMods = append(queryMods, models.KernelAccountWhere.OwnerAddress.EQ(filterBy.Signer.Bytes())) } accountCount, err := models.KernelAccounts(queryMods...).Count(ctx, r.PDB.DBS().Reader) @@ -116,24 +185,52 @@ func (r *Repository) GetAccounts(ctx context.Context, first *int, after *string, slices.Reverse(all) } - edges := make([]*gmodel.AccountEdge, len(all)) - nodes := make([]*gmodel.Account, len(all)) - var errList gqlerror.List - for i, acct := range all { + ordered := 0 + ownerToKernals := make(map[common.Address]AcctInfos) + for _, acct := range all { + owner := common.BytesToAddress(acct.OwnerAddress) c, err := pHelp.EncodeCursor(AccountCursor{OwnerAddress: acct.OwnerAddress, Kernel: acct.Kernel}) if err != nil { return nil, err } - apiAccount, err := ToAPI(acct) - if err != nil { - errList = append(errList, gqlerror.Errorf("error converting account to api: %v", err)) - continue + + acctInfos, ok := ownerToKernals[owner] + if !ok { + acctInfos = AcctInfos{Idx: ordered} + ordered++ } - edges[i] = &gmodel.AccountEdge{ - Node: apiAccount, - Cursor: c, + + acctInfos.Kernels = append(acctInfos.Kernels, &gmodel.Kernel{ + Address: common.BytesToAddress(acct.Kernel), + CreatedAt: acct.CreatedAt, + Signer: &gmodel.Signer{ + Address: common.BytesToAddress(owner.Bytes()), + SignerAdded: acct.SignerAdded, + }, + }) + acctInfos.Cursor = append(acctInfos.Cursor, c) + ownerToKernals[owner] = acctInfos + + } + + edges := make([]*gmodel.AccountEdge, len(ownerToKernals)) + nodes := make([]*gmodel.Account, len(ownerToKernals)) + var errList gqlerror.List + + for owner, acctInfos := range ownerToKernals { + apiAccount := &gmodel.Account{ + Signer: owner, + Kernel: acctInfos.Kernels, + } + + edges[acctInfos.Idx] = &gmodel.AccountEdge{ + Node: apiAccount, + } + + if len(acctInfos.Cursor) != 0 { + edges[acctInfos.Idx].Cursor = acctInfos.Cursor[len(acctInfos.Cursor)-1] } - nodes[i] = edges[i].Node + nodes[acctInfos.Idx] = edges[acctInfos.Idx].Node } var endCur, startCur *string @@ -159,3 +256,9 @@ func (r *Repository) GetAccounts(ctx context.Context, first *int, after *string, } return res, nil } + +type AcctInfos struct { + Idx int + Kernels []*gmodel.Kernel + Cursor []string +} diff --git a/migrations/00031_kernel_tbl.sql b/migrations/00031_kernel_tbl.sql index 772cc308..bee6ae59 100644 --- a/migrations/00031_kernel_tbl.sql +++ b/migrations/00031_kernel_tbl.sql @@ -2,6 +2,8 @@ -- +goose StatementBegin CREATE TABLE kernel_accounts( kernel bytea CONSTRAINT kernel_accounts_kernel_address_check CHECK (length(kernel) = 20) PRIMARY KEY, + created_at timestamptz NOT NULL DEFAULT NOW(), + signer_added timestamptz NOT NULL DEFAULT NOW(), owner_address bytea CONSTRAINT kernel_accounts_owner_address_check CHECK (length(owner_address) = 20) NOT NULL -- TODO(ae): should this reference any other table? ); -- +goose StatementEnd diff --git a/models/kernel_accounts.go b/models/kernel_accounts.go index 8875a89f..ba5de86a 100644 --- a/models/kernel_accounts.go +++ b/models/kernel_accounts.go @@ -23,8 +23,10 @@ import ( // KernelAccount is an object representing the database table. type KernelAccount struct { - Kernel []byte `boil:"kernel" json:"kernel" toml:"kernel" yaml:"kernel"` - OwnerAddress []byte `boil:"owner_address" json:"owner_address" toml:"owner_address" yaml:"owner_address"` + Kernel []byte `boil:"kernel" json:"kernel" toml:"kernel" yaml:"kernel"` + CreatedAt time.Time `boil:"created_at" json:"created_at" toml:"created_at" yaml:"created_at"` + SignerAdded time.Time `boil:"signer_added" json:"signer_added" toml:"signer_added" yaml:"signer_added"` + OwnerAddress []byte `boil:"owner_address" json:"owner_address" toml:"owner_address" yaml:"owner_address"` R *kernelAccountR `boil:"-" json:"-" toml:"-" yaml:"-"` L kernelAccountL `boil:"-" json:"-" toml:"-" yaml:"-"` @@ -32,17 +34,25 @@ type KernelAccount struct { var KernelAccountColumns = struct { Kernel string + CreatedAt string + SignerAdded string OwnerAddress string }{ Kernel: "kernel", + CreatedAt: "created_at", + SignerAdded: "signer_added", OwnerAddress: "owner_address", } var KernelAccountTableColumns = struct { Kernel string + CreatedAt string + SignerAdded string OwnerAddress string }{ Kernel: "kernel_accounts.kernel", + CreatedAt: "kernel_accounts.created_at", + SignerAdded: "kernel_accounts.signer_added", OwnerAddress: "kernel_accounts.owner_address", } @@ -50,9 +60,13 @@ var KernelAccountTableColumns = struct { var KernelAccountWhere = struct { Kernel whereHelper__byte + CreatedAt whereHelpertime_Time + SignerAdded whereHelpertime_Time OwnerAddress whereHelper__byte }{ Kernel: whereHelper__byte{field: "\"identity_api\".\"kernel_accounts\".\"kernel\""}, + CreatedAt: whereHelpertime_Time{field: "\"identity_api\".\"kernel_accounts\".\"created_at\""}, + SignerAdded: whereHelpertime_Time{field: "\"identity_api\".\"kernel_accounts\".\"signer_added\""}, OwnerAddress: whereHelper__byte{field: "\"identity_api\".\"kernel_accounts\".\"owner_address\""}, } @@ -73,9 +87,9 @@ func (*kernelAccountR) NewStruct() *kernelAccountR { type kernelAccountL struct{} var ( - kernelAccountAllColumns = []string{"kernel", "owner_address"} + kernelAccountAllColumns = []string{"kernel", "created_at", "signer_added", "owner_address"} kernelAccountColumnsWithoutDefault = []string{"kernel", "owner_address"} - kernelAccountColumnsWithDefault = []string{} + kernelAccountColumnsWithDefault = []string{"created_at", "signer_added"} kernelAccountPrimaryKeyColumns = []string{"kernel"} kernelAccountGeneratedColumns = []string{} ) @@ -434,6 +448,13 @@ func (o *KernelAccount) Insert(ctx context.Context, exec boil.ContextExecutor, c } var err error + if !boil.TimestampsAreSkipped(ctx) { + currTime := time.Now().In(boil.GetLocation()) + + if o.CreatedAt.IsZero() { + o.CreatedAt = currTime + } + } if err := o.doBeforeInsertHooks(ctx, exec); err != nil { return err @@ -639,6 +660,13 @@ func (o *KernelAccount) Upsert(ctx context.Context, exec boil.ContextExecutor, u if o == nil { return errors.New("models: no kernel_accounts provided for upsert") } + if !boil.TimestampsAreSkipped(ctx) { + currTime := time.Now().In(boil.GetLocation()) + + if o.CreatedAt.IsZero() { + o.CreatedAt = currTime + } + } if err := o.doBeforeUpsertHooks(ctx, exec); err != nil { return err From 58d648692f3058a97921ca8f6a3899426fb75126 Mon Sep 17 00:00:00 2001 From: Allyson-English Date: Fri, 19 Jul 2024 11:22:32 -0400 Subject: [PATCH 09/12] consolidate acct by queries --- internal/repositories/account/account.go | 99 ++++++------------------ 1 file changed, 22 insertions(+), 77 deletions(-) diff --git a/internal/repositories/account/account.go b/internal/repositories/account/account.go index 5f105870..7802c32b 100644 --- a/internal/repositories/account/account.go +++ b/internal/repositories/account/account.go @@ -21,92 +21,37 @@ type Repository struct { } type AccountCursor struct { - OwnerAddress []byte - Kernel []byte + Signer []byte + Kernel []byte } var accountCursorColumnsTuple = "(" + models.KernelAccountColumns.OwnerAddress + ", " + models.KernelAccountColumns.Kernel + ")" func (r *Repository) GetAccount(ctx context.Context, by gmodel.AccountBy) (*gmodel.Account, error) { - if by.Signer != nil && by.Kernel == nil && by.Address == nil { - return r.GetAccountBySigner(ctx, *by.Signer), nil - } - - if by.Kernel != nil && by.Signer == nil && by.Address == nil { - return r.GetAccountByKernel(ctx, *by.Kernel), nil - } - if by.Address != nil && by.Signer == nil && by.Kernel == nil { - return r.GetAccountAddress(ctx, *by.Address), nil + var acctBy []qm.QueryMod + switch { + case by.Signer != nil || by.Address != nil: + acctBy = append(acctBy, models.KernelAccountWhere.OwnerAddress.EQ(by.Signer.Bytes())) + case by.Kernel != nil || by.Address != nil: + acctBy = append(acctBy, models.KernelAccountWhere.Kernel.EQ(by.Kernel.Bytes())) + default: + return nil, gqlerror.Errorf("Provide exactly one of `signer`, `kernel` or `address`.") } - return nil, gqlerror.Errorf("Provide exactly one of `signer`, `kernel` or `address`.") -} - -func (r *Repository) GetAccountBySigner(ctx context.Context, signer common.Address) *gmodel.Account { - all, err := models.KernelAccounts(models.KernelAccountWhere.OwnerAddress.EQ(signer.Bytes())).All(ctx, r.PDB.DBS().Reader) + all, err := models.KernelAccounts(acctBy...).All(ctx, r.PDB.DBS().Reader) if err != nil { - return nil - } - - apiAccount := &gmodel.Account{ - Signer: common.BytesToAddress(signer.Bytes()), + return nil, err } + var apiAccount *gmodel.Account for _, acct := range all { - apiAccount.Kernel = append(apiAccount.Kernel, &gmodel.Kernel{ - Address: common.BytesToAddress(acct.Kernel), - CreatedAt: acct.CreatedAt, - Signer: &gmodel.Signer{ - Address: common.BytesToAddress(signer.Bytes()), - SignerAdded: acct.SignerAdded, - }, - }) - } - - return apiAccount -} - -func (r *Repository) GetAccountByKernel(ctx context.Context, kernel common.Address) *gmodel.Account { - all, err := models.KernelAccounts(models.KernelAccountWhere.Kernel.EQ(kernel.Bytes())).All(ctx, r.PDB.DBS().Reader) - if err != nil { - return nil - } - - var apiAccount gmodel.Account - for idx, acct := range all { - if idx == 0 { - apiAccount.Signer = common.BytesToAddress(acct.OwnerAddress) + if apiAccount == nil { + apiAccount = &gmodel.Account{ + Signer: common.BytesToAddress(acct.OwnerAddress), + } } - apiAccount.Kernel = append(apiAccount.Kernel, &gmodel.Kernel{ - Address: common.BytesToAddress(acct.Kernel), - CreatedAt: acct.CreatedAt, - Signer: &gmodel.Signer{ - Address: common.BytesToAddress(kernel.Bytes()), - SignerAdded: acct.SignerAdded, - }, - }) - } - - return &apiAccount -} -func (r *Repository) GetAccountAddress(ctx context.Context, address common.Address) *gmodel.Account { - all, err := models.KernelAccounts( - qm.Expr( - qm.Or2(models.KernelAccountWhere.Kernel.EQ(address.Bytes())), - qm.Or2(models.KernelAccountWhere.OwnerAddress.EQ(address.Bytes())), - ), - ).All(ctx, r.PDB.DBS().Reader) - if err != nil { - return nil - } - - var apiAccount gmodel.Account - for idx, acct := range all { - if idx == 0 { - apiAccount.Signer = common.BytesToAddress(acct.OwnerAddress) - } apiAccount.Kernel = append(apiAccount.Kernel, &gmodel.Kernel{ Address: common.BytesToAddress(acct.Kernel), CreatedAt: acct.CreatedAt, @@ -117,11 +62,11 @@ func (r *Repository) GetAccountAddress(ctx context.Context, address common.Addre }) } - return &apiAccount + return apiAccount, nil } func (r *Repository) GetAccounts(ctx context.Context, first *int, after *string, last *int, before *string, filterBy *gmodel.AccountFilter) (*gmodel.AccountConnection, error) { - limit, err := helpers.ValidateFirstLast(first, last, 30) + limit, err := helpers.ValidateFirstLast(first, last, base.MaxPageSize) if err != nil { return nil, err } @@ -153,7 +98,7 @@ func (r *Repository) GetAccounts(ctx context.Context, first *int, after *string, return nil, err } queryMods = append(queryMods, - qm.Where(accountCursorColumnsTuple+" < (?, ?)", afterT.OwnerAddress, afterT.Kernel), + qm.Where(accountCursorColumnsTuple+" < (?, ?)", afterT.Signer, afterT.Kernel), ) } else if before != nil { beforeT, err := pHelp.DecodeCursor(*before) @@ -161,7 +106,7 @@ func (r *Repository) GetAccounts(ctx context.Context, first *int, after *string, return nil, err } queryMods = append(queryMods, - qm.Where(accountCursorColumnsTuple+" < (?, ?)", beforeT.OwnerAddress, beforeT.Kernel), + qm.Where(accountCursorColumnsTuple+" < (?, ?)", beforeT.Signer, beforeT.Kernel), ) } @@ -189,7 +134,7 @@ func (r *Repository) GetAccounts(ctx context.Context, first *int, after *string, ownerToKernals := make(map[common.Address]AcctInfos) for _, acct := range all { owner := common.BytesToAddress(acct.OwnerAddress) - c, err := pHelp.EncodeCursor(AccountCursor{OwnerAddress: acct.OwnerAddress, Kernel: acct.Kernel}) + c, err := pHelp.EncodeCursor(AccountCursor{Signer: acct.OwnerAddress, Kernel: acct.Kernel}) if err != nil { return nil, err } From decbf87e53138d3ee3cbe6ee4aa5048c3fdf433e Mon Sep 17 00:00:00 2001 From: Allyson-English Date: Fri, 19 Jul 2024 13:27:07 -0400 Subject: [PATCH 10/12] signer --- gqlgen.yml | 4 - graph/model/models_gen.go | 1 - internal/repositories/account/account.go | 63 +- .../services/contracts_events_consumer.go | 9 +- migrations/00031_kernel_tbl.sql | 10 +- models/accounts.go | 986 ++++++++++++++++++ models/aftermarket_devices.go | 30 - models/boil_table_names.go | 4 +- models/kernel_accounts.go | 956 ----------------- 9 files changed, 1031 insertions(+), 1032 deletions(-) create mode 100644 models/accounts.go delete mode 100644 models/kernel_accounts.go diff --git a/gqlgen.yml b/gqlgen.yml index eef30436..09c819d8 100644 --- a/gqlgen.yml +++ b/gqlgen.yml @@ -181,7 +181,3 @@ models: type: "*int" VehicleID: type: "int" - Account: - extraFields: - kernel: - type: "github.com/ethereum/go-ethereum/common.Address" diff --git a/graph/model/models_gen.go b/graph/model/models_gen.go index e985b86e..b0f8dd89 100644 --- a/graph/model/models_gen.go +++ b/graph/model/models_gen.go @@ -21,7 +21,6 @@ type Account struct { Kernel []*Kernel `json:"kernel,omitempty"` // Ethereum address of account signer. Signer common.Address `json:"signer"` - kernel common.Address `json:"-"` } // Input used to specify a unique Account to query. diff --git a/internal/repositories/account/account.go b/internal/repositories/account/account.go index 7802c32b..a386f7a8 100644 --- a/internal/repositories/account/account.go +++ b/internal/repositories/account/account.go @@ -2,6 +2,7 @@ package account import ( "context" + "fmt" gmodel "github.com/DIMO-Network/identity-api/graph/model" "github.com/DIMO-Network/identity-api/internal/helpers" @@ -25,30 +26,33 @@ type AccountCursor struct { Kernel []byte } -var accountCursorColumnsTuple = "(" + models.KernelAccountColumns.OwnerAddress + ", " + models.KernelAccountColumns.Kernel + ")" +var accountCursorColumnsTuple = "(" + models.AccountColumns.Signer + ", " + models.AccountColumns.Kernel + ")" func (r *Repository) GetAccount(ctx context.Context, by gmodel.AccountBy) (*gmodel.Account, error) { - var acctBy []qm.QueryMod + switch { - case by.Signer != nil || by.Address != nil: - acctBy = append(acctBy, models.KernelAccountWhere.OwnerAddress.EQ(by.Signer.Bytes())) - case by.Kernel != nil || by.Address != nil: - acctBy = append(acctBy, models.KernelAccountWhere.Kernel.EQ(by.Kernel.Bytes())) + case by.Signer != nil && by.Kernel == nil && by.Address == nil: + acctBy = append(acctBy, models.AccountWhere.Signer.EQ(by.Signer.Bytes())) + case by.Kernel != nil && by.Address == nil && by.Signer == nil: + acctBy = append(acctBy, models.AccountWhere.Kernel.EQ(by.Kernel.Bytes())) + case by.Address != nil && by.Signer == nil && by.Kernel == nil: + acctBy = append(acctBy, qm.Or2(models.AccountWhere.Kernel.EQ(by.Address.Bytes())), qm.Or2(models.AccountWhere.Signer.EQ(by.Address.Bytes()))) default: return nil, gqlerror.Errorf("Provide exactly one of `signer`, `kernel` or `address`.") } - all, err := models.KernelAccounts(acctBy...).All(ctx, r.PDB.DBS().Reader) + all, err := models.Accounts(acctBy...).All(ctx, r.PDB.DBS().Reader) if err != nil { - return nil, err + r.Log.Err(err).Msg("failed fetching account") + return nil, fmt.Errorf("failed fetching account") } var apiAccount *gmodel.Account for _, acct := range all { if apiAccount == nil { apiAccount = &gmodel.Account{ - Signer: common.BytesToAddress(acct.OwnerAddress), + Signer: common.BytesToAddress(acct.Signer), } } @@ -56,7 +60,7 @@ func (r *Repository) GetAccount(ctx context.Context, by gmodel.AccountBy) (*gmod Address: common.BytesToAddress(acct.Kernel), CreatedAt: acct.CreatedAt, Signer: &gmodel.Signer{ - Address: common.BytesToAddress(acct.OwnerAddress), + Address: common.BytesToAddress(acct.Signer), SignerAdded: acct.SignerAdded, }, }) @@ -73,10 +77,10 @@ func (r *Repository) GetAccounts(ctx context.Context, first *int, after *string, queryMods := []qm.QueryMod{} if filterBy != nil && filterBy.Signer != nil { - queryMods = append(queryMods, models.KernelAccountWhere.OwnerAddress.EQ(filterBy.Signer.Bytes())) + queryMods = append(queryMods, models.AccountWhere.Signer.EQ(filterBy.Signer.Bytes())) } - accountCount, err := models.KernelAccounts(queryMods...).Count(ctx, r.PDB.DBS().Reader) + accountCount, err := models.Accounts(queryMods...).Count(ctx, r.PDB.DBS().Reader) if err != nil { return nil, err } @@ -88,7 +92,8 @@ func (r *Repository) GetAccounts(ctx context.Context, first *int, after *string, queryMods = append(queryMods, qm.Limit(limit+1), - qm.OrderBy(models.KernelAccountColumns.OwnerAddress+orderBy+", "+models.KernelAccountColumns.Kernel+orderBy), + qm.OrderBy(models.AccountColumns.Signer+orderBy), + qm.OrderBy(models.AccountColumns.Kernel+orderBy), ) pHelp := &helpers.PaginationHelper[AccountCursor]{} @@ -110,9 +115,10 @@ func (r *Repository) GetAccounts(ctx context.Context, first *int, after *string, ) } - all, err := models.KernelAccounts(queryMods...).All(ctx, r.PDB.DBS().Reader) + all, err := models.Accounts(queryMods...).All(ctx, r.PDB.DBS().Reader) if err != nil { - return nil, err + r.Log.Err(err).Msg("failed fetching account") + return nil, fmt.Errorf("failed fetching account") } hasNext := before != nil @@ -131,15 +137,15 @@ func (r *Repository) GetAccounts(ctx context.Context, first *int, after *string, } ordered := 0 - ownerToKernals := make(map[common.Address]AcctInfos) + signerToKernels := make(map[common.Address]AcctInfos) for _, acct := range all { - owner := common.BytesToAddress(acct.OwnerAddress) - c, err := pHelp.EncodeCursor(AccountCursor{Signer: acct.OwnerAddress, Kernel: acct.Kernel}) + signer := common.BytesToAddress(acct.Signer) + c, err := pHelp.EncodeCursor(AccountCursor{Signer: acct.Signer, Kernel: acct.Kernel}) if err != nil { return nil, err } - acctInfos, ok := ownerToKernals[owner] + acctInfos, ok := signerToKernels[signer] if !ok { acctInfos = AcctInfos{Idx: ordered} ordered++ @@ -149,22 +155,20 @@ func (r *Repository) GetAccounts(ctx context.Context, first *int, after *string, Address: common.BytesToAddress(acct.Kernel), CreatedAt: acct.CreatedAt, Signer: &gmodel.Signer{ - Address: common.BytesToAddress(owner.Bytes()), + Address: common.BytesToAddress(signer.Bytes()), SignerAdded: acct.SignerAdded, }, }) acctInfos.Cursor = append(acctInfos.Cursor, c) - ownerToKernals[owner] = acctInfos + signerToKernels[signer] = acctInfos } - edges := make([]*gmodel.AccountEdge, len(ownerToKernals)) - nodes := make([]*gmodel.Account, len(ownerToKernals)) - var errList gqlerror.List - - for owner, acctInfos := range ownerToKernals { + edges := make([]*gmodel.AccountEdge, len(signerToKernels)) + nodes := make([]*gmodel.Account, len(signerToKernels)) + for signer, acctInfos := range signerToKernels { apiAccount := &gmodel.Account{ - Signer: owner, + Signer: signer, Kernel: acctInfos.Kernels, } @@ -179,7 +183,6 @@ func (r *Repository) GetAccounts(ctx context.Context, first *int, after *string, } var endCur, startCur *string - if len(all) != 0 { startCur = &edges[0].Cursor endCur = &edges[len(edges)-1].Cursor @@ -196,9 +199,7 @@ func (r *Repository) GetAccounts(ctx context.Context, first *int, after *string, HasPreviousPage: hasPrevious, }, } - if errList != nil { - return res, errList - } + return res, nil } diff --git a/internal/services/contracts_events_consumer.go b/internal/services/contracts_events_consumer.go index 91c46521..b2991341 100644 --- a/internal/services/contracts_events_consumer.go +++ b/internal/services/contracts_events_consumer.go @@ -71,6 +71,9 @@ const ( // Kernel ECDSA Validator. OwnerRegistered EventName = "OwnerRegistered" + + // WebAuthnPublicKeyRegistered + WebAuthnPublicKeyRegistered EventName = "WebAuthnPublicKeyRegistered" ) func (r EventName) String() string { @@ -699,9 +702,9 @@ func (c *ContractsEventsConsumer) handleOwnerRegisteredEvent(ctx context.Context return err } - kernel := models.KernelAccount{ - Kernel: args.Kernel.Bytes(), - OwnerAddress: args.Owner.Bytes(), + kernel := models.Account{ + Kernel: args.Kernel.Bytes(), + Signer: args.Owner.Bytes(), } return kernel.Insert(ctx, c.dbs.DBS().Writer, boil.Infer()) diff --git a/migrations/00031_kernel_tbl.sql b/migrations/00031_kernel_tbl.sql index bee6ae59..5083277f 100644 --- a/migrations/00031_kernel_tbl.sql +++ b/migrations/00031_kernel_tbl.sql @@ -1,14 +1,14 @@ -- +goose Up -- +goose StatementBegin -CREATE TABLE kernel_accounts( - kernel bytea CONSTRAINT kernel_accounts_kernel_address_check CHECK (length(kernel) = 20) PRIMARY KEY, +CREATE TABLE accounts( + kernel bytea CONSTRAINT accounts_kernel_address_check CHECK (length(kernel) = 20) PRIMARY KEY, + signer bytea CONSTRAINT accounts_signer_check CHECK (length(signer) = 20) NOT NULL, created_at timestamptz NOT NULL DEFAULT NOW(), - signer_added timestamptz NOT NULL DEFAULT NOW(), - owner_address bytea CONSTRAINT kernel_accounts_owner_address_check CHECK (length(owner_address) = 20) NOT NULL -- TODO(ae): should this reference any other table? + signer_added timestamptz NOT NULL DEFAULT NOW() ); -- +goose StatementEnd -- +goose Down -- +goose StatementBegin -DROP TABLE kernel_accounts; +DROP TABLE accounts; -- +goose StatementEnd diff --git a/models/accounts.go b/models/accounts.go new file mode 100644 index 00000000..7d428ebf --- /dev/null +++ b/models/accounts.go @@ -0,0 +1,986 @@ +// Code generated by SQLBoiler 4.16.2 (https://github.com/volatiletech/sqlboiler). DO NOT EDIT. +// This file is meant to be re-generated in place and/or deleted at any time. + +package models + +import ( + "context" + "database/sql" + "fmt" + "reflect" + "strconv" + "strings" + "sync" + "time" + + "github.com/friendsofgo/errors" + "github.com/volatiletech/sqlboiler/v4/boil" + "github.com/volatiletech/sqlboiler/v4/queries" + "github.com/volatiletech/sqlboiler/v4/queries/qm" + "github.com/volatiletech/sqlboiler/v4/queries/qmhelper" + "github.com/volatiletech/strmangle" +) + +// Account is an object representing the database table. +type Account struct { + Kernel []byte `boil:"kernel" json:"kernel" toml:"kernel" yaml:"kernel"` + Signer []byte `boil:"signer" json:"signer" toml:"signer" yaml:"signer"` + CreatedAt time.Time `boil:"created_at" json:"created_at" toml:"created_at" yaml:"created_at"` + SignerAdded time.Time `boil:"signer_added" json:"signer_added" toml:"signer_added" yaml:"signer_added"` + + R *accountR `boil:"-" json:"-" toml:"-" yaml:"-"` + L accountL `boil:"-" json:"-" toml:"-" yaml:"-"` +} + +var AccountColumns = struct { + Kernel string + Signer string + CreatedAt string + SignerAdded string +}{ + Kernel: "kernel", + Signer: "signer", + CreatedAt: "created_at", + SignerAdded: "signer_added", +} + +var AccountTableColumns = struct { + Kernel string + Signer string + CreatedAt string + SignerAdded string +}{ + Kernel: "accounts.kernel", + Signer: "accounts.signer", + CreatedAt: "accounts.created_at", + SignerAdded: "accounts.signer_added", +} + +// Generated where + +type whereHelper__byte struct{ field string } + +func (w whereHelper__byte) EQ(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.EQ, x) } +func (w whereHelper__byte) NEQ(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.NEQ, x) } +func (w whereHelper__byte) LT(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LT, x) } +func (w whereHelper__byte) LTE(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LTE, x) } +func (w whereHelper__byte) GT(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GT, x) } +func (w whereHelper__byte) GTE(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GTE, x) } + +type whereHelpertime_Time struct{ field string } + +func (w whereHelpertime_Time) EQ(x time.Time) qm.QueryMod { + return qmhelper.Where(w.field, qmhelper.EQ, x) +} +func (w whereHelpertime_Time) NEQ(x time.Time) qm.QueryMod { + return qmhelper.Where(w.field, qmhelper.NEQ, x) +} +func (w whereHelpertime_Time) LT(x time.Time) qm.QueryMod { + return qmhelper.Where(w.field, qmhelper.LT, x) +} +func (w whereHelpertime_Time) LTE(x time.Time) qm.QueryMod { + return qmhelper.Where(w.field, qmhelper.LTE, x) +} +func (w whereHelpertime_Time) GT(x time.Time) qm.QueryMod { + return qmhelper.Where(w.field, qmhelper.GT, x) +} +func (w whereHelpertime_Time) GTE(x time.Time) qm.QueryMod { + return qmhelper.Where(w.field, qmhelper.GTE, x) +} + +var AccountWhere = struct { + Kernel whereHelper__byte + Signer whereHelper__byte + CreatedAt whereHelpertime_Time + SignerAdded whereHelpertime_Time +}{ + Kernel: whereHelper__byte{field: "\"identity_api\".\"accounts\".\"kernel\""}, + Signer: whereHelper__byte{field: "\"identity_api\".\"accounts\".\"signer\""}, + CreatedAt: whereHelpertime_Time{field: "\"identity_api\".\"accounts\".\"created_at\""}, + SignerAdded: whereHelpertime_Time{field: "\"identity_api\".\"accounts\".\"signer_added\""}, +} + +// AccountRels is where relationship names are stored. +var AccountRels = struct { +}{} + +// accountR is where relationships are stored. +type accountR struct { +} + +// NewStruct creates a new relationship struct +func (*accountR) NewStruct() *accountR { + return &accountR{} +} + +// accountL is where Load methods for each relationship are stored. +type accountL struct{} + +var ( + accountAllColumns = []string{"kernel", "signer", "created_at", "signer_added"} + accountColumnsWithoutDefault = []string{"kernel", "signer"} + accountColumnsWithDefault = []string{"created_at", "signer_added"} + accountPrimaryKeyColumns = []string{"kernel"} + accountGeneratedColumns = []string{} +) + +type ( + // AccountSlice is an alias for a slice of pointers to Account. + // This should almost always be used instead of []Account. + AccountSlice []*Account + // AccountHook is the signature for custom Account hook methods + AccountHook func(context.Context, boil.ContextExecutor, *Account) error + + accountQuery struct { + *queries.Query + } +) + +// Cache for insert, update and upsert +var ( + accountType = reflect.TypeOf(&Account{}) + accountMapping = queries.MakeStructMapping(accountType) + accountPrimaryKeyMapping, _ = queries.BindMapping(accountType, accountMapping, accountPrimaryKeyColumns) + accountInsertCacheMut sync.RWMutex + accountInsertCache = make(map[string]insertCache) + accountUpdateCacheMut sync.RWMutex + accountUpdateCache = make(map[string]updateCache) + accountUpsertCacheMut sync.RWMutex + accountUpsertCache = make(map[string]insertCache) +) + +var ( + // Force time package dependency for automated UpdatedAt/CreatedAt. + _ = time.Second + // Force qmhelper dependency for where clause generation (which doesn't + // always happen) + _ = qmhelper.Where +) + +var accountAfterSelectMu sync.Mutex +var accountAfterSelectHooks []AccountHook + +var accountBeforeInsertMu sync.Mutex +var accountBeforeInsertHooks []AccountHook +var accountAfterInsertMu sync.Mutex +var accountAfterInsertHooks []AccountHook + +var accountBeforeUpdateMu sync.Mutex +var accountBeforeUpdateHooks []AccountHook +var accountAfterUpdateMu sync.Mutex +var accountAfterUpdateHooks []AccountHook + +var accountBeforeDeleteMu sync.Mutex +var accountBeforeDeleteHooks []AccountHook +var accountAfterDeleteMu sync.Mutex +var accountAfterDeleteHooks []AccountHook + +var accountBeforeUpsertMu sync.Mutex +var accountBeforeUpsertHooks []AccountHook +var accountAfterUpsertMu sync.Mutex +var accountAfterUpsertHooks []AccountHook + +// doAfterSelectHooks executes all "after Select" hooks. +func (o *Account) doAfterSelectHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range accountAfterSelectHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doBeforeInsertHooks executes all "before insert" hooks. +func (o *Account) doBeforeInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range accountBeforeInsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterInsertHooks executes all "after Insert" hooks. +func (o *Account) doAfterInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range accountAfterInsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doBeforeUpdateHooks executes all "before Update" hooks. +func (o *Account) doBeforeUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range accountBeforeUpdateHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterUpdateHooks executes all "after Update" hooks. +func (o *Account) doAfterUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range accountAfterUpdateHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doBeforeDeleteHooks executes all "before Delete" hooks. +func (o *Account) doBeforeDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range accountBeforeDeleteHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterDeleteHooks executes all "after Delete" hooks. +func (o *Account) doAfterDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range accountAfterDeleteHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doBeforeUpsertHooks executes all "before Upsert" hooks. +func (o *Account) doBeforeUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range accountBeforeUpsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterUpsertHooks executes all "after Upsert" hooks. +func (o *Account) doAfterUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range accountAfterUpsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// AddAccountHook registers your hook function for all future operations. +func AddAccountHook(hookPoint boil.HookPoint, accountHook AccountHook) { + switch hookPoint { + case boil.AfterSelectHook: + accountAfterSelectMu.Lock() + accountAfterSelectHooks = append(accountAfterSelectHooks, accountHook) + accountAfterSelectMu.Unlock() + case boil.BeforeInsertHook: + accountBeforeInsertMu.Lock() + accountBeforeInsertHooks = append(accountBeforeInsertHooks, accountHook) + accountBeforeInsertMu.Unlock() + case boil.AfterInsertHook: + accountAfterInsertMu.Lock() + accountAfterInsertHooks = append(accountAfterInsertHooks, accountHook) + accountAfterInsertMu.Unlock() + case boil.BeforeUpdateHook: + accountBeforeUpdateMu.Lock() + accountBeforeUpdateHooks = append(accountBeforeUpdateHooks, accountHook) + accountBeforeUpdateMu.Unlock() + case boil.AfterUpdateHook: + accountAfterUpdateMu.Lock() + accountAfterUpdateHooks = append(accountAfterUpdateHooks, accountHook) + accountAfterUpdateMu.Unlock() + case boil.BeforeDeleteHook: + accountBeforeDeleteMu.Lock() + accountBeforeDeleteHooks = append(accountBeforeDeleteHooks, accountHook) + accountBeforeDeleteMu.Unlock() + case boil.AfterDeleteHook: + accountAfterDeleteMu.Lock() + accountAfterDeleteHooks = append(accountAfterDeleteHooks, accountHook) + accountAfterDeleteMu.Unlock() + case boil.BeforeUpsertHook: + accountBeforeUpsertMu.Lock() + accountBeforeUpsertHooks = append(accountBeforeUpsertHooks, accountHook) + accountBeforeUpsertMu.Unlock() + case boil.AfterUpsertHook: + accountAfterUpsertMu.Lock() + accountAfterUpsertHooks = append(accountAfterUpsertHooks, accountHook) + accountAfterUpsertMu.Unlock() + } +} + +// One returns a single account record from the query. +func (q accountQuery) One(ctx context.Context, exec boil.ContextExecutor) (*Account, error) { + o := &Account{} + + queries.SetLimit(q.Query, 1) + + err := q.Bind(ctx, exec, o) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, sql.ErrNoRows + } + return nil, errors.Wrap(err, "models: failed to execute a one query for accounts") + } + + if err := o.doAfterSelectHooks(ctx, exec); err != nil { + return o, err + } + + return o, nil +} + +// All returns all Account records from the query. +func (q accountQuery) All(ctx context.Context, exec boil.ContextExecutor) (AccountSlice, error) { + var o []*Account + + err := q.Bind(ctx, exec, &o) + if err != nil { + return nil, errors.Wrap(err, "models: failed to assign all query results to Account slice") + } + + if len(accountAfterSelectHooks) != 0 { + for _, obj := range o { + if err := obj.doAfterSelectHooks(ctx, exec); err != nil { + return o, err + } + } + } + + return o, nil +} + +// Count returns the count of all Account records in the query. +func (q accountQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + var count int64 + + queries.SetSelect(q.Query, nil) + queries.SetCount(q.Query) + + err := q.Query.QueryRowContext(ctx, exec).Scan(&count) + if err != nil { + return 0, errors.Wrap(err, "models: failed to count accounts rows") + } + + return count, nil +} + +// Exists checks if the row exists in the table. +func (q accountQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) { + var count int64 + + queries.SetSelect(q.Query, nil) + queries.SetCount(q.Query) + queries.SetLimit(q.Query, 1) + + err := q.Query.QueryRowContext(ctx, exec).Scan(&count) + if err != nil { + return false, errors.Wrap(err, "models: failed to check if accounts exists") + } + + return count > 0, nil +} + +// Accounts retrieves all the records using an executor. +func Accounts(mods ...qm.QueryMod) accountQuery { + mods = append(mods, qm.From("\"identity_api\".\"accounts\"")) + q := NewQuery(mods...) + if len(queries.GetSelect(q)) == 0 { + queries.SetSelect(q, []string{"\"identity_api\".\"accounts\".*"}) + } + + return accountQuery{q} +} + +// FindAccount retrieves a single record by ID with an executor. +// If selectCols is empty Find will return all columns. +func FindAccount(ctx context.Context, exec boil.ContextExecutor, kernel []byte, selectCols ...string) (*Account, error) { + accountObj := &Account{} + + sel := "*" + if len(selectCols) > 0 { + sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",") + } + query := fmt.Sprintf( + "select %s from \"identity_api\".\"accounts\" where \"kernel\"=$1", sel, + ) + + q := queries.Raw(query, kernel) + + err := q.Bind(ctx, exec, accountObj) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, sql.ErrNoRows + } + return nil, errors.Wrap(err, "models: unable to select from accounts") + } + + if err = accountObj.doAfterSelectHooks(ctx, exec); err != nil { + return accountObj, err + } + + return accountObj, nil +} + +// Insert a single record using an executor. +// See boil.Columns.InsertColumnSet documentation to understand column list inference for inserts. +func (o *Account) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error { + if o == nil { + return errors.New("models: no accounts provided for insertion") + } + + var err error + if !boil.TimestampsAreSkipped(ctx) { + currTime := time.Now().In(boil.GetLocation()) + + if o.CreatedAt.IsZero() { + o.CreatedAt = currTime + } + } + + if err := o.doBeforeInsertHooks(ctx, exec); err != nil { + return err + } + + nzDefaults := queries.NonZeroDefaultSet(accountColumnsWithDefault, o) + + key := makeCacheKey(columns, nzDefaults) + accountInsertCacheMut.RLock() + cache, cached := accountInsertCache[key] + accountInsertCacheMut.RUnlock() + + if !cached { + wl, returnColumns := columns.InsertColumnSet( + accountAllColumns, + accountColumnsWithDefault, + accountColumnsWithoutDefault, + nzDefaults, + ) + + cache.valueMapping, err = queries.BindMapping(accountType, accountMapping, wl) + if err != nil { + return err + } + cache.retMapping, err = queries.BindMapping(accountType, accountMapping, returnColumns) + if err != nil { + return err + } + if len(wl) != 0 { + cache.query = fmt.Sprintf("INSERT INTO \"identity_api\".\"accounts\" (\"%s\") %%sVALUES (%s)%%s", strings.Join(wl, "\",\""), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1)) + } else { + cache.query = "INSERT INTO \"identity_api\".\"accounts\" %sDEFAULT VALUES%s" + } + + var queryOutput, queryReturning string + + if len(cache.retMapping) != 0 { + queryReturning = fmt.Sprintf(" RETURNING \"%s\"", strings.Join(returnColumns, "\",\"")) + } + + cache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning) + } + + value := reflect.Indirect(reflect.ValueOf(o)) + vals := queries.ValuesFromMapping(value, cache.valueMapping) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, cache.query) + fmt.Fprintln(writer, vals) + } + + if len(cache.retMapping) != 0 { + err = exec.QueryRowContext(ctx, cache.query, vals...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...) + } else { + _, err = exec.ExecContext(ctx, cache.query, vals...) + } + + if err != nil { + return errors.Wrap(err, "models: unable to insert into accounts") + } + + if !cached { + accountInsertCacheMut.Lock() + accountInsertCache[key] = cache + accountInsertCacheMut.Unlock() + } + + return o.doAfterInsertHooks(ctx, exec) +} + +// Update uses an executor to update the Account. +// See boil.Columns.UpdateColumnSet documentation to understand column list inference for updates. +// Update does not automatically update the record in case of default values. Use .Reload() to refresh the records. +func (o *Account) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) { + var err error + if err = o.doBeforeUpdateHooks(ctx, exec); err != nil { + return 0, err + } + key := makeCacheKey(columns, nil) + accountUpdateCacheMut.RLock() + cache, cached := accountUpdateCache[key] + accountUpdateCacheMut.RUnlock() + + if !cached { + wl := columns.UpdateColumnSet( + accountAllColumns, + accountPrimaryKeyColumns, + ) + + if !columns.IsWhitelist() { + wl = strmangle.SetComplement(wl, []string{"created_at"}) + } + if len(wl) == 0 { + return 0, errors.New("models: unable to update accounts, could not build whitelist") + } + + cache.query = fmt.Sprintf("UPDATE \"identity_api\".\"accounts\" SET %s WHERE %s", + strmangle.SetParamNames("\"", "\"", 1, wl), + strmangle.WhereClause("\"", "\"", len(wl)+1, accountPrimaryKeyColumns), + ) + cache.valueMapping, err = queries.BindMapping(accountType, accountMapping, append(wl, accountPrimaryKeyColumns...)) + if err != nil { + return 0, err + } + } + + values := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, cache.query) + fmt.Fprintln(writer, values) + } + var result sql.Result + result, err = exec.ExecContext(ctx, cache.query, values...) + if err != nil { + return 0, errors.Wrap(err, "models: unable to update accounts row") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: failed to get rows affected by update for accounts") + } + + if !cached { + accountUpdateCacheMut.Lock() + accountUpdateCache[key] = cache + accountUpdateCacheMut.Unlock() + } + + return rowsAff, o.doAfterUpdateHooks(ctx, exec) +} + +// UpdateAll updates all rows with the specified column values. +func (q accountQuery) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { + queries.SetUpdate(q.Query, cols) + + result, err := q.Query.ExecContext(ctx, exec) + if err != nil { + return 0, errors.Wrap(err, "models: unable to update all for accounts") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: unable to retrieve rows affected for accounts") + } + + return rowsAff, nil +} + +// UpdateAll updates all rows with the specified column values, using an executor. +func (o AccountSlice) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { + ln := int64(len(o)) + if ln == 0 { + return 0, nil + } + + if len(cols) == 0 { + return 0, errors.New("models: update all requires at least one column argument") + } + + colNames := make([]string, len(cols)) + args := make([]interface{}, len(cols)) + + i := 0 + for name, value := range cols { + colNames[i] = name + args[i] = value + i++ + } + + // Append all of the primary key values for each column + for _, obj := range o { + pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), accountPrimaryKeyMapping) + args = append(args, pkeyArgs...) + } + + sql := fmt.Sprintf("UPDATE \"identity_api\".\"accounts\" SET %s WHERE %s", + strmangle.SetParamNames("\"", "\"", 1, colNames), + strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), len(colNames)+1, accountPrimaryKeyColumns, len(o))) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, args...) + } + result, err := exec.ExecContext(ctx, sql, args...) + if err != nil { + return 0, errors.Wrap(err, "models: unable to update all in account slice") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: unable to retrieve rows affected all in update all account") + } + return rowsAff, nil +} + +// Upsert attempts an insert using an executor, and does an update or ignore on conflict. +// See boil.Columns documentation for how to properly use updateColumns and insertColumns. +func (o *Account) Upsert(ctx context.Context, exec boil.ContextExecutor, updateOnConflict bool, conflictColumns []string, updateColumns, insertColumns boil.Columns, opts ...UpsertOptionFunc) error { + if o == nil { + return errors.New("models: no accounts provided for upsert") + } + if !boil.TimestampsAreSkipped(ctx) { + currTime := time.Now().In(boil.GetLocation()) + + if o.CreatedAt.IsZero() { + o.CreatedAt = currTime + } + } + + if err := o.doBeforeUpsertHooks(ctx, exec); err != nil { + return err + } + + nzDefaults := queries.NonZeroDefaultSet(accountColumnsWithDefault, o) + + // Build cache key in-line uglily - mysql vs psql problems + buf := strmangle.GetBuffer() + if updateOnConflict { + buf.WriteByte('t') + } else { + buf.WriteByte('f') + } + buf.WriteByte('.') + for _, c := range conflictColumns { + buf.WriteString(c) + } + buf.WriteByte('.') + buf.WriteString(strconv.Itoa(updateColumns.Kind)) + for _, c := range updateColumns.Cols { + buf.WriteString(c) + } + buf.WriteByte('.') + buf.WriteString(strconv.Itoa(insertColumns.Kind)) + for _, c := range insertColumns.Cols { + buf.WriteString(c) + } + buf.WriteByte('.') + for _, c := range nzDefaults { + buf.WriteString(c) + } + key := buf.String() + strmangle.PutBuffer(buf) + + accountUpsertCacheMut.RLock() + cache, cached := accountUpsertCache[key] + accountUpsertCacheMut.RUnlock() + + var err error + + if !cached { + insert, _ := insertColumns.InsertColumnSet( + accountAllColumns, + accountColumnsWithDefault, + accountColumnsWithoutDefault, + nzDefaults, + ) + + update := updateColumns.UpdateColumnSet( + accountAllColumns, + accountPrimaryKeyColumns, + ) + + if updateOnConflict && len(update) == 0 { + return errors.New("models: unable to upsert accounts, could not build update column list") + } + + ret := strmangle.SetComplement(accountAllColumns, strmangle.SetIntersect(insert, update)) + + conflict := conflictColumns + if len(conflict) == 0 && updateOnConflict && len(update) != 0 { + if len(accountPrimaryKeyColumns) == 0 { + return errors.New("models: unable to upsert accounts, could not build conflict column list") + } + + conflict = make([]string, len(accountPrimaryKeyColumns)) + copy(conflict, accountPrimaryKeyColumns) + } + cache.query = buildUpsertQueryPostgres(dialect, "\"identity_api\".\"accounts\"", updateOnConflict, ret, update, conflict, insert, opts...) + + cache.valueMapping, err = queries.BindMapping(accountType, accountMapping, insert) + if err != nil { + return err + } + if len(ret) != 0 { + cache.retMapping, err = queries.BindMapping(accountType, accountMapping, ret) + if err != nil { + return err + } + } + } + + value := reflect.Indirect(reflect.ValueOf(o)) + vals := queries.ValuesFromMapping(value, cache.valueMapping) + var returns []interface{} + if len(cache.retMapping) != 0 { + returns = queries.PtrsFromMapping(value, cache.retMapping) + } + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, cache.query) + fmt.Fprintln(writer, vals) + } + if len(cache.retMapping) != 0 { + err = exec.QueryRowContext(ctx, cache.query, vals...).Scan(returns...) + if errors.Is(err, sql.ErrNoRows) { + err = nil // Postgres doesn't return anything when there's no update + } + } else { + _, err = exec.ExecContext(ctx, cache.query, vals...) + } + if err != nil { + return errors.Wrap(err, "models: unable to upsert accounts") + } + + if !cached { + accountUpsertCacheMut.Lock() + accountUpsertCache[key] = cache + accountUpsertCacheMut.Unlock() + } + + return o.doAfterUpsertHooks(ctx, exec) +} + +// Delete deletes a single Account record with an executor. +// Delete will match against the primary key column to find the record to delete. +func (o *Account) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + if o == nil { + return 0, errors.New("models: no Account provided for delete") + } + + if err := o.doBeforeDeleteHooks(ctx, exec); err != nil { + return 0, err + } + + args := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), accountPrimaryKeyMapping) + sql := "DELETE FROM \"identity_api\".\"accounts\" WHERE \"kernel\"=$1" + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, args...) + } + result, err := exec.ExecContext(ctx, sql, args...) + if err != nil { + return 0, errors.Wrap(err, "models: unable to delete from accounts") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: failed to get rows affected by delete for accounts") + } + + if err := o.doAfterDeleteHooks(ctx, exec); err != nil { + return 0, err + } + + return rowsAff, nil +} + +// DeleteAll deletes all matching rows. +func (q accountQuery) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + if q.Query == nil { + return 0, errors.New("models: no accountQuery provided for delete all") + } + + queries.SetDelete(q.Query) + + result, err := q.Query.ExecContext(ctx, exec) + if err != nil { + return 0, errors.Wrap(err, "models: unable to delete all from accounts") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for accounts") + } + + return rowsAff, nil +} + +// DeleteAll deletes all rows in the slice, using an executor. +func (o AccountSlice) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + if len(o) == 0 { + return 0, nil + } + + if len(accountBeforeDeleteHooks) != 0 { + for _, obj := range o { + if err := obj.doBeforeDeleteHooks(ctx, exec); err != nil { + return 0, err + } + } + } + + var args []interface{} + for _, obj := range o { + pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), accountPrimaryKeyMapping) + args = append(args, pkeyArgs...) + } + + sql := "DELETE FROM \"identity_api\".\"accounts\" WHERE " + + strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, accountPrimaryKeyColumns, len(o)) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, args) + } + result, err := exec.ExecContext(ctx, sql, args...) + if err != nil { + return 0, errors.Wrap(err, "models: unable to delete all from account slice") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for accounts") + } + + if len(accountAfterDeleteHooks) != 0 { + for _, obj := range o { + if err := obj.doAfterDeleteHooks(ctx, exec); err != nil { + return 0, err + } + } + } + + return rowsAff, nil +} + +// Reload refetches the object from the database +// using the primary keys with an executor. +func (o *Account) Reload(ctx context.Context, exec boil.ContextExecutor) error { + ret, err := FindAccount(ctx, exec, o.Kernel) + if err != nil { + return err + } + + *o = *ret + return nil +} + +// ReloadAll refetches every row with matching primary key column values +// and overwrites the original object slice with the newly updated slice. +func (o *AccountSlice) ReloadAll(ctx context.Context, exec boil.ContextExecutor) error { + if o == nil || len(*o) == 0 { + return nil + } + + slice := AccountSlice{} + var args []interface{} + for _, obj := range *o { + pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), accountPrimaryKeyMapping) + args = append(args, pkeyArgs...) + } + + sql := "SELECT \"identity_api\".\"accounts\".* FROM \"identity_api\".\"accounts\" WHERE " + + strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, accountPrimaryKeyColumns, len(*o)) + + q := queries.Raw(sql, args...) + + err := q.Bind(ctx, exec, &slice) + if err != nil { + return errors.Wrap(err, "models: unable to reload all in AccountSlice") + } + + *o = slice + + return nil +} + +// AccountExists checks if the Account row exists. +func AccountExists(ctx context.Context, exec boil.ContextExecutor, kernel []byte) (bool, error) { + var exists bool + sql := "select exists(select 1 from \"identity_api\".\"accounts\" where \"kernel\"=$1 limit 1)" + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, kernel) + } + row := exec.QueryRowContext(ctx, sql, kernel) + + err := row.Scan(&exists) + if err != nil { + return false, errors.Wrap(err, "models: unable to check if accounts exists") + } + + return exists, nil +} + +// Exists checks if the Account row exists. +func (o *Account) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) { + return AccountExists(ctx, exec, o.Kernel) +} diff --git a/models/aftermarket_devices.go b/models/aftermarket_devices.go index 7115528e..eace46ae 100644 --- a/models/aftermarket_devices.go +++ b/models/aftermarket_devices.go @@ -117,15 +117,6 @@ func (w whereHelperint) NIN(slice []int) qm.QueryMod { return qm.WhereNotIn(fmt.Sprintf("%s NOT IN ?", w.field), values...) } -type whereHelper__byte struct{ field string } - -func (w whereHelper__byte) EQ(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.EQ, x) } -func (w whereHelper__byte) NEQ(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.NEQ, x) } -func (w whereHelper__byte) LT(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LT, x) } -func (w whereHelper__byte) LTE(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LTE, x) } -func (w whereHelper__byte) GT(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GT, x) } -func (w whereHelper__byte) GTE(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GTE, x) } - type whereHelpernull_String struct{ field string } func (w whereHelpernull_String) EQ(x null.String) qm.QueryMod { @@ -176,27 +167,6 @@ func (w whereHelpernull_String) NIN(slice []string) qm.QueryMod { func (w whereHelpernull_String) IsNull() qm.QueryMod { return qmhelper.WhereIsNull(w.field) } func (w whereHelpernull_String) IsNotNull() qm.QueryMod { return qmhelper.WhereIsNotNull(w.field) } -type whereHelpertime_Time struct{ field string } - -func (w whereHelpertime_Time) EQ(x time.Time) qm.QueryMod { - return qmhelper.Where(w.field, qmhelper.EQ, x) -} -func (w whereHelpertime_Time) NEQ(x time.Time) qm.QueryMod { - return qmhelper.Where(w.field, qmhelper.NEQ, x) -} -func (w whereHelpertime_Time) LT(x time.Time) qm.QueryMod { - return qmhelper.Where(w.field, qmhelper.LT, x) -} -func (w whereHelpertime_Time) LTE(x time.Time) qm.QueryMod { - return qmhelper.Where(w.field, qmhelper.LTE, x) -} -func (w whereHelpertime_Time) GT(x time.Time) qm.QueryMod { - return qmhelper.Where(w.field, qmhelper.GT, x) -} -func (w whereHelpertime_Time) GTE(x time.Time) qm.QueryMod { - return qmhelper.Where(w.field, qmhelper.GTE, x) -} - type whereHelpernull_Int struct{ field string } func (w whereHelpernull_Int) EQ(x null.Int) qm.QueryMod { diff --git a/models/boil_table_names.go b/models/boil_table_names.go index 481f9c7a..48f3e945 100644 --- a/models/boil_table_names.go +++ b/models/boil_table_names.go @@ -4,18 +4,18 @@ package models var TableNames = struct { + Accounts string AftermarketDevices string DCNS string - KernelAccounts string Manufacturers string Privileges string Rewards string SyntheticDevices string Vehicles string }{ + Accounts: "accounts", AftermarketDevices: "aftermarket_devices", DCNS: "dcns", - KernelAccounts: "kernel_accounts", Manufacturers: "manufacturers", Privileges: "privileges", Rewards: "rewards", diff --git a/models/kernel_accounts.go b/models/kernel_accounts.go deleted file mode 100644 index ba5de86a..00000000 --- a/models/kernel_accounts.go +++ /dev/null @@ -1,956 +0,0 @@ -// Code generated by SQLBoiler 4.16.2 (https://github.com/volatiletech/sqlboiler). DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package models - -import ( - "context" - "database/sql" - "fmt" - "reflect" - "strconv" - "strings" - "sync" - "time" - - "github.com/friendsofgo/errors" - "github.com/volatiletech/sqlboiler/v4/boil" - "github.com/volatiletech/sqlboiler/v4/queries" - "github.com/volatiletech/sqlboiler/v4/queries/qm" - "github.com/volatiletech/sqlboiler/v4/queries/qmhelper" - "github.com/volatiletech/strmangle" -) - -// KernelAccount is an object representing the database table. -type KernelAccount struct { - Kernel []byte `boil:"kernel" json:"kernel" toml:"kernel" yaml:"kernel"` - CreatedAt time.Time `boil:"created_at" json:"created_at" toml:"created_at" yaml:"created_at"` - SignerAdded time.Time `boil:"signer_added" json:"signer_added" toml:"signer_added" yaml:"signer_added"` - OwnerAddress []byte `boil:"owner_address" json:"owner_address" toml:"owner_address" yaml:"owner_address"` - - R *kernelAccountR `boil:"-" json:"-" toml:"-" yaml:"-"` - L kernelAccountL `boil:"-" json:"-" toml:"-" yaml:"-"` -} - -var KernelAccountColumns = struct { - Kernel string - CreatedAt string - SignerAdded string - OwnerAddress string -}{ - Kernel: "kernel", - CreatedAt: "created_at", - SignerAdded: "signer_added", - OwnerAddress: "owner_address", -} - -var KernelAccountTableColumns = struct { - Kernel string - CreatedAt string - SignerAdded string - OwnerAddress string -}{ - Kernel: "kernel_accounts.kernel", - CreatedAt: "kernel_accounts.created_at", - SignerAdded: "kernel_accounts.signer_added", - OwnerAddress: "kernel_accounts.owner_address", -} - -// Generated where - -var KernelAccountWhere = struct { - Kernel whereHelper__byte - CreatedAt whereHelpertime_Time - SignerAdded whereHelpertime_Time - OwnerAddress whereHelper__byte -}{ - Kernel: whereHelper__byte{field: "\"identity_api\".\"kernel_accounts\".\"kernel\""}, - CreatedAt: whereHelpertime_Time{field: "\"identity_api\".\"kernel_accounts\".\"created_at\""}, - SignerAdded: whereHelpertime_Time{field: "\"identity_api\".\"kernel_accounts\".\"signer_added\""}, - OwnerAddress: whereHelper__byte{field: "\"identity_api\".\"kernel_accounts\".\"owner_address\""}, -} - -// KernelAccountRels is where relationship names are stored. -var KernelAccountRels = struct { -}{} - -// kernelAccountR is where relationships are stored. -type kernelAccountR struct { -} - -// NewStruct creates a new relationship struct -func (*kernelAccountR) NewStruct() *kernelAccountR { - return &kernelAccountR{} -} - -// kernelAccountL is where Load methods for each relationship are stored. -type kernelAccountL struct{} - -var ( - kernelAccountAllColumns = []string{"kernel", "created_at", "signer_added", "owner_address"} - kernelAccountColumnsWithoutDefault = []string{"kernel", "owner_address"} - kernelAccountColumnsWithDefault = []string{"created_at", "signer_added"} - kernelAccountPrimaryKeyColumns = []string{"kernel"} - kernelAccountGeneratedColumns = []string{} -) - -type ( - // KernelAccountSlice is an alias for a slice of pointers to KernelAccount. - // This should almost always be used instead of []KernelAccount. - KernelAccountSlice []*KernelAccount - // KernelAccountHook is the signature for custom KernelAccount hook methods - KernelAccountHook func(context.Context, boil.ContextExecutor, *KernelAccount) error - - kernelAccountQuery struct { - *queries.Query - } -) - -// Cache for insert, update and upsert -var ( - kernelAccountType = reflect.TypeOf(&KernelAccount{}) - kernelAccountMapping = queries.MakeStructMapping(kernelAccountType) - kernelAccountPrimaryKeyMapping, _ = queries.BindMapping(kernelAccountType, kernelAccountMapping, kernelAccountPrimaryKeyColumns) - kernelAccountInsertCacheMut sync.RWMutex - kernelAccountInsertCache = make(map[string]insertCache) - kernelAccountUpdateCacheMut sync.RWMutex - kernelAccountUpdateCache = make(map[string]updateCache) - kernelAccountUpsertCacheMut sync.RWMutex - kernelAccountUpsertCache = make(map[string]insertCache) -) - -var ( - // Force time package dependency for automated UpdatedAt/CreatedAt. - _ = time.Second - // Force qmhelper dependency for where clause generation (which doesn't - // always happen) - _ = qmhelper.Where -) - -var kernelAccountAfterSelectMu sync.Mutex -var kernelAccountAfterSelectHooks []KernelAccountHook - -var kernelAccountBeforeInsertMu sync.Mutex -var kernelAccountBeforeInsertHooks []KernelAccountHook -var kernelAccountAfterInsertMu sync.Mutex -var kernelAccountAfterInsertHooks []KernelAccountHook - -var kernelAccountBeforeUpdateMu sync.Mutex -var kernelAccountBeforeUpdateHooks []KernelAccountHook -var kernelAccountAfterUpdateMu sync.Mutex -var kernelAccountAfterUpdateHooks []KernelAccountHook - -var kernelAccountBeforeDeleteMu sync.Mutex -var kernelAccountBeforeDeleteHooks []KernelAccountHook -var kernelAccountAfterDeleteMu sync.Mutex -var kernelAccountAfterDeleteHooks []KernelAccountHook - -var kernelAccountBeforeUpsertMu sync.Mutex -var kernelAccountBeforeUpsertHooks []KernelAccountHook -var kernelAccountAfterUpsertMu sync.Mutex -var kernelAccountAfterUpsertHooks []KernelAccountHook - -// doAfterSelectHooks executes all "after Select" hooks. -func (o *KernelAccount) doAfterSelectHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range kernelAccountAfterSelectHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doBeforeInsertHooks executes all "before insert" hooks. -func (o *KernelAccount) doBeforeInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range kernelAccountBeforeInsertHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doAfterInsertHooks executes all "after Insert" hooks. -func (o *KernelAccount) doAfterInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range kernelAccountAfterInsertHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doBeforeUpdateHooks executes all "before Update" hooks. -func (o *KernelAccount) doBeforeUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range kernelAccountBeforeUpdateHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doAfterUpdateHooks executes all "after Update" hooks. -func (o *KernelAccount) doAfterUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range kernelAccountAfterUpdateHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doBeforeDeleteHooks executes all "before Delete" hooks. -func (o *KernelAccount) doBeforeDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range kernelAccountBeforeDeleteHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doAfterDeleteHooks executes all "after Delete" hooks. -func (o *KernelAccount) doAfterDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range kernelAccountAfterDeleteHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doBeforeUpsertHooks executes all "before Upsert" hooks. -func (o *KernelAccount) doBeforeUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range kernelAccountBeforeUpsertHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doAfterUpsertHooks executes all "after Upsert" hooks. -func (o *KernelAccount) doAfterUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range kernelAccountAfterUpsertHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// AddKernelAccountHook registers your hook function for all future operations. -func AddKernelAccountHook(hookPoint boil.HookPoint, kernelAccountHook KernelAccountHook) { - switch hookPoint { - case boil.AfterSelectHook: - kernelAccountAfterSelectMu.Lock() - kernelAccountAfterSelectHooks = append(kernelAccountAfterSelectHooks, kernelAccountHook) - kernelAccountAfterSelectMu.Unlock() - case boil.BeforeInsertHook: - kernelAccountBeforeInsertMu.Lock() - kernelAccountBeforeInsertHooks = append(kernelAccountBeforeInsertHooks, kernelAccountHook) - kernelAccountBeforeInsertMu.Unlock() - case boil.AfterInsertHook: - kernelAccountAfterInsertMu.Lock() - kernelAccountAfterInsertHooks = append(kernelAccountAfterInsertHooks, kernelAccountHook) - kernelAccountAfterInsertMu.Unlock() - case boil.BeforeUpdateHook: - kernelAccountBeforeUpdateMu.Lock() - kernelAccountBeforeUpdateHooks = append(kernelAccountBeforeUpdateHooks, kernelAccountHook) - kernelAccountBeforeUpdateMu.Unlock() - case boil.AfterUpdateHook: - kernelAccountAfterUpdateMu.Lock() - kernelAccountAfterUpdateHooks = append(kernelAccountAfterUpdateHooks, kernelAccountHook) - kernelAccountAfterUpdateMu.Unlock() - case boil.BeforeDeleteHook: - kernelAccountBeforeDeleteMu.Lock() - kernelAccountBeforeDeleteHooks = append(kernelAccountBeforeDeleteHooks, kernelAccountHook) - kernelAccountBeforeDeleteMu.Unlock() - case boil.AfterDeleteHook: - kernelAccountAfterDeleteMu.Lock() - kernelAccountAfterDeleteHooks = append(kernelAccountAfterDeleteHooks, kernelAccountHook) - kernelAccountAfterDeleteMu.Unlock() - case boil.BeforeUpsertHook: - kernelAccountBeforeUpsertMu.Lock() - kernelAccountBeforeUpsertHooks = append(kernelAccountBeforeUpsertHooks, kernelAccountHook) - kernelAccountBeforeUpsertMu.Unlock() - case boil.AfterUpsertHook: - kernelAccountAfterUpsertMu.Lock() - kernelAccountAfterUpsertHooks = append(kernelAccountAfterUpsertHooks, kernelAccountHook) - kernelAccountAfterUpsertMu.Unlock() - } -} - -// One returns a single kernelAccount record from the query. -func (q kernelAccountQuery) One(ctx context.Context, exec boil.ContextExecutor) (*KernelAccount, error) { - o := &KernelAccount{} - - queries.SetLimit(q.Query, 1) - - err := q.Bind(ctx, exec, o) - if err != nil { - if errors.Is(err, sql.ErrNoRows) { - return nil, sql.ErrNoRows - } - return nil, errors.Wrap(err, "models: failed to execute a one query for kernel_accounts") - } - - if err := o.doAfterSelectHooks(ctx, exec); err != nil { - return o, err - } - - return o, nil -} - -// All returns all KernelAccount records from the query. -func (q kernelAccountQuery) All(ctx context.Context, exec boil.ContextExecutor) (KernelAccountSlice, error) { - var o []*KernelAccount - - err := q.Bind(ctx, exec, &o) - if err != nil { - return nil, errors.Wrap(err, "models: failed to assign all query results to KernelAccount slice") - } - - if len(kernelAccountAfterSelectHooks) != 0 { - for _, obj := range o { - if err := obj.doAfterSelectHooks(ctx, exec); err != nil { - return o, err - } - } - } - - return o, nil -} - -// Count returns the count of all KernelAccount records in the query. -func (q kernelAccountQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) { - var count int64 - - queries.SetSelect(q.Query, nil) - queries.SetCount(q.Query) - - err := q.Query.QueryRowContext(ctx, exec).Scan(&count) - if err != nil { - return 0, errors.Wrap(err, "models: failed to count kernel_accounts rows") - } - - return count, nil -} - -// Exists checks if the row exists in the table. -func (q kernelAccountQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) { - var count int64 - - queries.SetSelect(q.Query, nil) - queries.SetCount(q.Query) - queries.SetLimit(q.Query, 1) - - err := q.Query.QueryRowContext(ctx, exec).Scan(&count) - if err != nil { - return false, errors.Wrap(err, "models: failed to check if kernel_accounts exists") - } - - return count > 0, nil -} - -// KernelAccounts retrieves all the records using an executor. -func KernelAccounts(mods ...qm.QueryMod) kernelAccountQuery { - mods = append(mods, qm.From("\"identity_api\".\"kernel_accounts\"")) - q := NewQuery(mods...) - if len(queries.GetSelect(q)) == 0 { - queries.SetSelect(q, []string{"\"identity_api\".\"kernel_accounts\".*"}) - } - - return kernelAccountQuery{q} -} - -// FindKernelAccount retrieves a single record by ID with an executor. -// If selectCols is empty Find will return all columns. -func FindKernelAccount(ctx context.Context, exec boil.ContextExecutor, kernel []byte, selectCols ...string) (*KernelAccount, error) { - kernelAccountObj := &KernelAccount{} - - sel := "*" - if len(selectCols) > 0 { - sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",") - } - query := fmt.Sprintf( - "select %s from \"identity_api\".\"kernel_accounts\" where \"kernel\"=$1", sel, - ) - - q := queries.Raw(query, kernel) - - err := q.Bind(ctx, exec, kernelAccountObj) - if err != nil { - if errors.Is(err, sql.ErrNoRows) { - return nil, sql.ErrNoRows - } - return nil, errors.Wrap(err, "models: unable to select from kernel_accounts") - } - - if err = kernelAccountObj.doAfterSelectHooks(ctx, exec); err != nil { - return kernelAccountObj, err - } - - return kernelAccountObj, nil -} - -// Insert a single record using an executor. -// See boil.Columns.InsertColumnSet documentation to understand column list inference for inserts. -func (o *KernelAccount) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error { - if o == nil { - return errors.New("models: no kernel_accounts provided for insertion") - } - - var err error - if !boil.TimestampsAreSkipped(ctx) { - currTime := time.Now().In(boil.GetLocation()) - - if o.CreatedAt.IsZero() { - o.CreatedAt = currTime - } - } - - if err := o.doBeforeInsertHooks(ctx, exec); err != nil { - return err - } - - nzDefaults := queries.NonZeroDefaultSet(kernelAccountColumnsWithDefault, o) - - key := makeCacheKey(columns, nzDefaults) - kernelAccountInsertCacheMut.RLock() - cache, cached := kernelAccountInsertCache[key] - kernelAccountInsertCacheMut.RUnlock() - - if !cached { - wl, returnColumns := columns.InsertColumnSet( - kernelAccountAllColumns, - kernelAccountColumnsWithDefault, - kernelAccountColumnsWithoutDefault, - nzDefaults, - ) - - cache.valueMapping, err = queries.BindMapping(kernelAccountType, kernelAccountMapping, wl) - if err != nil { - return err - } - cache.retMapping, err = queries.BindMapping(kernelAccountType, kernelAccountMapping, returnColumns) - if err != nil { - return err - } - if len(wl) != 0 { - cache.query = fmt.Sprintf("INSERT INTO \"identity_api\".\"kernel_accounts\" (\"%s\") %%sVALUES (%s)%%s", strings.Join(wl, "\",\""), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1)) - } else { - cache.query = "INSERT INTO \"identity_api\".\"kernel_accounts\" %sDEFAULT VALUES%s" - } - - var queryOutput, queryReturning string - - if len(cache.retMapping) != 0 { - queryReturning = fmt.Sprintf(" RETURNING \"%s\"", strings.Join(returnColumns, "\",\"")) - } - - cache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning) - } - - value := reflect.Indirect(reflect.ValueOf(o)) - vals := queries.ValuesFromMapping(value, cache.valueMapping) - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, cache.query) - fmt.Fprintln(writer, vals) - } - - if len(cache.retMapping) != 0 { - err = exec.QueryRowContext(ctx, cache.query, vals...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...) - } else { - _, err = exec.ExecContext(ctx, cache.query, vals...) - } - - if err != nil { - return errors.Wrap(err, "models: unable to insert into kernel_accounts") - } - - if !cached { - kernelAccountInsertCacheMut.Lock() - kernelAccountInsertCache[key] = cache - kernelAccountInsertCacheMut.Unlock() - } - - return o.doAfterInsertHooks(ctx, exec) -} - -// Update uses an executor to update the KernelAccount. -// See boil.Columns.UpdateColumnSet documentation to understand column list inference for updates. -// Update does not automatically update the record in case of default values. Use .Reload() to refresh the records. -func (o *KernelAccount) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) { - var err error - if err = o.doBeforeUpdateHooks(ctx, exec); err != nil { - return 0, err - } - key := makeCacheKey(columns, nil) - kernelAccountUpdateCacheMut.RLock() - cache, cached := kernelAccountUpdateCache[key] - kernelAccountUpdateCacheMut.RUnlock() - - if !cached { - wl := columns.UpdateColumnSet( - kernelAccountAllColumns, - kernelAccountPrimaryKeyColumns, - ) - - if !columns.IsWhitelist() { - wl = strmangle.SetComplement(wl, []string{"created_at"}) - } - if len(wl) == 0 { - return 0, errors.New("models: unable to update kernel_accounts, could not build whitelist") - } - - cache.query = fmt.Sprintf("UPDATE \"identity_api\".\"kernel_accounts\" SET %s WHERE %s", - strmangle.SetParamNames("\"", "\"", 1, wl), - strmangle.WhereClause("\"", "\"", len(wl)+1, kernelAccountPrimaryKeyColumns), - ) - cache.valueMapping, err = queries.BindMapping(kernelAccountType, kernelAccountMapping, append(wl, kernelAccountPrimaryKeyColumns...)) - if err != nil { - return 0, err - } - } - - values := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping) - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, cache.query) - fmt.Fprintln(writer, values) - } - var result sql.Result - result, err = exec.ExecContext(ctx, cache.query, values...) - if err != nil { - return 0, errors.Wrap(err, "models: unable to update kernel_accounts row") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "models: failed to get rows affected by update for kernel_accounts") - } - - if !cached { - kernelAccountUpdateCacheMut.Lock() - kernelAccountUpdateCache[key] = cache - kernelAccountUpdateCacheMut.Unlock() - } - - return rowsAff, o.doAfterUpdateHooks(ctx, exec) -} - -// UpdateAll updates all rows with the specified column values. -func (q kernelAccountQuery) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { - queries.SetUpdate(q.Query, cols) - - result, err := q.Query.ExecContext(ctx, exec) - if err != nil { - return 0, errors.Wrap(err, "models: unable to update all for kernel_accounts") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "models: unable to retrieve rows affected for kernel_accounts") - } - - return rowsAff, nil -} - -// UpdateAll updates all rows with the specified column values, using an executor. -func (o KernelAccountSlice) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { - ln := int64(len(o)) - if ln == 0 { - return 0, nil - } - - if len(cols) == 0 { - return 0, errors.New("models: update all requires at least one column argument") - } - - colNames := make([]string, len(cols)) - args := make([]interface{}, len(cols)) - - i := 0 - for name, value := range cols { - colNames[i] = name - args[i] = value - i++ - } - - // Append all of the primary key values for each column - for _, obj := range o { - pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), kernelAccountPrimaryKeyMapping) - args = append(args, pkeyArgs...) - } - - sql := fmt.Sprintf("UPDATE \"identity_api\".\"kernel_accounts\" SET %s WHERE %s", - strmangle.SetParamNames("\"", "\"", 1, colNames), - strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), len(colNames)+1, kernelAccountPrimaryKeyColumns, len(o))) - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, sql) - fmt.Fprintln(writer, args...) - } - result, err := exec.ExecContext(ctx, sql, args...) - if err != nil { - return 0, errors.Wrap(err, "models: unable to update all in kernelAccount slice") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "models: unable to retrieve rows affected all in update all kernelAccount") - } - return rowsAff, nil -} - -// Upsert attempts an insert using an executor, and does an update or ignore on conflict. -// See boil.Columns documentation for how to properly use updateColumns and insertColumns. -func (o *KernelAccount) Upsert(ctx context.Context, exec boil.ContextExecutor, updateOnConflict bool, conflictColumns []string, updateColumns, insertColumns boil.Columns, opts ...UpsertOptionFunc) error { - if o == nil { - return errors.New("models: no kernel_accounts provided for upsert") - } - if !boil.TimestampsAreSkipped(ctx) { - currTime := time.Now().In(boil.GetLocation()) - - if o.CreatedAt.IsZero() { - o.CreatedAt = currTime - } - } - - if err := o.doBeforeUpsertHooks(ctx, exec); err != nil { - return err - } - - nzDefaults := queries.NonZeroDefaultSet(kernelAccountColumnsWithDefault, o) - - // Build cache key in-line uglily - mysql vs psql problems - buf := strmangle.GetBuffer() - if updateOnConflict { - buf.WriteByte('t') - } else { - buf.WriteByte('f') - } - buf.WriteByte('.') - for _, c := range conflictColumns { - buf.WriteString(c) - } - buf.WriteByte('.') - buf.WriteString(strconv.Itoa(updateColumns.Kind)) - for _, c := range updateColumns.Cols { - buf.WriteString(c) - } - buf.WriteByte('.') - buf.WriteString(strconv.Itoa(insertColumns.Kind)) - for _, c := range insertColumns.Cols { - buf.WriteString(c) - } - buf.WriteByte('.') - for _, c := range nzDefaults { - buf.WriteString(c) - } - key := buf.String() - strmangle.PutBuffer(buf) - - kernelAccountUpsertCacheMut.RLock() - cache, cached := kernelAccountUpsertCache[key] - kernelAccountUpsertCacheMut.RUnlock() - - var err error - - if !cached { - insert, _ := insertColumns.InsertColumnSet( - kernelAccountAllColumns, - kernelAccountColumnsWithDefault, - kernelAccountColumnsWithoutDefault, - nzDefaults, - ) - - update := updateColumns.UpdateColumnSet( - kernelAccountAllColumns, - kernelAccountPrimaryKeyColumns, - ) - - if updateOnConflict && len(update) == 0 { - return errors.New("models: unable to upsert kernel_accounts, could not build update column list") - } - - ret := strmangle.SetComplement(kernelAccountAllColumns, strmangle.SetIntersect(insert, update)) - - conflict := conflictColumns - if len(conflict) == 0 && updateOnConflict && len(update) != 0 { - if len(kernelAccountPrimaryKeyColumns) == 0 { - return errors.New("models: unable to upsert kernel_accounts, could not build conflict column list") - } - - conflict = make([]string, len(kernelAccountPrimaryKeyColumns)) - copy(conflict, kernelAccountPrimaryKeyColumns) - } - cache.query = buildUpsertQueryPostgres(dialect, "\"identity_api\".\"kernel_accounts\"", updateOnConflict, ret, update, conflict, insert, opts...) - - cache.valueMapping, err = queries.BindMapping(kernelAccountType, kernelAccountMapping, insert) - if err != nil { - return err - } - if len(ret) != 0 { - cache.retMapping, err = queries.BindMapping(kernelAccountType, kernelAccountMapping, ret) - if err != nil { - return err - } - } - } - - value := reflect.Indirect(reflect.ValueOf(o)) - vals := queries.ValuesFromMapping(value, cache.valueMapping) - var returns []interface{} - if len(cache.retMapping) != 0 { - returns = queries.PtrsFromMapping(value, cache.retMapping) - } - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, cache.query) - fmt.Fprintln(writer, vals) - } - if len(cache.retMapping) != 0 { - err = exec.QueryRowContext(ctx, cache.query, vals...).Scan(returns...) - if errors.Is(err, sql.ErrNoRows) { - err = nil // Postgres doesn't return anything when there's no update - } - } else { - _, err = exec.ExecContext(ctx, cache.query, vals...) - } - if err != nil { - return errors.Wrap(err, "models: unable to upsert kernel_accounts") - } - - if !cached { - kernelAccountUpsertCacheMut.Lock() - kernelAccountUpsertCache[key] = cache - kernelAccountUpsertCacheMut.Unlock() - } - - return o.doAfterUpsertHooks(ctx, exec) -} - -// Delete deletes a single KernelAccount record with an executor. -// Delete will match against the primary key column to find the record to delete. -func (o *KernelAccount) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) { - if o == nil { - return 0, errors.New("models: no KernelAccount provided for delete") - } - - if err := o.doBeforeDeleteHooks(ctx, exec); err != nil { - return 0, err - } - - args := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), kernelAccountPrimaryKeyMapping) - sql := "DELETE FROM \"identity_api\".\"kernel_accounts\" WHERE \"kernel\"=$1" - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, sql) - fmt.Fprintln(writer, args...) - } - result, err := exec.ExecContext(ctx, sql, args...) - if err != nil { - return 0, errors.Wrap(err, "models: unable to delete from kernel_accounts") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "models: failed to get rows affected by delete for kernel_accounts") - } - - if err := o.doAfterDeleteHooks(ctx, exec); err != nil { - return 0, err - } - - return rowsAff, nil -} - -// DeleteAll deletes all matching rows. -func (q kernelAccountQuery) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { - if q.Query == nil { - return 0, errors.New("models: no kernelAccountQuery provided for delete all") - } - - queries.SetDelete(q.Query) - - result, err := q.Query.ExecContext(ctx, exec) - if err != nil { - return 0, errors.Wrap(err, "models: unable to delete all from kernel_accounts") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for kernel_accounts") - } - - return rowsAff, nil -} - -// DeleteAll deletes all rows in the slice, using an executor. -func (o KernelAccountSlice) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { - if len(o) == 0 { - return 0, nil - } - - if len(kernelAccountBeforeDeleteHooks) != 0 { - for _, obj := range o { - if err := obj.doBeforeDeleteHooks(ctx, exec); err != nil { - return 0, err - } - } - } - - var args []interface{} - for _, obj := range o { - pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), kernelAccountPrimaryKeyMapping) - args = append(args, pkeyArgs...) - } - - sql := "DELETE FROM \"identity_api\".\"kernel_accounts\" WHERE " + - strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, kernelAccountPrimaryKeyColumns, len(o)) - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, sql) - fmt.Fprintln(writer, args) - } - result, err := exec.ExecContext(ctx, sql, args...) - if err != nil { - return 0, errors.Wrap(err, "models: unable to delete all from kernelAccount slice") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for kernel_accounts") - } - - if len(kernelAccountAfterDeleteHooks) != 0 { - for _, obj := range o { - if err := obj.doAfterDeleteHooks(ctx, exec); err != nil { - return 0, err - } - } - } - - return rowsAff, nil -} - -// Reload refetches the object from the database -// using the primary keys with an executor. -func (o *KernelAccount) Reload(ctx context.Context, exec boil.ContextExecutor) error { - ret, err := FindKernelAccount(ctx, exec, o.Kernel) - if err != nil { - return err - } - - *o = *ret - return nil -} - -// ReloadAll refetches every row with matching primary key column values -// and overwrites the original object slice with the newly updated slice. -func (o *KernelAccountSlice) ReloadAll(ctx context.Context, exec boil.ContextExecutor) error { - if o == nil || len(*o) == 0 { - return nil - } - - slice := KernelAccountSlice{} - var args []interface{} - for _, obj := range *o { - pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), kernelAccountPrimaryKeyMapping) - args = append(args, pkeyArgs...) - } - - sql := "SELECT \"identity_api\".\"kernel_accounts\".* FROM \"identity_api\".\"kernel_accounts\" WHERE " + - strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, kernelAccountPrimaryKeyColumns, len(*o)) - - q := queries.Raw(sql, args...) - - err := q.Bind(ctx, exec, &slice) - if err != nil { - return errors.Wrap(err, "models: unable to reload all in KernelAccountSlice") - } - - *o = slice - - return nil -} - -// KernelAccountExists checks if the KernelAccount row exists. -func KernelAccountExists(ctx context.Context, exec boil.ContextExecutor, kernel []byte) (bool, error) { - var exists bool - sql := "select exists(select 1 from \"identity_api\".\"kernel_accounts\" where \"kernel\"=$1 limit 1)" - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, sql) - fmt.Fprintln(writer, kernel) - } - row := exec.QueryRowContext(ctx, sql, kernel) - - err := row.Scan(&exists) - if err != nil { - return false, errors.Wrap(err, "models: unable to check if kernel_accounts exists") - } - - return exists, nil -} - -// Exists checks if the KernelAccount row exists. -func (o *KernelAccount) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) { - return KernelAccountExists(ctx, exec, o.Kernel) -} From 8f46f43ac1d4a38a107c6f4fd777b73d072c0ef2 Mon Sep 17 00:00:00 2001 From: Allyson-English Date: Tue, 23 Jul 2024 12:10:52 -0400 Subject: [PATCH 11/12] tests --- internal/repositories/account/account_test.go | 130 ++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 internal/repositories/account/account_test.go diff --git a/internal/repositories/account/account_test.go b/internal/repositories/account/account_test.go new file mode 100644 index 00000000..29c8fde6 --- /dev/null +++ b/internal/repositories/account/account_test.go @@ -0,0 +1,130 @@ +package account + +import ( + "context" + "fmt" + "slices" + "testing" + "time" + + gmodel "github.com/DIMO-Network/identity-api/graph/model" + "github.com/DIMO-Network/identity-api/internal/config" + test "github.com/DIMO-Network/identity-api/internal/helpers" + "github.com/DIMO-Network/identity-api/internal/repositories/base" + "github.com/DIMO-Network/identity-api/models" + "github.com/DIMO-Network/shared/db" + "github.com/ethereum/go-ethereum/common" + "github.com/rs/zerolog" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/suite" + "github.com/testcontainers/testcontainers-go/modules/postgres" + "github.com/volatiletech/sqlboiler/v4/boil" +) + +type AccountRepoTestSuite struct { + suite.Suite + ctx context.Context + pdb db.Store + container *postgres.PostgresContainer + repo *Repository + settings config.Settings +} + +func (o *AccountRepoTestSuite) SetupSuite() { + o.ctx = context.Background() + o.pdb, o.container = test.StartContainerDatabase(o.ctx, o.T(), "../../../migrations") + logger := zerolog.Nop() + o.repo = &Repository{base.NewRepository(o.pdb, o.settings, &logger)} +} + +// TearDownTest after each test truncate tables +func (s *AccountRepoTestSuite) TearDownTest() { + s.Require().NoError(s.container.Restore(s.ctx)) +} + +// TearDownSuite cleanup at end by terminating container +func (o *AccountRepoTestSuite) TearDownSuite() { + fmt.Printf("shutting down postgres at with session: %s \n", o.container.SessionID()) + + if err := o.container.Terminate(o.ctx); err != nil { + o.T().Fatal(err) + } +} + +// Test Runner +func TestAccountRepoTestSuite(t *testing.T) { + suite.Run(t, new(AccountRepoTestSuite)) +} + +func (o *AccountRepoTestSuite) Test_GetAccountBySigner() { + numKernels := 5 + createdAt := time.Now().UTC().Truncate(time.Second) + signerAdded := time.Now().UTC().Truncate(time.Second) + kernels := []common.Address{} + _, signer, err := test.GenerateWallet() + o.NoError(err) + for range numKernels { + _, kernel, err := test.GenerateWallet() + o.NoError(err) + kernels = append(kernels, *kernel) + k := models.Account{ + Signer: signer.Bytes(), + Kernel: kernel.Bytes(), + CreatedAt: createdAt, + SignerAdded: signerAdded, + } + if err := k.Insert(o.ctx, o.pdb.DBS().Writer, boil.Infer()); err != nil { + assert.NoError(o.T(), err) + } + } + + resp, err := o.repo.GetAccount(o.ctx, gmodel.AccountBy{ + Signer: signer, + }) + o.NoError(err) + + o.Equal(resp.Signer, *signer) + o.Equal(resp.Kernel[0].Signer.Address, *signer) + o.Equal(len(resp.Kernel), numKernels) + o.Equal(resp.Kernel[0].CreatedAt, createdAt) + o.Equal(resp.Kernel[0].Signer.SignerAdded, signerAdded) + for _, k := range resp.Kernel { + slices.Contains(kernels, k.Address) + } +} + +func (o *AccountRepoTestSuite) Test_GetAccountByKernel() { + numKernels := 5 + createdAt := time.Now().UTC().Truncate(time.Second) + signerAdded := time.Now().UTC().Truncate(time.Second) + kernels := []models.Account{} + _, signer, err := test.GenerateWallet() + o.NoError(err) + for range numKernels { + _, kernel, err := test.GenerateWallet() + o.NoError(err) + k := models.Account{ + Signer: signer.Bytes(), + Kernel: kernel.Bytes(), + CreatedAt: createdAt, + SignerAdded: signerAdded, + } + kernels = append(kernels, k) + if err := k.Insert(o.ctx, o.pdb.DBS().Writer, boil.Infer()); err != nil { + assert.NoError(o.T(), err) + } + } + + kernelAddr := common.BytesToAddress(kernels[0].Kernel) + resp, err := o.repo.GetAccount(o.ctx, gmodel.AccountBy{ + Kernel: &kernelAddr, + }) + o.NoError(err) + + o.Equal(resp.Signer, *signer) + o.Equal(resp.Kernel[0].Signer.Address, *signer) + o.Equal(len(resp.Kernel), 1) + o.Equal(resp.Kernel[0].Address, kernelAddr) + o.Equal(resp.Kernel[0].CreatedAt, createdAt) + o.Equal(resp.Kernel[0].Signer.SignerAdded, signerAdded) +} From da26ddc66b938cad68aa1e25720d34f6fea3734e Mon Sep 17 00:00:00 2001 From: Allyson-English Date: Tue, 13 Aug 2024 09:53:26 -0400 Subject: [PATCH 12/12] dont return db error to user --- go.mod | 4 ++++ go.sum | 6 ++++++ internal/repositories/account/account.go | 7 ++++--- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 464e914c..ae3acae2 100644 --- a/go.mod +++ b/go.mod @@ -33,11 +33,14 @@ require ( require ( dario.cat/mergo v1.0.0 // indirect github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 // indirect + github.com/Khan/genqlient v0.7.0 // indirect github.com/Microsoft/go-winio v0.6.2 // indirect github.com/Microsoft/hcsshim v0.11.4 // indirect github.com/Shopify/sarama v1.38.1 // indirect github.com/StackExchange/wmi v1.2.1 // indirect github.com/agnivade/levenshtein v1.1.1 // indirect + github.com/alexflint/go-arg v1.4.2 // indirect + github.com/alexflint/go-scalar v1.0.0 // indirect github.com/andybalholm/brotli v1.1.0 // indirect github.com/avast/retry-go/v4 v4.5.1 // indirect github.com/aws/aws-sdk-go-v2 v1.25.0 // indirect @@ -149,6 +152,7 @@ require ( google.golang.org/genproto/googleapis/rpc v0.0.0-20240213162025-012b6fc9bca9 // indirect google.golang.org/grpc v1.61.1 // indirect google.golang.org/protobuf v1.34.1 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect rsc.io/tmplfunc v0.0.3 // indirect ) diff --git a/go.sum b/go.sum index 89446ea4..66234aea 100644 --- a/go.sum +++ b/go.sum @@ -78,6 +78,8 @@ github.com/DIMO-Network/shared v0.10.16/go.mod h1:LDNCMzOGA+MqXtHbvRDFS/1kl8sHMQ github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= github.com/DataDog/zstd v1.4.5 h1:EndNeuB0l9syBZhut0wns3gV1hL8zX8LIu6ZiVHWLIQ= github.com/DataDog/zstd v1.4.5/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= +github.com/Khan/genqlient v0.7.0 h1:GZ1meyRnzcDTK48EjqB8t3bcfYvHArCUUvgOwpz1D4w= +github.com/Khan/genqlient v0.7.0/go.mod h1:HNyy3wZvuYwmW3Y7mkoQLZsa/R5n5yIRajS1kPBvSFM= github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs= github.com/Masterminds/sprig/v3 v3.2.2/go.mod h1:UoaO7Yp8KlPnJIYWTFkMaqPUYKTfGFPhxNuwnnxkKlk= @@ -103,6 +105,10 @@ github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuy github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= +github.com/alexflint/go-arg v1.4.2 h1:lDWZAXxpAnZUq4qwb86p/3rIJJ2Li81EoMbTMujhVa0= +github.com/alexflint/go-arg v1.4.2/go.mod h1:9iRbDxne7LcR/GSvEr7ma++GLpdIU1zrghf2y2768kM= +github.com/alexflint/go-scalar v1.0.0 h1:NGupf1XV/Xb04wXskDFzS0KWOLH632W/EO4fAFi+A70= +github.com/alexflint/go-scalar v1.0.0/go.mod h1:GpHzbCOZXEKMEcygYQ5n/aa4Aq84zbxjy3MxYW0gjYw= github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ= github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M= diff --git a/internal/repositories/account/account.go b/internal/repositories/account/account.go index a386f7a8..3b7bae71 100644 --- a/internal/repositories/account/account.go +++ b/internal/repositories/account/account.go @@ -82,7 +82,8 @@ func (r *Repository) GetAccounts(ctx context.Context, first *int, after *string, accountCount, err := models.Accounts(queryMods...).Count(ctx, r.PDB.DBS().Reader) if err != nil { - return nil, err + r.Log.Err(err).Msg("failed fetching accounts") + return nil, fmt.Errorf("failed fetching accounts") } orderBy := " DESC" @@ -117,8 +118,8 @@ func (r *Repository) GetAccounts(ctx context.Context, first *int, after *string, all, err := models.Accounts(queryMods...).All(ctx, r.PDB.DBS().Reader) if err != nil { - r.Log.Err(err).Msg("failed fetching account") - return nil, fmt.Errorf("failed fetching account") + r.Log.Err(err).Msg("failed fetching accounts") + return nil, fmt.Errorf("failed fetching accounts") } hasNext := before != nil