diff --git a/core/chains/evm/config/chain_scoped.go b/core/chains/evm/config/chain_scoped.go index b2046559b0d..7971a18d4db 100644 --- a/core/chains/evm/config/chain_scoped.go +++ b/core/chains/evm/config/chain_scoped.go @@ -15,9 +15,9 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/logger" ) -func NewTOMLChainScopedConfig(genCfg gencfg.AppConfig, tomlConfig *toml.EVMConfig, lggr logger.Logger) *ChainScoped { +func NewTOMLChainScopedConfig(appCfg gencfg.AppConfig, tomlConfig *toml.EVMConfig, lggr logger.Logger) *ChainScoped { return &ChainScoped{ - AppConfig: genCfg, + AppConfig: appCfg, evmConfig: &evmConfig{c: tomlConfig}, lggr: lggr} } diff --git a/core/chains/evm/forwarders/orm.go b/core/chains/evm/forwarders/orm.go index 594d4d442b2..287698d22f6 100644 --- a/core/chains/evm/forwarders/orm.go +++ b/core/chains/evm/forwarders/orm.go @@ -34,7 +34,7 @@ func NewORM(db *sqlx.DB, lggr logger.Logger, cfg pg.QConfig) *orm { // CreateForwarder creates the Forwarder address associated with the current EVM chain id. func (o *orm) CreateForwarder(addr common.Address, evmChainId utils.Big) (fwd Forwarder, err error) { - sql := `INSERT INTO evm_forwarders (address, evm_chain_id, created_at, updated_at) VALUES ($1, $2, now(), now()) RETURNING *` + sql := `INSERT INTO evm.forwarders (address, evm_chain_id, created_at, updated_at) VALUES ($1, $2, now(), now()) RETURNING *` err = o.q.Get(&fwd, sql, addr, evmChainId) return fwd, err } @@ -50,7 +50,7 @@ func (o *orm) DeleteForwarder(id int64, cleanup func(tx pg.Queryer, evmChainID i var rowsAffected int64 err = o.q.Transaction(func(tx pg.Queryer) error { - err = tx.Get(&dest, `SELECT evm_chain_id, address FROM evm_forwarders WHERE id = $1`, id) + err = tx.Get(&dest, `SELECT evm_chain_id, address FROM evm.forwarders WHERE id = $1`, id) if err != nil { return err } @@ -60,7 +60,7 @@ func (o *orm) DeleteForwarder(id int64, cleanup func(tx pg.Queryer, evmChainID i } } - result, err2 := o.q.Exec(`DELETE FROM evm_forwarders WHERE id = $1`, id) + result, err2 := o.q.Exec(`DELETE FROM evm.forwarders WHERE id = $1`, id) // If the forwarder wasn't found, we still want to delete the filter. // In that case, the transaction must return nil, even though DeleteForwarder // will return sql.ErrNoRows @@ -80,12 +80,12 @@ func (o *orm) DeleteForwarder(id int64, cleanup func(tx pg.Queryer, evmChainID i // FindForwarders returns all forwarder addresses from offset up until limit. func (o *orm) FindForwarders(offset, limit int) (fwds []Forwarder, count int, err error) { - sql := `SELECT count(*) FROM evm_forwarders` + sql := `SELECT count(*) FROM evm.forwarders` if err = o.q.Get(&count, sql); err != nil { return } - sql = `SELECT * FROM evm_forwarders ORDER BY created_at DESC, id DESC LIMIT $1 OFFSET $2` + sql = `SELECT * FROM evm.forwarders ORDER BY created_at DESC, id DESC LIMIT $1 OFFSET $2` if err = o.q.Select(&fwds, sql, limit, offset); err != nil { return } @@ -94,7 +94,7 @@ func (o *orm) FindForwarders(offset, limit int) (fwds []Forwarder, count int, er // FindForwardersByChain returns all forwarder addresses for a chain. func (o *orm) FindForwardersByChain(evmChainId utils.Big) (fwds []Forwarder, err error) { - sql := `SELECT * FROM evm_forwarders where evm_chain_id = $1 ORDER BY created_at DESC, id DESC` + sql := `SELECT * FROM evm.forwarders where evm_chain_id = $1 ORDER BY created_at DESC, id DESC` err = o.q.Select(&fwds, sql, evmChainId) return } @@ -108,7 +108,7 @@ func (o *orm) FindForwardersInListByChain(evmChainId utils.Big, addrs []common.A } query, args, err := sqlx.Named(` - SELECT * FROM evm_forwarders + SELECT * FROM evm.forwarders WHERE evm_chain_id = :chainid AND address IN (:addresses) ORDER BY created_at DESC, id DESC`, diff --git a/core/chains/evm/headtracker/head_tracker_test.go b/core/chains/evm/headtracker/head_tracker_test.go index cf8399ceeda..12fcb195310 100644 --- a/core/chains/evm/headtracker/head_tracker_test.go +++ b/core/chains/evm/headtracker/head_tracker_test.go @@ -38,7 +38,7 @@ import ( ) func firstHead(t *testing.T, db *sqlx.DB) (h evmtypes.Head) { - if err := db.Get(&h, `SELECT * FROM evm_heads ORDER BY number ASC LIMIT 1`); err != nil { + if err := db.Get(&h, `SELECT * FROM evm.heads ORDER BY number ASC LIMIT 1`); err != nil { t.Fatal(err) } return h diff --git a/core/chains/evm/headtracker/orm.go b/core/chains/evm/headtracker/orm.go index 02747752148..426df68b301 100644 --- a/core/chains/evm/headtracker/orm.go +++ b/core/chains/evm/headtracker/orm.go @@ -43,7 +43,7 @@ func (orm *orm) IdempotentInsertHead(ctx context.Context, head *evmtypes.Head) e // listener guarantees head.EVMChainID to be equal to orm.chainID q := orm.q.WithOpts(pg.WithParentCtx(ctx)) query := ` - INSERT INTO evm_heads (hash, number, parent_hash, created_at, timestamp, l1_block_number, evm_chain_id, base_fee_per_gas) VALUES ( + INSERT INTO evm.heads (hash, number, parent_hash, created_at, timestamp, l1_block_number, evm_chain_id, base_fee_per_gas) VALUES ( :hash, :number, :parent_hash, :created_at, :timestamp, :l1_block_number, :evm_chain_id, :base_fee_per_gas) ON CONFLICT (evm_chain_id, hash) DO NOTHING` err := q.ExecQNamed(query, head) @@ -53,11 +53,11 @@ func (orm *orm) IdempotentInsertHead(ctx context.Context, head *evmtypes.Head) e func (orm *orm) TrimOldHeads(ctx context.Context, n uint) (err error) { q := orm.q.WithOpts(pg.WithParentCtx(ctx)) return q.ExecQ(` - DELETE FROM evm_heads + DELETE FROM evm.heads WHERE evm_chain_id = $1 AND number < ( SELECT min(number) FROM ( SELECT number - FROM evm_heads + FROM evm.heads WHERE evm_chain_id = $1 ORDER BY number DESC LIMIT $2 @@ -68,7 +68,7 @@ func (orm *orm) TrimOldHeads(ctx context.Context, n uint) (err error) { func (orm *orm) LatestHead(ctx context.Context) (head *evmtypes.Head, err error) { head = new(evmtypes.Head) q := orm.q.WithOpts(pg.WithParentCtx(ctx)) - err = q.Get(head, `SELECT * FROM evm_heads WHERE evm_chain_id = $1 ORDER BY number DESC, created_at DESC, id DESC LIMIT 1`, orm.chainID) + err = q.Get(head, `SELECT * FROM evm.heads WHERE evm_chain_id = $1 ORDER BY number DESC, created_at DESC, id DESC LIMIT 1`, orm.chainID) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -78,7 +78,7 @@ func (orm *orm) LatestHead(ctx context.Context) (head *evmtypes.Head, err error) func (orm *orm) LatestHeads(ctx context.Context, limit uint) (heads []*evmtypes.Head, err error) { q := orm.q.WithOpts(pg.WithParentCtx(ctx)) - err = q.Select(&heads, `SELECT * FROM evm_heads WHERE evm_chain_id = $1 ORDER BY number DESC, created_at DESC, id DESC LIMIT $2`, orm.chainID, limit) + err = q.Select(&heads, `SELECT * FROM evm.heads WHERE evm_chain_id = $1 ORDER BY number DESC, created_at DESC, id DESC LIMIT $2`, orm.chainID, limit) err = errors.Wrap(err, "LatestHeads failed") return } @@ -86,7 +86,7 @@ func (orm *orm) LatestHeads(ctx context.Context, limit uint) (heads []*evmtypes. func (orm *orm) HeadByHash(ctx context.Context, hash common.Hash) (head *evmtypes.Head, err error) { q := orm.q.WithOpts(pg.WithParentCtx(ctx)) head = new(evmtypes.Head) - err = q.Get(head, `SELECT * FROM evm_heads WHERE evm_chain_id = $1 AND hash = $2`, orm.chainID, hash) + err = q.Get(head, `SELECT * FROM evm.heads WHERE evm_chain_id = $1 AND hash = $2`, orm.chainID, hash) if errors.Is(err, sql.ErrNoRows) { return nil, nil } diff --git a/core/chains/evm/logpoller/log_poller.go b/core/chains/evm/logpoller/log_poller.go index e4ad8dcdfaa..227688fce16 100644 --- a/core/chains/evm/logpoller/log_poller.go +++ b/core/chains/evm/logpoller/log_poller.go @@ -743,7 +743,7 @@ func (lp *logPoller) getCurrentBlockMaybeHandleReorg(ctx context.Context, curren // that applications see them and take action upon it, however that // results in significantly slower reads since we must then compute // the canonical set per read. Typically, if an application took action on a log - // it would be saved elsewhere e.g. eth_txes, so it seems better to just support the fast reads. + // it would be saved elsewhere e.g. evm.txes, so it seems better to just support the fast reads. // Its also nicely analogous to reading from the chain itself. err2 = lp.orm.q.WithOpts(pg.WithParentCtx(ctx)).Transaction(func(tx pg.Queryer) error { // These deletes are bounded by reorg depth, so they are diff --git a/core/chains/evm/logpoller/orm.go b/core/chains/evm/logpoller/orm.go index 08a4d558fbf..3c678aeed36 100644 --- a/core/chains/evm/logpoller/orm.go +++ b/core/chains/evm/logpoller/orm.go @@ -34,7 +34,7 @@ func NewORM(chainID *big.Int, db *sqlx.DB, lggr logger.Logger, cfg pg.QConfig) * // InsertBlock is idempotent to support replays. func (o *ORM) InsertBlock(h common.Hash, n int64, t time.Time, qopts ...pg.QOpt) error { q := o.q.WithOpts(qopts...) - err := q.ExecQ(`INSERT INTO evm_log_poller_blocks (evm_chain_id, block_hash, block_number, block_timestamp, created_at) + err := q.ExecQ(`INSERT INTO evm.log_poller_blocks (evm_chain_id, block_hash, block_number, block_timestamp, created_at) VALUES ($1, $2, $3, $4, NOW()) ON CONFLICT DO NOTHING`, utils.NewBig(o.chainID), h[:], n, t) return err } @@ -54,7 +54,7 @@ func (o *ORM) InsertFilter(filter Filter, qopts ...pg.QOpt) (err error) { for _, ev := range filter.EventSigs { events = append(events, ev.Bytes()) } - return q.ExecQ(`INSERT INTO evm_log_poller_filters + return q.ExecQ(`INSERT INTO evm.log_poller_filters (name, evm_chain_id, retention, created_at, address, event) SELECT * FROM (SELECT $1, $2::NUMERIC, $3::BIGINT, NOW()) x, @@ -67,7 +67,7 @@ func (o *ORM) InsertFilter(filter Filter, qopts ...pg.QOpt) (err error) { // DeleteFilter removes all events,address pairs associated with the Filter func (o *ORM) DeleteFilter(name string, qopts ...pg.QOpt) error { q := o.q.WithOpts(qopts...) - return q.ExecQ(`DELETE FROM evm_log_poller_filters WHERE name = $1 AND evm_chain_id = $2`, name, utils.NewBig(o.chainID)) + return q.ExecQ(`DELETE FROM evm.log_poller_filters WHERE name = $1 AND evm_chain_id = $2`, name, utils.NewBig(o.chainID)) } // LoadFiltersForChain returns all filters for this chain @@ -78,7 +78,7 @@ func (o *ORM) LoadFilters(qopts ...pg.QOpt) (map[string]Filter, error) { ARRAY_AGG(DISTINCT address)::BYTEA[] AS addresses, ARRAY_AGG(DISTINCT event)::BYTEA[] AS event_sigs, MAX(retention) AS retention - FROM evm_log_poller_filters WHERE evm_chain_id = $1 + FROM evm.log_poller_filters WHERE evm_chain_id = $1 GROUP BY name`, utils.NewBig(o.chainID)) filters := make(map[string]Filter) for _, filter := range rows { @@ -91,7 +91,7 @@ func (o *ORM) LoadFilters(qopts ...pg.QOpt) (map[string]Filter, error) { func (o *ORM) SelectBlockByHash(h common.Hash, qopts ...pg.QOpt) (*LogPollerBlock, error) { q := o.q.WithOpts(qopts...) var b LogPollerBlock - if err := q.Get(&b, `SELECT * FROM evm_log_poller_blocks WHERE block_hash = $1 AND evm_chain_id = $2`, h, utils.NewBig(o.chainID)); err != nil { + if err := q.Get(&b, `SELECT * FROM evm.log_poller_blocks WHERE block_hash = $1 AND evm_chain_id = $2`, h, utils.NewBig(o.chainID)); err != nil { return nil, err } return &b, nil @@ -100,7 +100,7 @@ func (o *ORM) SelectBlockByHash(h common.Hash, qopts ...pg.QOpt) (*LogPollerBloc func (o *ORM) SelectBlockByNumber(n int64, qopts ...pg.QOpt) (*LogPollerBlock, error) { q := o.q.WithOpts(qopts...) var b LogPollerBlock - if err := q.Get(&b, `SELECT * FROM evm_log_poller_blocks WHERE block_number = $1 AND evm_chain_id = $2`, n, utils.NewBig(o.chainID)); err != nil { + if err := q.Get(&b, `SELECT * FROM evm.log_poller_blocks WHERE block_number = $1 AND evm_chain_id = $2`, n, utils.NewBig(o.chainID)); err != nil { return nil, err } return &b, nil @@ -109,7 +109,7 @@ func (o *ORM) SelectBlockByNumber(n int64, qopts ...pg.QOpt) (*LogPollerBlock, e func (o *ORM) SelectLatestBlock(qopts ...pg.QOpt) (*LogPollerBlock, error) { q := o.q.WithOpts(qopts...) var b LogPollerBlock - if err := q.Get(&b, `SELECT * FROM evm_log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1`, utils.NewBig(o.chainID)); err != nil { + if err := q.Get(&b, `SELECT * FROM evm.log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1`, utils.NewBig(o.chainID)); err != nil { return nil, err } return &b, nil @@ -118,11 +118,11 @@ func (o *ORM) SelectLatestBlock(qopts ...pg.QOpt) (*LogPollerBlock, error) { func (o *ORM) SelectLatestLogEventSigWithConfs(eventSig common.Hash, address common.Address, confs int, qopts ...pg.QOpt) (*Log, error) { q := o.q.WithOpts(qopts...) var l Log - if err := q.Get(&l, `SELECT * FROM evm_logs + if err := q.Get(&l, `SELECT * FROM evm.logs WHERE evm_chain_id = $1 AND event_sig = $2 AND address = $3 - AND (block_number + $4) <= (SELECT COALESCE(block_number, 0) FROM evm_log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) + AND (block_number + $4) <= (SELECT COALESCE(block_number, 0) FROM evm.log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) ORDER BY (block_number, log_index) DESC LIMIT 1`, utils.NewBig(o.chainID), eventSig, address, confs); err != nil { return nil, err } @@ -132,19 +132,19 @@ func (o *ORM) SelectLatestLogEventSigWithConfs(eventSig common.Hash, address com // DeleteBlocksAfter delete all blocks after and including start. func (o *ORM) DeleteBlocksAfter(start int64, qopts ...pg.QOpt) error { q := o.q.WithOpts(qopts...) - return q.ExecQ(`DELETE FROM evm_log_poller_blocks WHERE block_number >= $1 AND evm_chain_id = $2`, start, utils.NewBig(o.chainID)) + return q.ExecQ(`DELETE FROM evm.log_poller_blocks WHERE block_number >= $1 AND evm_chain_id = $2`, start, utils.NewBig(o.chainID)) } // DeleteBlocksBefore delete all blocks before and including end. func (o *ORM) DeleteBlocksBefore(end int64, qopts ...pg.QOpt) error { q := o.q.WithOpts(qopts...) - _, err := q.Exec(`DELETE FROM evm_log_poller_blocks WHERE block_number <= $1 AND evm_chain_id = $2`, end, utils.NewBig(o.chainID)) + _, err := q.Exec(`DELETE FROM evm.log_poller_blocks WHERE block_number <= $1 AND evm_chain_id = $2`, end, utils.NewBig(o.chainID)) return err } func (o *ORM) DeleteLogsAfter(start int64, qopts ...pg.QOpt) error { q := o.q.WithOpts(qopts...) - return q.ExecQ(`DELETE FROM evm_logs WHERE block_number >= $1 AND evm_chain_id = $2`, start, utils.NewBig(o.chainID)) + return q.ExecQ(`DELETE FROM evm.logs WHERE block_number >= $1 AND evm_chain_id = $2`, start, utils.NewBig(o.chainID)) } type Exp struct { @@ -161,9 +161,9 @@ func (o *ORM) DeleteExpiredLogs(qopts ...pg.QOpt) error { return q.ExecQ(`WITH r AS ( SELECT address, event, MAX(retention) AS retention - FROM evm_log_poller_filters WHERE evm_chain_id=$1 + FROM evm.log_poller_filters WHERE evm_chain_id=$1 GROUP BY evm_chain_id,address, event HAVING NOT 0 = ANY(ARRAY_AGG(retention)) - ) DELETE FROM evm_logs l USING r + ) DELETE FROM evm.logs l USING r WHERE l.evm_chain_id = $1 AND l.address=r.address AND l.event_sig=r.event AND l.created_at <= STATEMENT_TIMESTAMP() - (r.retention / 10^9 * interval '1 second')`, // retention is in nanoseconds (time.Duration aka BIGINT) utils.NewBig(o.chainID)) @@ -185,7 +185,7 @@ func (o *ORM) InsertLogs(logs []Log, qopts ...pg.QOpt) error { end = len(logs) } - err := q.ExecQNamed(`INSERT INTO evm_logs + err := q.ExecQNamed(`INSERT INTO evm.logs (evm_chain_id, log_index, block_hash, block_number, block_timestamp, address, event_sig, topics, tx_hash, data, created_at) VALUES (:evm_chain_id, :log_index, :block_hash, :block_number, :block_timestamp, :address, :event_sig, :topics, :tx_hash, :data, NOW()) ON CONFLICT DO NOTHING`, logs[start:end]) @@ -206,7 +206,7 @@ func (o *ORM) InsertLogs(logs []Log, qopts ...pg.QOpt) error { func (o *ORM) SelectLogsByBlockRange(start, end int64) ([]Log, error) { var logs []Log err := o.q.Select(&logs, ` - SELECT * FROM evm_logs + SELECT * FROM evm.logs WHERE block_number >= $1 AND block_number <= $2 AND evm_chain_id = $3 ORDER BY (block_number, log_index, created_at)`, start, end, utils.NewBig(o.chainID)) if err != nil { @@ -220,10 +220,10 @@ func (o *ORM) SelectLogsByBlockRangeFilter(start, end int64, address common.Addr var logs []Log q := o.q.WithOpts(qopts...) err := q.Select(&logs, ` - SELECT * FROM evm_logs - WHERE evm_logs.block_number >= $1 AND evm_logs.block_number <= $2 AND evm_logs.evm_chain_id = $3 + SELECT * FROM evm.logs + WHERE evm.logs.block_number >= $1 AND evm.logs.block_number <= $2 AND evm.logs.evm_chain_id = $3 AND address = $4 AND event_sig = $5 - ORDER BY (evm_logs.block_number, evm_logs.log_index)`, start, end, utils.NewBig(o.chainID), address, eventSig.Bytes()) + ORDER BY (evm.logs.block_number, evm.logs.log_index)`, start, end, utils.NewBig(o.chainID), address, eventSig.Bytes()) if err != nil { return nil, err } @@ -235,12 +235,12 @@ func (o *ORM) SelectLogsCreatedAfter(eventSig []byte, address common.Address, af var logs []Log q := o.q.WithOpts(qopts...) err := q.Select(&logs, ` - SELECT * FROM evm_logs + SELECT * FROM evm.logs WHERE evm_chain_id = $1 AND address = $2 AND event_sig = $3 AND created_at > $4 - AND (block_number + $5) <= (SELECT COALESCE(block_number, 0) FROM evm_log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) + AND (block_number + $5) <= (SELECT COALESCE(block_number, 0) FROM evm.log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) ORDER BY created_at ASC`, utils.NewBig(o.chainID), address, eventSig, after, confs) if err != nil { return nil, err @@ -267,12 +267,12 @@ func (o *ORM) SelectLogsWithSigsByBlockRangeFilter(start, end int64, address com ` SELECT * -FROM evm_logs -WHERE evm_logs.block_number BETWEEN :start AND :end - AND evm_logs.evm_chain_id = :chainid - AND evm_logs.address = :address - AND evm_logs.event_sig IN (:EventSigs) -ORDER BY (evm_logs.block_number, evm_logs.log_index)`, a) +FROM evm.logs +WHERE evm.logs.block_number BETWEEN :start AND :end + AND evm.logs.evm_chain_id = :chainid + AND evm.logs.address = :address + AND evm.logs.event_sig IN (:EventSigs) +ORDER BY (evm.logs.block_number, evm.logs.log_index)`, a) if err != nil { return nil, errors.Wrap(err, "sqlx Named") } @@ -292,7 +292,7 @@ func (o *ORM) GetBlocksRange(start uint64, end uint64, qopts ...pg.QOpt) ([]LogP var blocks []LogPollerBlock q := o.q.WithOpts(qopts...) err := q.Select(&blocks, ` - SELECT * FROM evm_log_poller_blocks + SELECT * FROM evm.log_poller_blocks WHERE block_number >= $1 AND block_number <= $2 AND evm_chain_id = $3 ORDER BY block_number ASC`, start, end, utils.NewBig(o.chainID)) if err != nil { @@ -309,13 +309,13 @@ func (o *ORM) SelectLatestLogEventSigsAddrsWithConfs(fromBlock int64, addresses q := o.q.WithOpts(qopts...) err := q.Select(&logs, ` - SELECT * FROM evm_logs WHERE (block_number, address, event_sig) IN ( - SELECT MAX(block_number), address, event_sig FROM evm_logs + SELECT * FROM evm.logs WHERE (block_number, address, event_sig) IN ( + SELECT MAX(block_number), address, event_sig FROM evm.logs WHERE evm_chain_id = $1 AND event_sig = ANY($2) AND address = ANY($3) AND block_number > $4 AND - block_number <= (SELECT COALESCE(block_number, 0) FROM evm_log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) - $5 + block_number <= (SELECT COALESCE(block_number, 0) FROM evm.log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) - $5 GROUP BY event_sig, address ) ORDER BY block_number ASC @@ -334,12 +334,12 @@ func (o *ORM) SelectLatestBlockNumberEventSigsAddrsWithConfs(fromBlock int64, ev q := o.q.WithOpts(qopts...) err := q.Get(&blockNumber, ` - SELECT COALESCE(MAX(block_number), 0) FROM evm_logs + SELECT COALESCE(MAX(block_number), 0) FROM evm.logs WHERE evm_chain_id = $1 AND event_sig = ANY($2) AND address = ANY($3) AND block_number > $4 AND - block_number <= (SELECT COALESCE(block_number, 0) FROM evm_log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) - $5`, + block_number <= (SELECT COALESCE(block_number, 0) FROM evm.log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) - $5`, o.chainID.Int64(), sigs, addrs, fromBlock, confs) if err != nil { return 0, err @@ -351,13 +351,13 @@ func (o *ORM) SelectDataWordRange(address common.Address, eventSig common.Hash, var logs []Log q := o.q.WithOpts(qopts...) err := q.Select(&logs, - `SELECT * FROM evm_logs - WHERE evm_logs.evm_chain_id = $1 + `SELECT * FROM evm.logs + WHERE evm.logs.evm_chain_id = $1 AND address = $2 AND event_sig = $3 AND substring(data from 32*$4+1 for 32) >= $5 AND substring(data from 32*$4+1 for 32) <= $6 - AND block_number <= (SELECT COALESCE(block_number, 0) FROM evm_log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) - $7 - ORDER BY (evm_logs.block_number, evm_logs.log_index)`, utils.NewBig(o.chainID), address, eventSig.Bytes(), wordIndex, wordValueMin.Bytes(), wordValueMax.Bytes(), confs) + AND block_number <= (SELECT COALESCE(block_number, 0) FROM evm.log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) - $7 + ORDER BY (evm.logs.block_number, evm.logs.log_index)`, utils.NewBig(o.chainID), address, eventSig.Bytes(), wordIndex, wordValueMin.Bytes(), wordValueMax.Bytes(), confs) if err != nil { return nil, err } @@ -368,12 +368,12 @@ func (o *ORM) SelectDataWordGreaterThan(address common.Address, eventSig common. var logs []Log q := o.q.WithOpts(qopts...) err := q.Select(&logs, - `SELECT * FROM evm_logs - WHERE evm_logs.evm_chain_id = $1 + `SELECT * FROM evm.logs + WHERE evm.logs.evm_chain_id = $1 AND address = $2 AND event_sig = $3 AND substring(data from 32*$4+1 for 32) >= $5 - AND block_number <= (SELECT COALESCE(block_number, 0) FROM evm_log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) - $6 - ORDER BY (evm_logs.block_number, evm_logs.log_index)`, utils.NewBig(o.chainID), address, eventSig.Bytes(), wordIndex, wordValueMin.Bytes(), confs) + AND block_number <= (SELECT COALESCE(block_number, 0) FROM evm.log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) - $6 + ORDER BY (evm.logs.block_number, evm.logs.log_index)`, utils.NewBig(o.chainID), address, eventSig.Bytes(), wordIndex, wordValueMin.Bytes(), confs) if err != nil { return nil, err } @@ -388,12 +388,12 @@ func (o *ORM) SelectIndexLogsTopicGreaterThan(address common.Address, eventSig c var logs []Log q := o.q.WithOpts(qopts...) err := q.Select(&logs, - `SELECT * FROM evm_logs - WHERE evm_logs.evm_chain_id = $1 + `SELECT * FROM evm.logs + WHERE evm.logs.evm_chain_id = $1 AND address = $2 AND event_sig = $3 AND topics[$4] >= $5 - AND block_number <= (SELECT COALESCE(block_number, 0) FROM evm_log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) - $6 - ORDER BY (evm_logs.block_number, evm_logs.log_index)`, utils.NewBig(o.chainID), address, eventSig.Bytes(), topicIndex+1, topicValueMin.Bytes(), confs) + AND block_number <= (SELECT COALESCE(block_number, 0) FROM evm.log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) - $6 + ORDER BY (evm.logs.block_number, evm.logs.log_index)`, utils.NewBig(o.chainID), address, eventSig.Bytes(), topicIndex+1, topicValueMin.Bytes(), confs) if err != nil { return nil, err } @@ -408,13 +408,13 @@ func (o *ORM) SelectIndexLogsTopicRange(address common.Address, eventSig common. var logs []Log q := o.q.WithOpts(qopts...) err := q.Select(&logs, - `SELECT * FROM evm_logs - WHERE evm_logs.evm_chain_id = $1 + `SELECT * FROM evm.logs + WHERE evm.logs.evm_chain_id = $1 AND address = $2 AND event_sig = $3 AND topics[$4] >= $5 AND topics[$4] <= $6 - AND block_number <= (SELECT COALESCE(block_number, 0) FROM evm_log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) - $7 - ORDER BY (evm_logs.block_number, evm_logs.log_index)`, utils.NewBig(o.chainID), address, eventSig.Bytes(), topicIndex+1, topicValueMin.Bytes(), topicValueMax.Bytes(), confs) + AND block_number <= (SELECT COALESCE(block_number, 0) FROM evm.log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) - $7 + ORDER BY (evm.logs.block_number, evm.logs.log_index)`, utils.NewBig(o.chainID), address, eventSig.Bytes(), topicIndex+1, topicValueMin.Bytes(), topicValueMax.Bytes(), confs) if err != nil { return nil, err } @@ -431,12 +431,12 @@ func (o *ORM) SelectIndexedLogs(address common.Address, eventSig common.Hash, to topicValuesBytes := concatBytes(topicValues) // Add 1 since postgresql arrays are 1-indexed. err := q.Select(&logs, ` - SELECT * FROM evm_logs - WHERE evm_logs.evm_chain_id = $1 + SELECT * FROM evm.logs + WHERE evm.logs.evm_chain_id = $1 AND address = $2 AND event_sig = $3 AND topics[$4] = ANY($5) - AND block_number <= (SELECT COALESCE(block_number, 0) FROM evm_log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) - $6 - ORDER BY (evm_logs.block_number, evm_logs.log_index)`, utils.NewBig(o.chainID), address, eventSig.Bytes(), topicIndex+1, topicValuesBytes, confs) + AND block_number <= (SELECT COALESCE(block_number, 0) FROM evm.log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) - $6 + ORDER BY (evm.logs.block_number, evm.logs.log_index)`, utils.NewBig(o.chainID), address, eventSig.Bytes(), topicIndex+1, topicValuesBytes, confs) if err != nil { return nil, err } @@ -453,11 +453,11 @@ func (o *ORM) SelectIndexedLogsByBlockRangeFilter(start, end int64, address comm topicValuesBytes := concatBytes(topicValues) q := o.q.WithOpts(qopts...) err := q.Select(&logs, ` - SELECT * FROM evm_logs - WHERE evm_logs.block_number >= $1 AND evm_logs.block_number <= $2 AND evm_logs.evm_chain_id = $3 + SELECT * FROM evm.logs + WHERE evm.logs.block_number >= $1 AND evm.logs.block_number <= $2 AND evm.logs.evm_chain_id = $3 AND address = $4 AND event_sig = $5 AND topics[$6] = ANY($7) - ORDER BY (evm_logs.block_number, evm_logs.log_index)`, start, end, utils.NewBig(o.chainID), address, eventSig.Bytes(), topicIndex+1, topicValuesBytes) + ORDER BY (evm.logs.block_number, evm.logs.log_index)`, start, end, utils.NewBig(o.chainID), address, eventSig.Bytes(), topicIndex+1, topicValuesBytes) if err != nil { return nil, err } @@ -478,12 +478,12 @@ func (o *ORM) SelectIndexedLogsCreatedAfter(address common.Address, eventSig com topicValuesBytes := concatBytes(topicValues) // Add 1 since postgresql arrays are 1-indexed. err := q.Select(&logs, ` - SELECT * FROM evm_logs - WHERE evm_logs.evm_chain_id = $1 + SELECT * FROM evm.logs + WHERE evm.logs.evm_chain_id = $1 AND address = $2 AND event_sig = $3 AND topics[$4] = ANY($5) AND created_at > $6 - AND block_number <= (SELECT COALESCE(block_number, 0) FROM evm_log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) - $7 + AND block_number <= (SELECT COALESCE(block_number, 0) FROM evm.log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) - $7 ORDER BY created_at ASC`, utils.NewBig(o.chainID), address, eventSig.Bytes(), topicIndex+1, topicValuesBytes, after, confs) if err != nil { return nil, err @@ -502,25 +502,25 @@ func (o *ORM) SelectIndexedLogsWithSigsExcluding(sigA, sigB common.Hash, topicIn err := q.Select(&logs, ` SELECT * - FROM evm_logs + FROM evm.logs WHERE evm_chain_id = $1 AND address = $2 AND event_sig = $3 AND block_number BETWEEN $6 AND $7 - AND block_number <= (SELECT COALESCE(block_number, 0) FROM evm_log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) - $8 + AND block_number <= (SELECT COALESCE(block_number, 0) FROM evm.log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) - $8 EXCEPT SELECT a.* - FROM evm_logs AS a - INNER JOIN evm_logs B + FROM evm.logs AS a + INNER JOIN evm.logs B ON a.evm_chain_id = b.evm_chain_id AND a.address = b.address AND a.topics[$5] = b.topics[$5] AND a.event_sig = $3 AND b.event_sig = $4 AND b.block_number BETWEEN $6 AND $7 - AND b.block_number <= (SELECT COALESCE(block_number, 0) FROM evm_log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) - $8 + AND b.block_number <= (SELECT COALESCE(block_number, 0) FROM evm.log_poller_blocks WHERE evm_chain_id = $1 ORDER BY block_number DESC LIMIT 1) - $8 ORDER BY block_number,log_index ASC `, utils.NewBig(o.chainID), address, sigA.Bytes(), sigB.Bytes(), topicIndex+1, startBlock, endBlock, confs) diff --git a/core/chains/evm/txmgr/broadcaster_test.go b/core/chains/evm/txmgr/broadcaster_test.go index 2e665bc3c8f..aa0368ecc09 100644 --- a/core/chains/evm/txmgr/broadcaster_test.go +++ b/core/chains/evm/txmgr/broadcaster_test.go @@ -618,7 +618,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_OptimisticLockingOnEthTx(t *testi } // Simulate a "PruneQueue" call - assert.NoError(t, utils.JustError(db.Exec(`DELETE FROM eth_txes WHERE state = 'unstarted'`))) + assert.NoError(t, utils.JustError(db.Exec(`DELETE FROM evm.txes WHERE state = 'unstarted'`))) close(chBlock) }() @@ -729,7 +729,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_ResumingFromCrash(t *testing.T) { eb := NewTestEthBroadcaster(t, txStore, ethClient, ethKeyStore, evmcfg, &testCheckerFactory{}, false) // Crashed right after we commit the database transaction that saved - // the nonce to the eth_tx so evm_key_states.next_nonce has not been + // the nonce to the eth_tx so evm.key_states.next_nonce has not been // incremented yet inProgressEthTx := cltest.MustInsertInProgressEthTxWithAttempt(t, txStore, firstNonce, fromAddress) @@ -1009,7 +1009,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_Errors(t *testing.T) { // We assume success and hand off to eth confirmer to eventually mark it as failed var latestID int64 var etx1 txmgr.Tx - require.NoError(t, db.Get(&latestID, "SELECT max(id) FROM eth_txes")) + require.NoError(t, db.Get(&latestID, "SELECT max(id) FROM evm.txes")) etx1, err = txStore.FindTxWithAttempts(latestID) require.NoError(t, err) require.NotNil(t, etx1.BroadcastAt) @@ -1056,7 +1056,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_Errors(t *testing.T) { // Check that the key had its nonce reset var nonce int64 - err := db.Get(&nonce, `SELECT next_nonce FROM evm_key_states WHERE address = $1 ORDER BY created_at ASC, id ASC`, fromAddress) + err = db.Get(&nonce, `SELECT next_nonce FROM evm.key_states WHERE address = $1 ORDER BY created_at ASC, id ASC`, fromAddress) require.NoError(t, err) // Saved NextNonce must be the same as before because this transaction // was not accepted by the eth node and never can be @@ -1126,7 +1126,6 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_Errors(t *testing.T) { estimator := gas.NewWrappedEvmEstimator(gas.NewFixedPriceEstimator(evmcfg.EVM().GasEstimator(), evmcfg.EVM().GasEstimator().BlockHistory(), lggr), evmcfg.EVM().GasEstimator().EIP1559DynamicFees()) txBuilder := txmgr.NewEvmTxAttemptBuilder(*ethClient.ConfiguredChainID(), evmcfg.EVM().GasEstimator(), ethKeyStore, estimator) eb = txmgr.NewEvmBroadcaster(txStore, txmgr.NewEvmTxmClient(ethClient), txmgr.NewEvmTxmConfig(evmcfg.EVM()), txmgr.NewEvmTxmFeeConfig(evmcfg.EVM().GasEstimator()), evmcfg.EVM().Transactions(), evmcfg.Database().Listener(), ethKeyStore, eventBroadcaster, txBuilder, nil, lggr, &testCheckerFactory{}, false) - require.NoError(t, err) { retryable, err := eb.ProcessUnstartedTxs(testutils.Context(t), fromAddress) assert.NoError(t, err) @@ -1174,7 +1173,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_Errors(t *testing.T) { // Check that the key had its nonce reset var nonce int64 - err := db.Get(&nonce, `SELECT next_nonce FROM evm_key_states WHERE address = $1 ORDER BY created_at ASC, id ASC`, fromAddress) + err = db.Get(&nonce, `SELECT next_nonce FROM evm.key_states WHERE address = $1 ORDER BY created_at ASC, id ASC`, fromAddress) require.NoError(t, err) // Saved NextNonce must be the same as before because this transaction // was not accepted by the eth node and never can be @@ -1479,7 +1478,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_Errors(t *testing.T) { assert.True(t, retryable) // TEARDOWN: Clear out the unsent tx before the next test - pgtest.MustExec(t, db, `DELETE FROM eth_txes WHERE nonce = $1`, localNextNonce) + pgtest.MustExec(t, db, `DELETE FROM evm.txes WHERE nonce = $1`, localNextNonce) }) t.Run("eth tx is left in progress if eth node returns insufficient eth", func(t *testing.T) { @@ -1510,7 +1509,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_Errors(t *testing.T) { assert.Nil(t, attempt.BroadcastBeforeBlockNum) }) - pgtest.MustExec(t, db, `DELETE FROM eth_txes`) + pgtest.MustExec(t, db, `DELETE FROM evm.txes`) t.Run("eth tx is left in progress if nonce is too high", func(t *testing.T) { localNextNonce := getLocalNextNonce(t, ethKeyStore, fromAddress) @@ -1538,7 +1537,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_Errors(t *testing.T) { assert.Equal(t, txmgrtypes.TxAttemptInProgress, attempt.State) assert.Nil(t, attempt.BroadcastBeforeBlockNum) - pgtest.MustExec(t, db, `DELETE FROM eth_txes`) + pgtest.MustExec(t, db, `DELETE FROM evm.txes`) }) t.Run("eth node returns underpriced transaction and bumping gas doesn't increase it in EIP-1559 mode", func(t *testing.T) { @@ -1568,7 +1567,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_Errors(t *testing.T) { require.Contains(t, err.Error(), "bumped gas tip cap of 1 wei is less than or equal to original gas tip cap of 1 wei") assert.True(t, retryable) - pgtest.MustExec(t, db, `DELETE FROM eth_txes`) + pgtest.MustExec(t, db, `DELETE FROM evm.txes`) }) t.Run("eth node returns underpriced transaction in EIP-1559 mode, bumps until inclusion", func(t *testing.T) { @@ -1617,7 +1616,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_Errors(t *testing.T) { assert.False(t, retryable) // TEARDOWN: Clear out the unsent tx before the next test - pgtest.MustExec(t, db, `DELETE FROM eth_txes WHERE nonce = $1`, localNextNonce) + pgtest.MustExec(t, db, `DELETE FROM evm.txes WHERE nonce = $1`, localNextNonce) }) } @@ -1672,7 +1671,7 @@ func TestEthBroadcaster_ProcessUnstartedEthTxs_KeystoreErrors(t *testing.T) { // Check that the key did not have its nonce incremented var nonce int64 - err = db.Get(&nonce, `SELECT next_nonce FROM evm_key_states WHERE address = $1 ORDER BY created_at ASC, id ASC`, fromAddress) + err = db.Get(&nonce, `SELECT next_nonce FROM evm.key_states WHERE address = $1 ORDER BY created_at ASC, id ASC`, fromAddress) require.NoError(t, err) require.Equal(t, int64(localNonce), nonce) }) @@ -1704,7 +1703,7 @@ func TestEthBroadcaster_IncrementNextNonce(t *testing.T) { // Nonce bumped to 1 var nonce int64 - err := db.Get(&nonce, `SELECT next_nonce FROM evm_key_states WHERE address = $1 ORDER BY created_at ASC, id ASC`, keyState.Address.Address()) + err := db.Get(&nonce, `SELECT next_nonce FROM evm.key_states WHERE address = $1 ORDER BY created_at ASC, id ASC`, keyState.Address.Address()) require.NoError(t, err) require.Equal(t, int64(1), nonce) } @@ -1771,7 +1770,7 @@ func TestEthBroadcaster_SyncNonce(t *testing.T) { sub := pgmocks.NewSubscription(t) sub.On("Events").Return(make(<-chan pg.Event)) sub.On("Close") - eventBroadcaster.On("Subscribe", "insert_on_eth_txes", "").Return(sub, nil) + eventBroadcaster.On("Subscribe", "evm.insert_on_txes", "").Return(sub, nil) estimator := gas.NewWrappedEvmEstimator(gas.NewFixedPriceEstimator(evmcfg.EVM().GasEstimator(), evmcfg.EVM().GasEstimator().BlockHistory(), lggr), evmcfg.EVM().GasEstimator().EIP1559DynamicFees()) checkerFactory := &testCheckerFactory{} @@ -1808,12 +1807,12 @@ func TestEthBroadcaster_SyncNonce(t *testing.T) { // Check keyState to make sure it has correct nonce assigned var nonce int64 - err := db.Get(&nonce, `SELECT next_nonce FROM evm_key_states WHERE address = $1 ORDER BY created_at ASC, id ASC`, fromAddress) + err := db.Get(&nonce, `SELECT next_nonce FROM evm.key_states WHERE address = $1 ORDER BY created_at ASC, id ASC`, fromAddress) require.NoError(t, err) assert.Equal(t, int64(ethNodeNonce), nonce) // The disabled key did not get updated - err = db.Get(&nonce, `SELECT next_nonce FROM evm_key_states WHERE address = $1 ORDER BY created_at ASC, id ASC`, disabledAddress) + err = db.Get(&nonce, `SELECT next_nonce FROM evm.key_states WHERE address = $1 ORDER BY created_at ASC, id ASC`, disabledAddress) require.NoError(t, err) assert.Equal(t, int64(0), nonce) }) @@ -1842,12 +1841,12 @@ func TestEthBroadcaster_SyncNonce(t *testing.T) { // Check keyState to make sure it has correct nonce assigned var nonce int64 - err := db.Get(&nonce, `SELECT next_nonce FROM evm_key_states WHERE address = $1 ORDER BY created_at ASC, id ASC`, fromAddress) + err := db.Get(&nonce, `SELECT next_nonce FROM evm.key_states WHERE address = $1 ORDER BY created_at ASC, id ASC`, fromAddress) require.NoError(t, err) assert.Equal(t, int64(ethNodeNonce), nonce) // The disabled key did not get updated - err = db.Get(&nonce, `SELECT next_nonce FROM evm_key_states WHERE address = $1 ORDER BY created_at ASC, id ASC`, disabledAddress) + err = db.Get(&nonce, `SELECT next_nonce FROM evm.key_states WHERE address = $1 ORDER BY created_at ASC, id ASC`, disabledAddress) require.NoError(t, err) assert.Equal(t, int64(0), nonce) }) diff --git a/core/chains/evm/txmgr/confirmer_test.go b/core/chains/evm/txmgr/confirmer_test.go index 3de0c1079bf..795725cdb2d 100644 --- a/core/chains/evm/txmgr/confirmer_test.go +++ b/core/chains/evm/txmgr/confirmer_test.go @@ -824,7 +824,7 @@ func TestEthConfirmer_CheckForReceipts_confirmed_missing_receipt_scoped_to_key(t etx2_9 := cltest.MustInsertUnconfirmedEthTx(t, txStore, 3, fromAddress1_2) // there also happens to be a confirmed tx with a higher nonce from a different chain in the DB etx_other_chain := cltest.MustInsertUnconfirmedEthTx(t, txStore, 8, fromAddress2_1) - pgtest.MustExec(t, db, `UPDATE eth_txes SET state='confirmed' WHERE id = $1`, etx_other_chain.ID) + pgtest.MustExec(t, db, `UPDATE evm.txes SET state='confirmed' WHERE id = $1`, etx_other_chain.ID) attempt2_9 := newBroadcastLegacyEthTxAttempt(t, etx2_9.ID, int64(1)) require.NoError(t, txStore.InsertTxAttempt(&attempt2_9)) @@ -914,7 +914,7 @@ func TestEthConfirmer_CheckForReceipts_confirmed_missing_receipt(t *testing.T) { attempt3_1 := newBroadcastLegacyEthTxAttempt(t, etx3.ID, int64(1)) require.NoError(t, txStore.InsertTxAttempt(&attempt3_1)) - pgtest.MustExec(t, db, `UPDATE eth_tx_attempts SET broadcast_before_block_num = 41 WHERE broadcast_before_block_num IS NULL`) + pgtest.MustExec(t, db, `UPDATE evm.tx_attempts SET broadcast_before_block_num = 41 WHERE broadcast_before_block_num IS NULL`) t.Run("marks buried eth_txes as 'confirmed_missing_receipt'", func(t *testing.T) { txmReceipt0 := evmtypes.Receipt{ @@ -1400,7 +1400,7 @@ func TestEthConfirmer_FindTxsRequiringRebroadcast(t *testing.T) { nonce++ attempt1_1 := etx1.TxAttempts[0] dbAttempt := txmgr.DbEthTxAttemptFromEthTxAttempt(&attempt1_1) - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, tooNew, attempt1_1.ID)) + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, tooNew, attempt1_1.ID)) attempt1_2 := newBroadcastLegacyEthTxAttempt(t, etx1.ID) attempt1_2.BroadcastBeforeBlockNum = &onTheMoney attempt1_2.TxFee = gas.EvmFee{Legacy: assets.NewWeiI(30000)} @@ -1417,7 +1417,7 @@ func TestEthConfirmer_FindTxsRequiringRebroadcast(t *testing.T) { nonce++ attempt2_1 := etx2.TxAttempts[0] dbAttempt = txmgr.DbEthTxAttemptFromEthTxAttempt(&attempt2_1) - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, tooNew, attempt2_1.ID)) + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, tooNew, attempt2_1.ID)) t.Run("returns nothing when the transaction has attempts that are too new", func(t *testing.T) { etxs, err := ec.FindTxsRequiringRebroadcast(testutils.Context(t), lggr, evmFromAddress, currentHead, gasBumpThreshold, 10, 0, &cltest.FixtureChainID) @@ -1464,13 +1464,13 @@ func TestEthConfirmer_FindTxsRequiringRebroadcast(t *testing.T) { nonce++ attempt3_1 := etx3.TxAttempts[0] dbAttempt = txmgr.DbEthTxAttemptFromEthTxAttempt(&attempt3_1) - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt3_1.ID)) + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt3_1.ID)) // NOTE: It should ignore qualifying eth_txes from a different address etxOther := cltest.MustInsertUnconfirmedEthTxWithBroadcastLegacyAttempt(t, txStore, 0, otherAddress) attemptOther1 := etxOther.TxAttempts[0] dbAttempt = txmgr.DbEthTxAttemptFromEthTxAttempt(&attemptOther1) - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attemptOther1.ID)) + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attemptOther1.ID)) t.Run("returns the transaction if it is unconfirmed with an attempt that is older than gasBumpThreshold blocks", func(t *testing.T) { etxs, err := ec.FindTxsRequiringRebroadcast(testutils.Context(t), lggr, evmFromAddress, currentHead, gasBumpThreshold, 10, 0, &cltest.FixtureChainID) @@ -1520,14 +1520,14 @@ func TestEthConfirmer_FindTxsRequiringRebroadcast(t *testing.T) { nonce++ attempt4_1 := etx4.TxAttempts[0] dbAttempt = txmgr.DbEthTxAttemptFromEthTxAttempt(&attemptOther1) - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt4_1.ID)) + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt4_1.ID)) t.Run("ignores pending transactions for another key", func(t *testing.T) { // Re-use etx3 nonce for another key, it should not affect the results for this key etxOther := cltest.MustInsertUnconfirmedEthTxWithBroadcastLegacyAttempt(t, txStore, (*etx3.Sequence).Int64(), otherAddress) aOther := etxOther.TxAttempts[0] dbAttempt = txmgr.DbEthTxAttemptFromEthTxAttempt(&aOther) - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, aOther.ID)) + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, aOther.ID)) etxs, err := ec.FindTxsRequiringRebroadcast(testutils.Context(t), lggr, evmFromAddress, currentHead, gasBumpThreshold, 6, 0, &cltest.FixtureChainID) require.NoError(t, err) @@ -1660,7 +1660,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary_WithConnectivityCheck(t *testing etx := cltest.MustInsertUnconfirmedEthTxWithBroadcastLegacyAttempt(t, txStore, nonce, fromAddress, originalBroadcastAt) attempt1 := etx.TxAttempts[0] dbAttempt := txmgr.DbEthTxAttemptFromEthTxAttempt(&attempt1) - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt1.ID)) + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt1.ID)) // Send transaction and assume success. ethClient.On("SendTransactionReturnCode", mock.Anything, mock.Anything, fromAddress).Return(clienttypes.Successful, nil).Once() @@ -1704,7 +1704,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary_WithConnectivityCheck(t *testing etx := cltest.MustInsertUnconfirmedEthTxWithBroadcastDynamicFeeAttempt(t, txStore, nonce, fromAddress, originalBroadcastAt) attempt1 := etx.TxAttempts[0] dbAttempt := txmgr.DbEthTxAttemptFromEthTxAttempt(&attempt1) - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt1.ID)) + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt1.ID)) // Send transaction and assume success. ethClient.On("SendTransactionReturnCode", mock.Anything, mock.Anything, fromAddress).Return(clienttypes.Successful, nil).Once() @@ -1754,7 +1754,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary(t *testing.T) { nonce++ attempt1_1 := etx.TxAttempts[0] var dbAttempt txmgr.DbEthTxAttempt - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt1_1.ID)) + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt1_1.ID)) t.Run("re-sends previous transaction on keystore error", func(t *testing.T) { // simulate bumped transaction that is somehow impossible to sign @@ -1889,7 +1889,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary(t *testing.T) { require.Len(t, etx.TxAttempts, 2) }) - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt1_2.ID)) + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt1_2.ID)) var attempt1_3 txmgr.TxAttempt t.Run("creates new attempt with higher gas price if transaction is already in mempool (e.g. due to previous crash before we could save the new attempt)", func(t *testing.T) { @@ -1927,7 +1927,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary(t *testing.T) { assert.Equal(t, txmgrtypes.TxAttemptBroadcast, attempt1_3.State) }) - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt1_3.ID)) + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt1_3.ID)) var attempt1_4 txmgr.TxAttempt t.Run("saves new attempt even for transaction that has already been confirmed (nonce already used)", func(t *testing.T) { @@ -1975,12 +1975,12 @@ func TestEthConfirmer_RebroadcastWhereNecessary(t *testing.T) { }) // Mark original tx as confirmed so we won't pick it up any more - pgtest.MustExec(t, db, `UPDATE eth_txes SET state = 'confirmed'`) + pgtest.MustExec(t, db, `UPDATE evm.txes SET state = 'confirmed'`) etx2 := cltest.MustInsertUnconfirmedEthTxWithBroadcastLegacyAttempt(t, txStore, nonce, fromAddress) nonce++ attempt2_1 := etx2.TxAttempts[0] - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt2_1.ID)) + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt2_1.ID)) var attempt2_2 txmgr.TxAttempt t.Run("saves in_progress attempt on temporary error and returns error", func(t *testing.T) { @@ -2048,7 +2048,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary(t *testing.T) { }) // Set BroadcastBeforeBlockNum again so the next test will pick it up - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt2_2.ID)) + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt2_2.ID)) t.Run("assumes that 'nonce too low' error means confirmed_missing_receipt", func(t *testing.T) { expectedBumpedGasPrice := big.NewInt(25000000000) @@ -2087,7 +2087,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary(t *testing.T) { etx3 := cltest.MustInsertUnconfirmedEthTxWithBroadcastLegacyAttempt(t, txStore, nonce, fromAddress) nonce++ attempt3_1 := etx3.TxAttempts[0] - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1, gas_price=$2 WHERE id=$3 RETURNING *`, oldEnough, assets.NewWeiI(35000000000), attempt3_1.ID)) + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1, gas_price=$2 WHERE id=$3 RETURNING *`, oldEnough, assets.NewWeiI(35000000000), attempt3_1.ID)) var attempt3_2 txmgr.TxAttempt @@ -2125,7 +2125,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary(t *testing.T) { assert.Equal(t, expectedBumpedGasPrice.Int64(), attempt3_2.TxFee.Legacy.ToInt().Int64()) }) - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt3_2.ID)) + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt3_2.ID)) var attempt3_3 txmgr.TxAttempt t.Run("handles case where transaction is already known somehow", func(t *testing.T) { @@ -2160,7 +2160,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary(t *testing.T) { assert.Equal(t, expectedBumpedGasPrice.Int64(), attempt3_3.TxFee.Legacy.ToInt().Int64()) }) - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt3_3.ID)) + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt3_3.ID)) var attempt3_4 txmgr.TxAttempt t.Run("pretends it was accepted and continues the cycle if rejected for being temporarily underpriced", func(t *testing.T) { @@ -2199,7 +2199,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary(t *testing.T) { assert.Equal(t, expectedBumpedGasPrice.Int64(), attempt3_4.TxFee.Legacy.ToInt().Int64()) }) - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt3_4.ID)) + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt3_4.ID)) t.Run("resubmits at the old price and does not create a new attempt if one of the bumped transactions would exceed EVM.GasEstimator.PriceMax", func(t *testing.T) { // Set price such that the next bump will exceed EVM.GasEstimator.PriceMax @@ -2230,7 +2230,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary(t *testing.T) { assert.Equal(t, gasPrice.Int64(), attempt3_4.TxFee.Legacy.ToInt().Int64()) }) - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt3_4.ID)) + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt3_4.ID)) t.Run("resubmits at the old price and does not create a new attempt if the current price is exactly EVM.GasEstimator.PriceMax", func(t *testing.T) { // Set price such that the current price is already at EVM.GasEstimator.PriceMax @@ -2264,7 +2264,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary(t *testing.T) { // The EIP-1559 etx and attempt etx4 := cltest.MustInsertUnconfirmedEthTxWithBroadcastDynamicFeeAttempt(t, txStore, nonce, fromAddress) attempt4_1 := etx4.TxAttempts[0] - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1, gas_tip_cap=$2, gas_fee_cap=$3 WHERE id=$4 RETURNING *`, + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1, gas_tip_cap=$2, gas_fee_cap=$3 WHERE id=$4 RETURNING *`, oldEnough, assets.GWei(35), assets.GWei(100), attempt4_1.ID)) var attempt4_2 txmgr.TxAttempt @@ -2301,7 +2301,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary(t *testing.T) { assert.Equal(t, txmgrtypes.TxAttemptBroadcast, attempt1_2.State) }) - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1, gas_tip_cap=$2, gas_fee_cap=$3 WHERE id=$4 RETURNING *`, + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1, gas_tip_cap=$2, gas_fee_cap=$3 WHERE id=$4 RETURNING *`, oldEnough, assets.GWei(999), assets.GWei(1000), attempt4_2.ID)) t.Run("EIP-1559: resubmits at the old price and does not create a new attempt if one of the bumped EIP-1559 transactions would have its tip cap exceed EVM.GasEstimator.PriceMax", func(t *testing.T) { @@ -2331,7 +2331,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary(t *testing.T) { assert.Equal(t, assets.GWei(1000).Int64(), attempt4_2.TxFee.DynamicFeeCap.ToInt().Int64()) }) - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1, gas_tip_cap=$2, gas_fee_cap=$3 WHERE id=$4 RETURNING *`, + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1, gas_tip_cap=$2, gas_fee_cap=$3 WHERE id=$4 RETURNING *`, oldEnough, assets.GWei(45), assets.GWei(100), attempt4_2.ID)) t.Run("EIP-1559: saves attempt anyway if replacement transaction is underpriced because the bumped gas price is insufficiently higher than the previous one", func(t *testing.T) { @@ -2431,7 +2431,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary_TerminallyUnderpriced_ThenGoesTh nonce++ legacyAttempt := etx.TxAttempts[0] dbAttempt := txmgr.DbEthTxAttemptFromEthTxAttempt(&legacyAttempt) - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, legacyAttempt.ID)) + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, legacyAttempt.ID)) // Fail a few times with terminally underpriced ethClient.On("SendTransactionReturnCode", mock.Anything, mock.Anything, fromAddress).Return( @@ -2463,7 +2463,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary_TerminallyUnderpriced_ThenGoesTh nonce++ dxFeeAttempt := etx.TxAttempts[0] dbAttempt := txmgr.DbEthTxAttemptFromEthTxAttempt(&dxFeeAttempt) - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, dxFeeAttempt.ID)) + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, dxFeeAttempt.ID)) // Fail a few times with terminally underpriced ethClient.On("SendTransactionReturnCode", mock.Anything, mock.Anything, fromAddress).Return( @@ -2514,7 +2514,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary_WhenOutOfEth(t *testing.T) { nonce++ attempt1_1 := etx.TxAttempts[0] dbAttempt := txmgr.DbEthTxAttemptFromEthTxAttempt(&attempt1_1) - require.NoError(t, db.Get(&dbAttempt, `UPDATE eth_tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt1_1.ID)) + require.NoError(t, db.Get(&dbAttempt, `UPDATE evm.tx_attempts SET broadcast_before_block_num=$1 WHERE id=$2 RETURNING *`, oldEnough, attempt1_1.ID)) var attempt1_2 txmgr.TxAttempt insufficientEthError := errors.New("insufficient funds for gas * price + value") @@ -2623,7 +2623,7 @@ func TestEthConfirmer_RebroadcastWhereNecessary_WhenOutOfEth(t *testing.T) { var dbAttempts []txmgr.DbEthTxAttempt - require.NoError(t, db.Select(&dbAttempts, "SELECT * FROM eth_tx_attempts WHERE state = 'insufficient_eth'")) + require.NoError(t, db.Select(&dbAttempts, "SELECT * FROM evm.tx_attempts WHERE state = 'insufficient_eth'")) require.Len(t, dbAttempts, 0) }) } @@ -2954,7 +2954,7 @@ func TestEthConfirmer_ResumePendingRuns(t *testing.T) { etx := cltest.MustInsertConfirmedEthTxWithLegacyAttempt(t, txStore, 1, 1, fromAddress) cltest.MustInsertEthReceipt(t, txStore, head.Number-minConfirmations, head.Hash, etx.TxAttempts[0].Hash) - pgtest.MustExec(t, db, `UPDATE eth_txes SET pipeline_task_run_id = $1, min_confirmations = $2 WHERE id = $3`, &tr.ID, minConfirmations, etx.ID) + pgtest.MustExec(t, db, `UPDATE evm.txes SET pipeline_task_run_id = $1, min_confirmations = $2 WHERE id = $3`, &tr.ID, minConfirmations, etx.ID) err = ec.ResumePendingTaskRuns(testutils.Context(t), &head) require.NoError(t, err) @@ -2974,7 +2974,7 @@ func TestEthConfirmer_ResumePendingRuns(t *testing.T) { etx := cltest.MustInsertConfirmedEthTxWithLegacyAttempt(t, txStore, 2, 1, fromAddress) cltest.MustInsertEthReceipt(t, txStore, head.Number, head.Hash, etx.TxAttempts[0].Hash) - pgtest.MustExec(t, db, `UPDATE eth_txes SET pipeline_task_run_id = $1, min_confirmations = $2 WHERE id = $3`, &tr.ID, minConfirmations, etx.ID) + pgtest.MustExec(t, db, `UPDATE evm.txes SET pipeline_task_run_id = $1, min_confirmations = $2 WHERE id = $3`, &tr.ID, minConfirmations, etx.ID) err = ec.ResumePendingTaskRuns(testutils.Context(t), &head) require.NoError(t, err) @@ -2996,10 +2996,10 @@ func TestEthConfirmer_ResumePendingRuns(t *testing.T) { pgtest.MustExec(t, db, `UPDATE pipeline_runs SET state = 'suspended' WHERE id = $1`, run.ID) etx := cltest.MustInsertConfirmedEthTxWithLegacyAttempt(t, txStore, 3, 1, fromAddress) - pgtest.MustExec(t, db, `UPDATE eth_txes SET meta='{"FailOnRevert": true}'`) + pgtest.MustExec(t, db, `UPDATE evm.txes SET meta='{"FailOnRevert": true}'`) receipt := cltest.MustInsertEthReceipt(t, txStore, head.Number-minConfirmations, head.Hash, etx.TxAttempts[0].Hash) - pgtest.MustExec(t, db, `UPDATE eth_txes SET pipeline_task_run_id = $1, min_confirmations = $2 WHERE id = $3`, &tr.ID, minConfirmations, etx.ID) + pgtest.MustExec(t, db, `UPDATE evm.txes SET pipeline_task_run_id = $1, min_confirmations = $2 WHERE id = $3`, &tr.ID, minConfirmations, etx.ID) go func() { err2 := ec.ResumePendingTaskRuns(testutils.Context(t), &head) @@ -3036,12 +3036,12 @@ func TestEthConfirmer_ResumePendingRuns(t *testing.T) { pgtest.MustExec(t, db, `UPDATE pipeline_runs SET state = 'suspended' WHERE id = $1`, run.ID) etx := cltest.MustInsertConfirmedEthTxWithLegacyAttempt(t, txStore, 4, 1, fromAddress) - pgtest.MustExec(t, db, `UPDATE eth_txes SET meta='{"FailOnRevert": true}'`) + pgtest.MustExec(t, db, `UPDATE evm.txes SET meta='{"FailOnRevert": true}'`) // receipt is not passed through as a value since it reverted and caused an error cltest.MustInsertRevertedEthReceipt(t, txStore, head.Number-minConfirmations, head.Hash, etx.TxAttempts[0].Hash) - pgtest.MustExec(t, db, `UPDATE eth_txes SET pipeline_task_run_id = $1, min_confirmations = $2 WHERE id = $3`, &tr.ID, minConfirmations, etx.ID) + pgtest.MustExec(t, db, `UPDATE evm.txes SET pipeline_task_run_id = $1, min_confirmations = $2 WHERE id = $3`, &tr.ID, minConfirmations, etx.ID) go func() { err2 := ec.ResumePendingTaskRuns(testutils.Context(t), &head) diff --git a/core/chains/evm/txmgr/evm_tx_store.go b/core/chains/evm/txmgr/evm_tx_store.go index dbd3437aa82..4585d868603 100644 --- a/core/chains/evm/txmgr/evm_tx_store.go +++ b/core/chains/evm/txmgr/evm_tx_store.go @@ -81,7 +81,7 @@ type evmTxStore struct { var _ EvmTxStore = (*evmTxStore)(nil) var _ TestEvmTxStore = (*evmTxStore)(nil) -// Directly maps to columns of database table "eth_receipts". +// Directly maps to columns of database table "evm.receipts". // Do not modify type unless you // intend to modify the database schema type dbReceipt struct { @@ -148,7 +148,7 @@ func toOnchainReceipt(rs []*evmtypes.Receipt) []rawOnchainReceipt { return receipts } -// Directly maps to columns of database table "eth_txes". +// Directly maps to columns of database table "evm.txes". // This is exported, as tests and other external code still directly reads DB using this schema. type DbEthTx struct { ID int64 @@ -253,7 +253,7 @@ func dbEthTxsToEvmEthTxPtrs(dbEthTxs []DbEthTx, evmEthTxs []*Tx) { } } -// Directly maps to columns of database table "eth_tx_attempts". +// Directly maps to columns of database table "evm.tx_attempts". // This is exported, as tests and other external code still directly reads DB using this schema. type DbEthTxAttempt struct { ID int64 @@ -344,7 +344,7 @@ func NewTxStore( } const insertIntoEthTxAttemptsQuery = ` -INSERT INTO eth_tx_attempts (eth_tx_id, gas_price, signed_raw_tx, hash, broadcast_before_block_num, state, created_at, chain_specific_gas_limit, tx_type, gas_tip_cap, gas_fee_cap) +INSERT INTO evm.tx_attempts (eth_tx_id, gas_price, signed_raw_tx, hash, broadcast_before_block_num, state, created_at, chain_specific_gas_limit, tx_type, gas_tip_cap, gas_fee_cap) VALUES (:eth_tx_id, :gas_price, :signed_raw_tx, :hash, :broadcast_before_block_num, :state, NOW(), :chain_specific_gas_limit, :tx_type, :gas_tip_cap, :gas_fee_cap) RETURNING *; ` @@ -365,7 +365,7 @@ func (o *evmTxStore) preloadTxAttempts(txs []Tx) error { return nil } var dbAttempts []DbEthTxAttempt - sql := `SELECT * FROM eth_tx_attempts WHERE eth_tx_id IN (?) ORDER BY id desc;` + sql := `SELECT * FROM evm.tx_attempts WHERE eth_tx_id IN (?) ORDER BY id desc;` query, args, err := sqlx.In(sql, ids) if err != nil { return err @@ -400,7 +400,7 @@ func (o *evmTxStore) PreloadTxes(attempts []TxAttempt, qopts ...pg.QOpt) error { } dbEthTxs := make([]DbEthTx, len(ethTxIDs)) qq := o.q.WithOpts(qopts...) - if err := qq.Select(&dbEthTxs, `SELECT * FROM eth_txes WHERE id = ANY($1)`, pq.Array(ethTxIDs)); err != nil { + if err := qq.Select(&dbEthTxs, `SELECT * FROM evm.txes WHERE id = ANY($1)`, pq.Array(ethTxIDs)); err != nil { return pkgerrors.Wrap(err, "loadEthTxes failed") } for _, dbEtx := range dbEthTxs { @@ -417,12 +417,12 @@ func (o *evmTxStore) PreloadTxes(attempts []TxAttempt, qopts ...pg.QOpt) error { // Transactions returns all eth transactions without loaded relations // limited by passed parameters. func (o *evmTxStore) Transactions(offset, limit int) (txs []Tx, count int, err error) { - sql := `SELECT count(*) FROM eth_txes WHERE id IN (SELECT DISTINCT eth_tx_id FROM eth_tx_attempts)` + sql := `SELECT count(*) FROM evm.txes WHERE id IN (SELECT DISTINCT eth_tx_id FROM evm.tx_attempts)` if err = o.q.Get(&count, sql); err != nil { return } - sql = `SELECT * FROM eth_txes WHERE id IN (SELECT DISTINCT eth_tx_id FROM eth_tx_attempts) ORDER BY id desc LIMIT $1 OFFSET $2` + sql = `SELECT * FROM evm.txes WHERE id IN (SELECT DISTINCT eth_tx_id FROM evm.tx_attempts) ORDER BY id desc LIMIT $1 OFFSET $2` var dbEthTxs []DbEthTx if err = o.q.Select(&dbEthTxs, sql, limit, offset); err != nil { return @@ -434,12 +434,12 @@ func (o *evmTxStore) Transactions(offset, limit int) (txs []Tx, count int, err e // TransactionsWithAttempts returns all eth transactions with at least one attempt // limited by passed parameters. Attempts are sorted by id. func (o *evmTxStore) TransactionsWithAttempts(offset, limit int) (txs []Tx, count int, err error) { - sql := `SELECT count(*) FROM eth_txes WHERE id IN (SELECT DISTINCT eth_tx_id FROM eth_tx_attempts)` + sql := `SELECT count(*) FROM evm.txes WHERE id IN (SELECT DISTINCT eth_tx_id FROM evm.tx_attempts)` if err = o.q.Get(&count, sql); err != nil { return } - sql = `SELECT * FROM eth_txes WHERE id IN (SELECT DISTINCT eth_tx_id FROM eth_tx_attempts) ORDER BY id desc LIMIT $1 OFFSET $2` + sql = `SELECT * FROM evm.txes WHERE id IN (SELECT DISTINCT eth_tx_id FROM evm.tx_attempts) ORDER BY id desc LIMIT $1 OFFSET $2` var dbTxs []DbEthTx if err = o.q.Select(&dbTxs, sql, limit, offset); err != nil { return @@ -451,12 +451,12 @@ func (o *evmTxStore) TransactionsWithAttempts(offset, limit int) (txs []Tx, coun // TxAttempts returns the last tx attempts sorted by created_at descending. func (o *evmTxStore) TxAttempts(offset, limit int) (txs []TxAttempt, count int, err error) { - sql := `SELECT count(*) FROM eth_tx_attempts` + sql := `SELECT count(*) FROM evm.tx_attempts` if err = o.q.Get(&count, sql); err != nil { return } - sql = `SELECT * FROM eth_tx_attempts ORDER BY created_at DESC, id DESC LIMIT $1 OFFSET $2` + sql = `SELECT * FROM evm.tx_attempts ORDER BY created_at DESC, id DESC LIMIT $1 OFFSET $2` var dbTxs []DbEthTxAttempt if err = o.q.Select(&dbTxs, sql, limit, offset); err != nil { return @@ -469,7 +469,7 @@ func (o *evmTxStore) TxAttempts(offset, limit int) (txs []TxAttempt, count int, // FindTxAttempt returns an individual TxAttempt func (o *evmTxStore) FindTxAttempt(hash common.Hash) (*TxAttempt, error) { dbTxAttempt := DbEthTxAttempt{} - sql := `SELECT * FROM eth_tx_attempts WHERE hash = $1` + sql := `SELECT * FROM evm.tx_attempts WHERE hash = $1` if err := o.q.Get(&dbTxAttempt, sql, hash); err != nil { return nil, err } @@ -483,7 +483,7 @@ func (o *evmTxStore) FindTxAttempt(hash common.Hash) (*TxAttempt, error) { // FindTxAttemptsByTxIDs returns a list of attempts by ETH Tx IDs func (o *evmTxStore) FindTxAttemptsByTxIDs(ids []int64) ([]TxAttempt, error) { - sql := `SELECT * FROM eth_tx_attempts WHERE eth_tx_id = ANY($1)` + sql := `SELECT * FROM evm.tx_attempts WHERE eth_tx_id = ANY($1)` var dbTxAttempts []DbEthTxAttempt if err := o.q.Select(&dbTxAttempts, sql, ids); err != nil { return nil, err @@ -494,7 +494,7 @@ func (o *evmTxStore) FindTxAttemptsByTxIDs(ids []int64) ([]TxAttempt, error) { func (o *evmTxStore) FindTxByHash(hash common.Hash) (*Tx, error) { var dbEtx DbEthTx err := o.q.Transaction(func(tx pg.Queryer) error { - sql := `SELECT eth_txes.* FROM eth_txes WHERE id IN (SELECT DISTINCT eth_tx_id FROM eth_tx_attempts WHERE hash = $1)` + sql := `SELECT evm.txes.* FROM evm.txes WHERE id IN (SELECT DISTINCT eth_tx_id FROM evm.tx_attempts WHERE hash = $1)` if err := tx.Get(&dbEtx, sql, hash); err != nil { return pkgerrors.Wrapf(err, "failed to find eth_tx with hash %d", hash) } @@ -511,7 +511,7 @@ func (o *evmTxStore) InsertTx(etx *Tx) error { if etx.CreatedAt == (time.Time{}) { etx.CreatedAt = time.Now() } - const insertEthTxSQL = `INSERT INTO eth_txes (nonce, from_address, to_address, encoded_payload, value, gas_limit, error, broadcast_at, initial_broadcast_at, created_at, state, meta, subject, pipeline_task_run_id, min_confirmations, evm_chain_id, transmit_checker) VALUES ( + const insertEthTxSQL = `INSERT INTO evm.txes (nonce, from_address, to_address, encoded_payload, value, gas_limit, error, broadcast_at, initial_broadcast_at, created_at, state, meta, subject, pipeline_task_run_id, min_confirmations, evm_chain_id, transmit_checker) VALUES ( :nonce, :from_address, :to_address, :encoded_payload, :value, :gas_limit, :error, :broadcast_at, :initial_broadcast_at, :created_at, :state, :meta, :subject, :pipeline_task_run_id, :min_confirmations, :evm_chain_id, :transmit_checker ) RETURNING *` dbTx := DbEthTxFromEthTx(etx) @@ -533,7 +533,7 @@ func (o *evmTxStore) InsertReceipt(receipt *evmtypes.Receipt) (int64, error) { // convert to database representation r := DbReceiptFromEvmReceipt(receipt) - const insertEthReceiptSQL = `INSERT INTO eth_receipts (tx_hash, block_hash, block_number, transaction_index, receipt, created_at) VALUES ( + const insertEthReceiptSQL = `INSERT INTO evm.receipts (tx_hash, block_hash, block_number, transaction_index, receipt, created_at) VALUES ( :tx_hash, :block_hash, :block_number, :transaction_index, :receipt, NOW() ) RETURNING *` err := o.q.GetNamed(insertEthReceiptSQL, &r, &r) @@ -545,15 +545,15 @@ func (o *evmTxStore) InsertReceipt(receipt *evmtypes.Receipt) (int64, error) { func (o *evmTxStore) FindTxWithAttempts(etxID int64) (etx Tx, err error) { err = o.q.Transaction(func(tx pg.Queryer) error { var dbEtx DbEthTx - if err = tx.Get(&dbEtx, `SELECT * FROM eth_txes WHERE id = $1 ORDER BY created_at ASC, id ASC`, etxID); err != nil { + if err = tx.Get(&dbEtx, `SELECT * FROM evm.txes WHERE id = $1 ORDER BY created_at ASC, id ASC`, etxID); err != nil { return pkgerrors.Wrapf(err, "failed to find eth_tx with id %d", etxID) } DbEthTxToEthTx(dbEtx, &etx) if err = o.LoadTxAttempts(&etx, pg.WithQueryer(tx)); err != nil { - return pkgerrors.Wrapf(err, "failed to load eth_tx_attempts for eth_tx with id %d", etxID) + return pkgerrors.Wrapf(err, "failed to load evm.tx_attempts for eth_tx with id %d", etxID) } if err = loadEthTxAttemptsReceipts(tx, &etx); err != nil { - return pkgerrors.Wrapf(err, "failed to load eth_receipts for eth_tx with id %d", etxID) + return pkgerrors.Wrapf(err, "failed to load evm.receipts for eth_tx with id %d", etxID) } return nil }, pg.OptReadOnlyTx()) @@ -565,8 +565,8 @@ func (o *evmTxStore) FindTxAttemptConfirmedByTxIDs(ids []int64) ([]TxAttempt, er err := o.q.Transaction(func(tx pg.Queryer) error { var dbAttempts []DbEthTxAttempt if err := tx.Select(&dbAttempts, `SELECT eta.* - FROM eth_tx_attempts eta - join eth_receipts er on eta.hash = er.tx_hash where eta.eth_tx_id = ANY($1) ORDER BY eta.gas_price DESC, eta.gas_tip_cap DESC`, ids); err != nil { + FROM evm.tx_attempts eta + join evm.receipts er on eta.hash = er.tx_hash where eta.eth_tx_id = ANY($1) ORDER BY eta.gas_price DESC, eta.gas_tip_cap DESC`, ids); err != nil { return err } txAttempts = dbEthTxAttemptsToEthTxAttempts(dbAttempts) @@ -585,8 +585,8 @@ func (o *evmTxStore) LoadTxesAttempts(etxs []*Tx, qopts ...pg.QOpt) error { ethTxesM[etx.ID] = etxs[i] } var dbTxAttempts []DbEthTxAttempt - if err := qq.Select(&dbTxAttempts, `SELECT * FROM eth_tx_attempts WHERE eth_tx_id = ANY($1) ORDER BY eth_tx_attempts.gas_price DESC, eth_tx_attempts.gas_tip_cap DESC`, pq.Array(ethTxIDs)); err != nil { - return pkgerrors.Wrap(err, "loadEthTxesAttempts failed to load eth_tx_attempts") + if err := qq.Select(&dbTxAttempts, `SELECT * FROM evm.tx_attempts WHERE eth_tx_id = ANY($1) ORDER BY evm.tx_attempts.gas_price DESC, evm.tx_attempts.gas_tip_cap DESC`, pq.Array(ethTxIDs)); err != nil { + return pkgerrors.Wrap(err, "loadEthTxesAttempts failed to load evm.tx_attempts") } for _, dbAttempt := range dbTxAttempts { etx := ethTxesM[dbAttempt.EthTxID] @@ -618,8 +618,8 @@ func loadEthTxesAttemptsReceipts(q pg.Queryer, etxs []*Tx) (err error) { } } var rs []dbReceipt - if err = q.Select(&rs, `SELECT * FROM eth_receipts WHERE tx_hash = ANY($1)`, pq.Array(attemptHashes)); err != nil { - return pkgerrors.Wrap(err, "loadEthTxesAttemptsReceipts failed to load eth_receipts") + if err = q.Select(&rs, `SELECT * FROM evm.receipts WHERE tx_hash = ANY($1)`, pq.Array(attemptHashes)); err != nil { + return pkgerrors.Wrap(err, "loadEthTxesAttemptsReceipts failed to load evm.receipts") } var receipts []*evmtypes.Receipt = fromDBReceipts(rs) @@ -639,8 +639,8 @@ func loadConfirmedAttemptsReceipts(q pg.Queryer, attempts []TxAttempt) error { hashes = append(hashes, attempt.Hash.Bytes()) } var rs []dbReceipt - if err := q.Select(&rs, `SELECT * FROM eth_receipts WHERE tx_hash = ANY($1)`, pq.Array(hashes)); err != nil { - return pkgerrors.Wrap(err, "loadConfirmedAttemptsReceipts failed to load eth_receipts") + if err := q.Select(&rs, `SELECT * FROM evm.receipts WHERE tx_hash = ANY($1)`, pq.Array(hashes)); err != nil { + return pkgerrors.Wrap(err, "loadConfirmedAttemptsReceipts failed to load evm.receipts") } var receipts []*evmtypes.Receipt = fromDBReceipts(rs) for _, receipt := range receipts { @@ -658,19 +658,19 @@ func (o *evmTxStore) FindTxAttemptsRequiringResend(olderThan time.Time, maxInFli limit = null.Uint32From(maxInFlightTransactions) } var dbAttempts []DbEthTxAttempt - // this select distinct works because of unique index on eth_txes + // this select distinct works because of unique index on evm.txes // (evm_chain_id, from_address, nonce) err = o.q.Select(&dbAttempts, ` -SELECT DISTINCT ON (eth_txes.nonce) eth_tx_attempts.* -FROM eth_tx_attempts -JOIN eth_txes ON eth_txes.id = eth_tx_attempts.eth_tx_id AND eth_txes.state IN ('unconfirmed', 'confirmed_missing_receipt') -WHERE eth_tx_attempts.state <> 'in_progress' AND eth_txes.broadcast_at <= $1 AND evm_chain_id = $2 AND from_address = $3 -ORDER BY eth_txes.nonce ASC, eth_tx_attempts.gas_price DESC, eth_tx_attempts.gas_tip_cap DESC +SELECT DISTINCT ON (evm.txes.nonce) evm.tx_attempts.* +FROM evm.tx_attempts +JOIN evm.txes ON evm.txes.id = evm.tx_attempts.eth_tx_id AND evm.txes.state IN ('unconfirmed', 'confirmed_missing_receipt') +WHERE evm.tx_attempts.state <> 'in_progress' AND evm.txes.broadcast_at <= $1 AND evm_chain_id = $2 AND from_address = $3 +ORDER BY evm.txes.nonce ASC, evm.tx_attempts.gas_price DESC, evm.tx_attempts.gas_tip_cap DESC LIMIT $4 `, olderThan, chainID.String(), address, limit) attempts = dbEthTxAttemptsToEthTxAttempts(dbAttempts) - return attempts, pkgerrors.Wrap(err, "FindEthTxAttemptsRequiringResend failed to load eth_tx_attempts") + return attempts, pkgerrors.Wrap(err, "FindEthTxAttemptsRequiringResend failed to load evm.tx_attempts") } func (o *evmTxStore) UpdateBroadcastAts(now time.Time, etxIDs []int64) error { @@ -681,8 +681,8 @@ func (o *evmTxStore) UpdateBroadcastAts(now time.Time, etxIDs []int64) error { // Since EthConfirmer/EthResender can race (totally OK since highest // priced transaction always wins) we only want to update broadcast_at if // our version is later. - _, err := o.q.Exec(`UPDATE eth_txes SET broadcast_at = $1 WHERE id = ANY($2) AND broadcast_at < $1`, now, pq.Array(etxIDs)) - return pkgerrors.Wrap(err, "updateBroadcastAts failed to update eth_txes") + _, err := o.q.Exec(`UPDATE evm.txes SET broadcast_at = $1 WHERE id = ANY($2) AND broadcast_at < $1`, now, pq.Array(etxIDs)) + return pkgerrors.Wrap(err, "updateBroadcastAts failed to update evm.txes") } // SetBroadcastBeforeBlockNum updates already broadcast attempts with the @@ -690,11 +690,11 @@ func (o *evmTxStore) UpdateBroadcastAts(now time.Time, etxIDs []int64) error { // the attempt is already broadcast it _must_ have been before this head. func (o *evmTxStore) SetBroadcastBeforeBlockNum(blockNum int64, chainID *big.Int) error { _, err := o.q.Exec( - `UPDATE eth_tx_attempts + `UPDATE evm.tx_attempts SET broadcast_before_block_num = $1 -FROM eth_txes -WHERE eth_tx_attempts.broadcast_before_block_num IS NULL AND eth_tx_attempts.state = 'broadcast' -AND eth_txes.id = eth_tx_attempts.eth_tx_id AND eth_txes.evm_chain_id = $2`, +FROM evm.txes +WHERE evm.tx_attempts.broadcast_before_block_num IS NULL AND evm.tx_attempts.state = 'broadcast' +AND evm.txes.id = evm.tx_attempts.eth_tx_id AND evm.txes.evm_chain_id = $2`, blockNum, chainID.String(), ) return pkgerrors.Wrap(err, "SetBroadcastBeforeBlockNum failed") @@ -703,11 +703,11 @@ AND eth_txes.id = eth_tx_attempts.eth_tx_id AND eth_txes.evm_chain_id = $2`, func (o *evmTxStore) FindTxAttemptsConfirmedMissingReceipt(chainID *big.Int) (attempts []TxAttempt, err error) { var dbAttempts []DbEthTxAttempt err = o.q.Select(&dbAttempts, - `SELECT DISTINCT ON (eth_tx_attempts.eth_tx_id) eth_tx_attempts.* - FROM eth_tx_attempts - JOIN eth_txes ON eth_txes.id = eth_tx_attempts.eth_tx_id AND eth_txes.state = 'confirmed_missing_receipt' + `SELECT DISTINCT ON (evm.tx_attempts.eth_tx_id) evm.tx_attempts.* + FROM evm.tx_attempts + JOIN evm.txes ON evm.txes.id = evm.tx_attempts.eth_tx_id AND evm.txes.state = 'confirmed_missing_receipt' WHERE evm_chain_id = $1 - ORDER BY eth_tx_attempts.eth_tx_id ASC, eth_tx_attempts.gas_price DESC, eth_tx_attempts.gas_tip_cap DESC`, + ORDER BY evm.tx_attempts.eth_tx_id ASC, evm.tx_attempts.gas_price DESC, evm.tx_attempts.gas_tip_cap DESC`, chainID.String()) if err != nil { err = pkgerrors.Wrap(err, "FindEtxAttemptsConfirmedMissingReceipt failed to query") @@ -717,7 +717,7 @@ func (o *evmTxStore) FindTxAttemptsConfirmedMissingReceipt(chainID *big.Int) (at } func (o *evmTxStore) UpdateTxsUnconfirmed(ids []int64) error { - _, err := o.q.Exec(`UPDATE eth_txes SET state='unconfirmed' WHERE id = ANY($1)`, pq.Array(ids)) + _, err := o.q.Exec(`UPDATE evm.txes SET state='unconfirmed' WHERE id = ANY($1)`, pq.Array(ids)) if err != nil { return pkgerrors.Wrap(err, "UpdateEthTxsUnconfirmed failed to execute") @@ -729,17 +729,17 @@ func (o *evmTxStore) FindTxAttemptsRequiringReceiptFetch(chainID *big.Int) (atte err = o.q.Transaction(func(tx pg.Queryer) error { var dbAttempts []DbEthTxAttempt err = tx.Select(&dbAttempts, ` -SELECT eth_tx_attempts.* FROM eth_tx_attempts -JOIN eth_txes ON eth_txes.id = eth_tx_attempts.eth_tx_id AND eth_txes.state IN ('unconfirmed', 'confirmed_missing_receipt') AND eth_txes.evm_chain_id = $1 -WHERE eth_tx_attempts.state != 'insufficient_eth' -ORDER BY eth_txes.nonce ASC, eth_tx_attempts.gas_price DESC, eth_tx_attempts.gas_tip_cap DESC +SELECT evm.tx_attempts.* FROM evm.tx_attempts +JOIN evm.txes ON evm.txes.id = evm.tx_attempts.eth_tx_id AND evm.txes.state IN ('unconfirmed', 'confirmed_missing_receipt') AND evm.txes.evm_chain_id = $1 +WHERE evm.tx_attempts.state != 'insufficient_eth' +ORDER BY evm.txes.nonce ASC, evm.tx_attempts.gas_price DESC, evm.tx_attempts.gas_tip_cap DESC `, chainID.String()) if err != nil { - return pkgerrors.Wrap(err, "FindEthTxAttemptsRequiringReceiptFetch failed to load eth_tx_attempts") + return pkgerrors.Wrap(err, "FindEthTxAttemptsRequiringReceiptFetch failed to load evm.tx_attempts") } attempts = dbEthTxAttemptsToEthTxAttempts(dbAttempts) err = o.PreloadTxes(attempts, pg.WithQueryer(tx)) - return pkgerrors.Wrap(err, "FindEthTxAttemptsRequiringReceiptFetch failed to load eth_txes") + return pkgerrors.Wrap(err, "FindEthTxAttemptsRequiringReceiptFetch failed to load evm.txes") }, pg.OptReadOnlyTx()) return } @@ -793,27 +793,27 @@ func (o *evmTxStore) SaveFetchedReceipts(r []*evmtypes.Receipt, chainID *big.Int /* #nosec G201 */ sql := ` WITH inserted_receipts AS ( - INSERT INTO eth_receipts (tx_hash, block_hash, block_number, transaction_index, receipt, created_at) + INSERT INTO evm.receipts (tx_hash, block_hash, block_number, transaction_index, receipt, created_at) VALUES %s ON CONFLICT (tx_hash, block_hash) DO UPDATE SET block_number = EXCLUDED.block_number, transaction_index = EXCLUDED.transaction_index, receipt = EXCLUDED.receipt - RETURNING eth_receipts.tx_hash, eth_receipts.block_number + RETURNING evm.receipts.tx_hash, evm.receipts.block_number ), updated_eth_tx_attempts AS ( - UPDATE eth_tx_attempts + UPDATE evm.tx_attempts SET state = 'broadcast', - broadcast_before_block_num = COALESCE(eth_tx_attempts.broadcast_before_block_num, inserted_receipts.block_number) + broadcast_before_block_num = COALESCE(evm.tx_attempts.broadcast_before_block_num, inserted_receipts.block_number) FROM inserted_receipts - WHERE inserted_receipts.tx_hash = eth_tx_attempts.hash - RETURNING eth_tx_attempts.eth_tx_id + WHERE inserted_receipts.tx_hash = evm.tx_attempts.hash + RETURNING evm.tx_attempts.eth_tx_id ) - UPDATE eth_txes + UPDATE evm.txes SET state = 'confirmed' FROM updated_eth_tx_attempts - WHERE updated_eth_tx_attempts.eth_tx_id = eth_txes.id + WHERE updated_eth_tx_attempts.eth_tx_id = evm.txes.id AND evm_chain_id = ? ` @@ -826,7 +826,7 @@ func (o *evmTxStore) SaveFetchedReceipts(r []*evmtypes.Receipt, chainID *big.Int } // MarkAllConfirmedMissingReceipt -// It is possible that we can fail to get a receipt for all eth_tx_attempts +// It is possible that we can fail to get a receipt for all evm.tx_attempts // even though a transaction with this nonce has long since been confirmed (we // know this because transactions with higher nonces HAVE returned a receipt). // @@ -837,7 +837,7 @@ func (o *evmTxStore) SaveFetchedReceipts(r []*evmtypes.Receipt, chainID *big.Int // In this case we mark these transactions as 'confirmed_missing_receipt' to // prevent gas bumping. // -// NOTE: We continue to attempt to resend eth_txes in this state on +// NOTE: We continue to attempt to resend evm.txes in this state on // every head to guard against the extremely rare scenario of nonce gap due to // reorg that excludes the transaction (from another wallet) that had this // nonce (until finality depth is reached, after which we make the explicit @@ -847,18 +847,18 @@ func (o *evmTxStore) SaveFetchedReceipts(r []*evmtypes.Receipt, chainID *big.Int // attempts are below the finality depth from current head. func (o *evmTxStore) MarkAllConfirmedMissingReceipt(chainID *big.Int) (err error) { res, err := o.q.Exec(` -UPDATE eth_txes +UPDATE evm.txes SET state = 'confirmed_missing_receipt' FROM ( SELECT from_address, MAX(nonce) as max_nonce - FROM eth_txes + FROM evm.txes WHERE state = 'confirmed' AND evm_chain_id = $1 GROUP BY from_address ) AS max_table WHERE state = 'unconfirmed' AND evm_chain_id = $1 AND nonce < max_table.max_nonce - AND eth_txes.from_address = max_table.from_address + AND evm.txes.from_address = max_table.from_address `, chainID.String()) if err != nil { return pkgerrors.Wrap(err, "markAllConfirmedMissingReceipt failed") @@ -878,16 +878,16 @@ func (o *evmTxStore) GetInProgressTxAttempts(ctx context.Context, address common err = qq.Transaction(func(tx pg.Queryer) error { var dbAttempts []DbEthTxAttempt err = tx.Select(&dbAttempts, ` -SELECT eth_tx_attempts.* FROM eth_tx_attempts -INNER JOIN eth_txes ON eth_txes.id = eth_tx_attempts.eth_tx_id AND eth_txes.state in ('confirmed', 'confirmed_missing_receipt', 'unconfirmed') -WHERE eth_tx_attempts.state = 'in_progress' AND eth_txes.from_address = $1 AND eth_txes.evm_chain_id = $2 +SELECT evm.tx_attempts.* FROM evm.tx_attempts +INNER JOIN evm.txes ON evm.txes.id = evm.tx_attempts.eth_tx_id AND evm.txes.state in ('confirmed', 'confirmed_missing_receipt', 'unconfirmed') +WHERE evm.tx_attempts.state = 'in_progress' AND evm.txes.from_address = $1 AND evm.txes.evm_chain_id = $2 `, address, chainID.String()) if err != nil { - return pkgerrors.Wrap(err, "getInProgressEthTxAttempts failed to load eth_tx_attempts") + return pkgerrors.Wrap(err, "getInProgressEthTxAttempts failed to load evm.tx_attempts") } attempts = dbEthTxAttemptsToEthTxAttempts(dbAttempts) err = o.PreloadTxes(attempts, pg.WithQueryer(tx)) - return pkgerrors.Wrap(err, "getInProgressEthTxAttempts failed to load eth_txes") + return pkgerrors.Wrap(err, "getInProgressEthTxAttempts failed to load evm.txes") }, pg.OptReadOnlyTx()) return attempts, pkgerrors.Wrap(err, "getInProgressEthTxAttempts failed") } @@ -896,12 +896,12 @@ func (o *evmTxStore) FindReceiptsPendingConfirmation(ctx context.Context, blockN var rs []dbReceiptPlus err = o.q.SelectContext(ctx, &rs, ` - SELECT pipeline_task_runs.id, eth_receipts.receipt, COALESCE((eth_txes.meta->>'FailOnRevert')::boolean, false) "FailOnRevert" FROM pipeline_task_runs + SELECT pipeline_task_runs.id, evm.receipts.receipt, COALESCE((evm.txes.meta->>'FailOnRevert')::boolean, false) "FailOnRevert" FROM pipeline_task_runs INNER JOIN pipeline_runs ON pipeline_runs.id = pipeline_task_runs.pipeline_run_id - INNER JOIN eth_txes ON eth_txes.pipeline_task_run_id = pipeline_task_runs.id - INNER JOIN eth_tx_attempts ON eth_txes.id = eth_tx_attempts.eth_tx_id - INNER JOIN eth_receipts ON eth_tx_attempts.hash = eth_receipts.tx_hash - WHERE pipeline_runs.state = 'suspended' AND eth_receipts.block_number <= ($1 - eth_txes.min_confirmations) AND eth_txes.evm_chain_id = $2 + INNER JOIN evm.txes ON evm.txes.pipeline_task_run_id = pipeline_task_runs.id + INNER JOIN evm.tx_attempts ON evm.txes.id = evm.tx_attempts.eth_tx_id + INNER JOIN evm.receipts ON evm.tx_attempts.hash = evm.receipts.tx_hash + WHERE pipeline_runs.state = 'suspended' AND evm.receipts.block_number <= ($1 - evm.txes.min_confirmations) AND evm.txes.evm_chain_id = $2 `, blockNum, chainID.String()) receiptsPlus = fromDBReceiptsPlus(rs) @@ -911,12 +911,12 @@ func (o *evmTxStore) FindReceiptsPendingConfirmation(ctx context.Context, blockN // FindTxWithIdempotencyKey returns any broadcast ethtx with the given idempotencyKey and chainID func (o *evmTxStore) FindTxWithIdempotencyKey(idempotencyKey string, chainID *big.Int) (etx *Tx, err error) { var dbEtx DbEthTx - err = o.q.Get(&dbEtx, `SELECT * FROM eth_txes WHERE idempotency_key = $1 and evm_chain_id = $2`, idempotencyKey, chainID.String()) + err = o.q.Get(&dbEtx, `SELECT * FROM evm.txes WHERE idempotency_key = $1 and evm_chain_id = $2`, idempotencyKey, chainID.String()) if err != nil { if errors.Is(err, sql.ErrNoRows) { return nil, nil } - return nil, pkgerrors.Wrap(err, "FindTxWithIdempotencyKey failed to load eth_txes") + return nil, pkgerrors.Wrap(err, "FindTxWithIdempotencyKey failed to load evm.txes") } etx = new(Tx) DbEthTxToEthTx(dbEtx, etx) @@ -929,14 +929,14 @@ func (o *evmTxStore) FindTxWithSequence(fromAddress common.Address, nonce evmtyp err = o.q.Transaction(func(tx pg.Queryer) error { var dbEtx DbEthTx err = tx.Get(&dbEtx, ` -SELECT * FROM eth_txes WHERE from_address = $1 AND nonce = $2 AND state IN ('confirmed', 'confirmed_missing_receipt', 'unconfirmed') +SELECT * FROM evm.txes WHERE from_address = $1 AND nonce = $2 AND state IN ('confirmed', 'confirmed_missing_receipt', 'unconfirmed') `, fromAddress, nonce.Int64()) if err != nil { - return pkgerrors.Wrap(err, "FindEthTxWithNonce failed to load eth_txes") + return pkgerrors.Wrap(err, "FindEthTxWithNonce failed to load evm.txes") } DbEthTxToEthTx(dbEtx, etx) err = o.LoadTxAttempts(etx, pg.WithQueryer(tx)) - return pkgerrors.Wrap(err, "FindEthTxWithNonce failed to load eth_tx_attempts") + return pkgerrors.Wrap(err, "FindEthTxWithNonce failed to load evm.tx_attempts") }, pg.OptReadOnlyTx()) if errors.Is(err, sql.ErrNoRows) { return nil, nil @@ -948,7 +948,7 @@ func updateEthTxAttemptUnbroadcast(q pg.Queryer, attempt TxAttempt) error { if attempt.State != txmgrtypes.TxAttemptBroadcast { return errors.New("expected eth_tx_attempt to be broadcast") } - _, err := q.Exec(`UPDATE eth_tx_attempts SET broadcast_before_block_num = NULL, state = 'in_progress' WHERE id = $1`, attempt.ID) + _, err := q.Exec(`UPDATE evm.tx_attempts SET broadcast_before_block_num = NULL, state = 'in_progress' WHERE id = $1`, attempt.ID) return pkgerrors.Wrap(err, "updateEthTxAttemptUnbroadcast failed") } @@ -956,16 +956,16 @@ func updateEthTxUnconfirm(q pg.Queryer, etx Tx) error { if etx.State != txmgr.TxConfirmed { return errors.New("expected eth_tx state to be confirmed") } - _, err := q.Exec(`UPDATE eth_txes SET state = 'unconfirmed' WHERE id = $1`, etx.ID) + _, err := q.Exec(`UPDATE evm.txes SET state = 'unconfirmed' WHERE id = $1`, etx.ID) return pkgerrors.Wrap(err, "updateEthTxUnconfirm failed") } func deleteEthReceipts(q pg.Queryer, etxID int64) (err error) { _, err = q.Exec(` -DELETE FROM eth_receipts -USING eth_tx_attempts -WHERE eth_receipts.tx_hash = eth_tx_attempts.hash -AND eth_tx_attempts.eth_tx_id = $1 +DELETE FROM evm.receipts +USING evm.tx_attempts +WHERE evm.receipts.tx_hash = evm.tx_attempts.hash +AND evm.tx_attempts.eth_tx_id = $1 `, etxID) return pkgerrors.Wrap(err, "deleteEthReceipts failed") } @@ -986,22 +986,22 @@ func (o *evmTxStore) FindTransactionsConfirmedInBlockRange(highBlockNumber, lowB err = o.q.Transaction(func(tx pg.Queryer) error { var dbEtxs []DbEthTx err = tx.Select(&dbEtxs, ` -SELECT DISTINCT eth_txes.* FROM eth_txes -INNER JOIN eth_tx_attempts ON eth_txes.id = eth_tx_attempts.eth_tx_id AND eth_tx_attempts.state = 'broadcast' -INNER JOIN eth_receipts ON eth_receipts.tx_hash = eth_tx_attempts.hash -WHERE eth_txes.state IN ('confirmed', 'confirmed_missing_receipt') AND block_number BETWEEN $1 AND $2 AND evm_chain_id = $3 +SELECT DISTINCT evm.txes.* FROM evm.txes +INNER JOIN evm.tx_attempts ON evm.txes.id = evm.tx_attempts.eth_tx_id AND evm.tx_attempts.state = 'broadcast' +INNER JOIN evm.receipts ON evm.receipts.tx_hash = evm.tx_attempts.hash +WHERE evm.txes.state IN ('confirmed', 'confirmed_missing_receipt') AND block_number BETWEEN $1 AND $2 AND evm_chain_id = $3 ORDER BY nonce ASC `, lowBlockNumber, highBlockNumber, chainID.String()) if err != nil { - return pkgerrors.Wrap(err, "FindTransactionsConfirmedInBlockRange failed to load eth_txes") + return pkgerrors.Wrap(err, "FindTransactionsConfirmedInBlockRange failed to load evm.txes") } etxs = make([]*Tx, len(dbEtxs)) dbEthTxsToEvmEthTxPtrs(dbEtxs, etxs) if err = o.LoadTxesAttempts(etxs, pg.WithQueryer(tx)); err != nil { - return pkgerrors.Wrap(err, "FindTransactionsConfirmedInBlockRange failed to load eth_tx_attempts") + return pkgerrors.Wrap(err, "FindTransactionsConfirmedInBlockRange failed to load evm.tx_attempts") } err = loadEthTxesAttemptsReceipts(tx, etxs) - return pkgerrors.Wrap(err, "FindTransactionsConfirmedInBlockRange failed to load eth_receipts") + return pkgerrors.Wrap(err, "FindTransactionsConfirmedInBlockRange failed to load evm.receipts") }, pg.OptReadOnlyTx()) return etxs, pkgerrors.Wrap(err, "FindTransactionsConfirmedInBlockRange failed") } @@ -1014,11 +1014,11 @@ func saveAttemptWithNewState(q pg.Queryer, timeout time.Duration, logger logger. // In case of null broadcast_at (shouldn't happen) we don't want to // update anyway because it indicates a state where broadcast_at makes // no sense e.g. fatal_error - if _, err := tx.Exec(`UPDATE eth_txes SET broadcast_at = $1 WHERE id = $2 AND broadcast_at < $1`, broadcastAt, dbAttempt.EthTxID); err != nil { - return pkgerrors.Wrap(err, "saveAttemptWithNewState failed to update eth_txes") + if _, err := tx.Exec(`UPDATE evm.txes SET broadcast_at = $1 WHERE id = $2 AND broadcast_at < $1`, broadcastAt, dbAttempt.EthTxID); err != nil { + return pkgerrors.Wrap(err, "saveAttemptWithNewState failed to update evm.txes") } - _, err := tx.Exec(`UPDATE eth_tx_attempts SET state=$1 WHERE id=$2`, dbAttempt.State, dbAttempt.ID) - return pkgerrors.Wrap(err, "saveAttemptWithNewState failed to update eth_tx_attempts") + _, err := tx.Exec(`UPDATE evm.tx_attempts SET state=$1 WHERE id=$2`, dbAttempt.State, dbAttempt.ID) + return pkgerrors.Wrap(err, "saveAttemptWithNewState failed to update evm.tx_attempts") }) } @@ -1048,8 +1048,8 @@ func (o *evmTxStore) SaveConfirmedMissingReceiptAttempt(ctx context.Context, tim if err := saveSentAttempt(tx, timeout, o.logger, attempt, broadcastAt); err != nil { return err } - if _, err := tx.Exec(`UPDATE eth_txes SET state = 'confirmed_missing_receipt' WHERE id = $1`, attempt.TxID); err != nil { - return pkgerrors.Wrap(err, "failed to update eth_txes") + if _, err := tx.Exec(`UPDATE evm.txes SET state = 'confirmed_missing_receipt' WHERE id = $1`, attempt.TxID); err != nil { + return pkgerrors.Wrap(err, "failed to update evm.txes") } return nil @@ -1066,7 +1066,7 @@ func (o *evmTxStore) DeleteInProgressAttempt(ctx context.Context, attempt TxAtte if attempt.ID == 0 { return errors.New("DeleteInProgressAttempt: expected attempt to have an id") } - _, err := qq.Exec(`DELETE FROM eth_tx_attempts WHERE id = $1`, attempt.ID) + _, err := qq.Exec(`DELETE FROM evm.tx_attempts WHERE id = $1`, attempt.ID) return pkgerrors.Wrap(err, "DeleteInProgressAttempt failed") } @@ -1084,19 +1084,19 @@ func (o *evmTxStore) SaveInProgressAttempt(attempt *TxAttempt) error { } e = o.q.Get(&dbAttempt, query, args...) DbEthTxAttemptToEthTxAttempt(dbAttempt, attempt) - return pkgerrors.Wrap(e, "SaveInProgressAttempt failed to insert into eth_tx_attempts") + return pkgerrors.Wrap(e, "SaveInProgressAttempt failed to insert into evm.tx_attempts") } // Update only applies to case of insufficient eth and simply changes the state to in_progress - res, err := o.q.Exec(`UPDATE eth_tx_attempts SET state=$1, broadcast_before_block_num=$2 WHERE id=$3`, dbAttempt.State, dbAttempt.BroadcastBeforeBlockNum, dbAttempt.ID) + res, err := o.q.Exec(`UPDATE evm.tx_attempts SET state=$1, broadcast_before_block_num=$2 WHERE id=$3`, dbAttempt.State, dbAttempt.BroadcastBeforeBlockNum, dbAttempt.ID) if err != nil { - return pkgerrors.Wrap(err, "SaveInProgressAttempt failed to update eth_tx_attempts") + return pkgerrors.Wrap(err, "SaveInProgressAttempt failed to update evm.tx_attempts") } rowsAffected, err := res.RowsAffected() if err != nil { return pkgerrors.Wrap(err, "SaveInProgressAttempt failed to get RowsAffected") } if rowsAffected == 0 { - return pkgerrors.Wrapf(sql.ErrNoRows, "SaveInProgressAttempt tried to update eth_tx_attempts but no rows matched id %d", attempt.ID) + return pkgerrors.Wrapf(sql.ErrNoRows, "SaveInProgressAttempt tried to update evm.tx_attempts but no rows matched id %d", attempt.ID) } return nil } @@ -1105,7 +1105,7 @@ func (o *evmTxStore) SaveInProgressAttempt(attempt *TxAttempt) error { // attempts which are unconfirmed for at least gasBumpThreshold blocks, // limited by limit pending transactions // -// It also returns eth_txes that are unconfirmed with no eth_tx_attempts +// It also returns evm.txes that are unconfirmed with no evm.tx_attempts func (o *evmTxStore) FindTxsRequiringGasBump(ctx context.Context, address common.Address, blockNum, gasBumpThreshold, depth int64, chainID *big.Int) (etxs []*Tx, err error) { if gasBumpThreshold == 0 { return @@ -1113,20 +1113,20 @@ func (o *evmTxStore) FindTxsRequiringGasBump(ctx context.Context, address common qq := o.q.WithOpts(pg.WithParentCtx(ctx)) err = qq.Transaction(func(tx pg.Queryer) error { stmt := ` -SELECT eth_txes.* FROM eth_txes -LEFT JOIN eth_tx_attempts ON eth_txes.id = eth_tx_attempts.eth_tx_id AND (broadcast_before_block_num > $4 OR broadcast_before_block_num IS NULL OR eth_tx_attempts.state != 'broadcast') -WHERE eth_txes.state = 'unconfirmed' AND eth_tx_attempts.id IS NULL AND eth_txes.from_address = $1 AND eth_txes.evm_chain_id = $2 - AND (($3 = 0) OR (eth_txes.id IN (SELECT id FROM eth_txes WHERE state = 'unconfirmed' AND from_address = $1 ORDER BY nonce ASC LIMIT $3))) +SELECT evm.txes.* FROM evm.txes +LEFT JOIN evm.tx_attempts ON evm.txes.id = evm.tx_attempts.eth_tx_id AND (broadcast_before_block_num > $4 OR broadcast_before_block_num IS NULL OR evm.tx_attempts.state != 'broadcast') +WHERE evm.txes.state = 'unconfirmed' AND evm.tx_attempts.id IS NULL AND evm.txes.from_address = $1 AND evm.txes.evm_chain_id = $2 + AND (($3 = 0) OR (evm.txes.id IN (SELECT id FROM evm.txes WHERE state = 'unconfirmed' AND from_address = $1 ORDER BY nonce ASC LIMIT $3))) ORDER BY nonce ASC ` var dbEtxs []DbEthTx if err = tx.Select(&dbEtxs, stmt, address, chainID.String(), depth, blockNum-gasBumpThreshold); err != nil { - return pkgerrors.Wrap(err, "FindEthTxsRequiringGasBump failed to load eth_txes") + return pkgerrors.Wrap(err, "FindEthTxsRequiringGasBump failed to load evm.txes") } etxs = make([]*Tx, len(dbEtxs)) dbEthTxsToEvmEthTxPtrs(dbEtxs, etxs) err = o.LoadTxesAttempts(etxs, pg.WithQueryer(tx)) - return pkgerrors.Wrap(err, "FindEthTxsRequiringGasBump failed to load eth_tx_attempts") + return pkgerrors.Wrap(err, "FindEthTxsRequiringGasBump failed to load evm.tx_attempts") }, pg.OptReadOnlyTx()) return } @@ -1139,18 +1139,18 @@ func (o *evmTxStore) FindTxsRequiringResubmissionDueToInsufficientFunds(address err = qq.Transaction(func(tx pg.Queryer) error { var dbEtxs []DbEthTx err = tx.Select(&dbEtxs, ` -SELECT DISTINCT eth_txes.* FROM eth_txes -INNER JOIN eth_tx_attempts ON eth_txes.id = eth_tx_attempts.eth_tx_id AND eth_tx_attempts.state = 'insufficient_eth' -WHERE eth_txes.from_address = $1 AND eth_txes.state = 'unconfirmed' AND eth_txes.evm_chain_id = $2 +SELECT DISTINCT evm.txes.* FROM evm.txes +INNER JOIN evm.tx_attempts ON evm.txes.id = evm.tx_attempts.eth_tx_id AND evm.tx_attempts.state = 'insufficient_eth' +WHERE evm.txes.from_address = $1 AND evm.txes.state = 'unconfirmed' AND evm.txes.evm_chain_id = $2 ORDER BY nonce ASC `, address, chainID.String()) if err != nil { - return pkgerrors.Wrap(err, "FindEthTxsRequiringResubmissionDueToInsufficientEth failed to load eth_txes") + return pkgerrors.Wrap(err, "FindEthTxsRequiringResubmissionDueToInsufficientEth failed to load evm.txes") } etxs = make([]*Tx, len(dbEtxs)) dbEthTxsToEvmEthTxPtrs(dbEtxs, etxs) err = o.LoadTxesAttempts(etxs, pg.WithQueryer(tx)) - return pkgerrors.Wrap(err, "FindEthTxsRequiringResubmissionDueToInsufficientEth failed to load eth_tx_attempts") + return pkgerrors.Wrap(err, "FindEthTxsRequiringResubmissionDueToInsufficientEth failed to load evm.tx_attempts") }, pg.OptReadOnlyTx()) return } @@ -1182,20 +1182,20 @@ func (o *evmTxStore) MarkOldTxesMissingReceiptAsErrored(blockNum int64, finality } var data []etx err := q.Select(&data, ` -UPDATE eth_txes +UPDATE evm.txes SET state='fatal_error', nonce=NULL, error=$1, broadcast_at=NULL, initial_broadcast_at=NULL FROM ( - SELECT e1.id, e1.nonce, e1.from_address FROM eth_txes AS e1 WHERE id IN ( - SELECT e2.id FROM eth_txes AS e2 - INNER JOIN eth_tx_attempts ON e2.id = eth_tx_attempts.eth_tx_id + SELECT e1.id, e1.nonce, e1.from_address FROM evm.txes AS e1 WHERE id IN ( + SELECT e2.id FROM evm.txes AS e2 + INNER JOIN evm.tx_attempts ON e2.id = evm.tx_attempts.eth_tx_id WHERE e2.state = 'confirmed_missing_receipt' AND e2.evm_chain_id = $3 GROUP BY e2.id - HAVING max(eth_tx_attempts.broadcast_before_block_num) < $2 + HAVING max(evm.tx_attempts.broadcast_before_block_num) < $2 ) FOR UPDATE OF e1 ) e0 -WHERE e0.id = eth_txes.id +WHERE e0.id = evm.txes.id RETURNING e0.id, e0.nonce`, ErrCouldNotGetReceipt, cutoff, chainID.String()) if err != nil { @@ -1223,8 +1223,8 @@ RETURNING e0.id, e0.nonce`, ErrCouldNotGetReceipt, cutoff, chainID.String()) var results []result err = q.Select(&results, ` SELECT e.id, e.from_address, max(a.broadcast_before_block_num) AS max_broadcast_before_block_num, array_agg(a.hash) AS tx_hashes -FROM eth_txes e -INNER JOIN eth_tx_attempts a ON e.id = a.eth_tx_id +FROM evm.txes e +INNER JOIN evm.tx_attempts a ON e.id = a.eth_tx_id WHERE e.id = ANY($1) GROUP BY e.id `, etxIDs) @@ -1262,8 +1262,8 @@ func (o *evmTxStore) SaveReplacementInProgressAttempt(oldAttempt TxAttempt, repl return errors.New("expected oldAttempt to have an ID") } return qq.Transaction(func(tx pg.Queryer) error { - if _, err := tx.Exec(`DELETE FROM eth_tx_attempts WHERE id=$1`, oldAttempt.ID); err != nil { - return pkgerrors.Wrap(err, "saveReplacementInProgressAttempt failed to delete from eth_tx_attempts") + if _, err := tx.Exec(`DELETE FROM evm.tx_attempts WHERE id=$1`, oldAttempt.ID); err != nil { + return pkgerrors.Wrap(err, "saveReplacementInProgressAttempt failed to delete from evm.tx_attempts") } dbAttempt := DbEthTxAttemptFromEthTxAttempt(replacementAttempt) query, args, e := tx.BindNamed(insertIntoEthTxAttemptsQuery, &dbAttempt) @@ -1280,7 +1280,7 @@ func (o *evmTxStore) SaveReplacementInProgressAttempt(oldAttempt TxAttempt, repl func (o *evmTxStore) FindNextUnstartedTransactionFromAddress(etx *Tx, fromAddress common.Address, chainID *big.Int, qopts ...pg.QOpt) error { qq := o.q.WithOpts(qopts...) var dbEtx DbEthTx - err := qq.Get(&dbEtx, `SELECT * FROM eth_txes WHERE from_address = $1 AND state = 'unstarted' AND evm_chain_id = $2 ORDER BY value ASC, created_at ASC, id ASC`, fromAddress, chainID.String()) + err := qq.Get(&dbEtx, `SELECT * FROM evm.txes WHERE from_address = $1 AND state = 'unstarted' AND evm_chain_id = $2 ORDER BY value ASC, created_at ASC, id ASC`, fromAddress, chainID.String()) DbEthTxToEthTx(dbEtx, etx) return pkgerrors.Wrap(err, "failed to FindNextUnstartedTransactionFromAddress") } @@ -1299,11 +1299,11 @@ func (o *evmTxStore) UpdateTxFatalError(etx *Tx, qopts ...pg.QOpt) error { etx.State = txmgr.TxFatalError return qq.Transaction(func(tx pg.Queryer) error { - if _, err := tx.Exec(`DELETE FROM eth_tx_attempts WHERE eth_tx_id = $1`, etx.ID); err != nil { + if _, err := tx.Exec(`DELETE FROM evm.tx_attempts WHERE eth_tx_id = $1`, etx.ID); err != nil { return pkgerrors.Wrapf(err, "saveFatallyErroredTransaction failed to delete eth_tx_attempt with eth_tx.ID %v", etx.ID) } dbEtx := DbEthTxFromEthTx(etx) - err := pkgerrors.Wrap(tx.Get(&dbEtx, `UPDATE eth_txes SET state=$1, error=$2, broadcast_at=NULL, initial_broadcast_at=NULL, nonce=NULL WHERE id=$3 RETURNING *`, etx.State, etx.Error, etx.ID), "saveFatallyErroredTransaction failed to save eth_tx") + err := pkgerrors.Wrap(tx.Get(&dbEtx, `UPDATE evm.txes SET state=$1, error=$2, broadcast_at=NULL, initial_broadcast_at=NULL, nonce=NULL WHERE id=$3 RETURNING *`, etx.State, etx.Error, etx.ID), "saveFatallyErroredTransaction failed to save eth_tx") DbEthTxToEthTx(dbEtx, etx) return err }) @@ -1337,12 +1337,12 @@ func (o *evmTxStore) UpdateTxAttemptInProgressToBroadcast(etx *Tx, attempt TxAtt return pkgerrors.Wrap(err, "SaveEthTxAttempt failed on incrNextNonceCallback") } dbEtx := DbEthTxFromEthTx(etx) - if err := tx.Get(&dbEtx, `UPDATE eth_txes SET state=$1, error=$2, broadcast_at=$3, initial_broadcast_at=$4 WHERE id = $5 RETURNING *`, dbEtx.State, dbEtx.Error, dbEtx.BroadcastAt, dbEtx.InitialBroadcastAt, dbEtx.ID); err != nil { + if err := tx.Get(&dbEtx, `UPDATE evm.txes SET state=$1, error=$2, broadcast_at=$3, initial_broadcast_at=$4 WHERE id = $5 RETURNING *`, dbEtx.State, dbEtx.Error, dbEtx.BroadcastAt, dbEtx.InitialBroadcastAt, dbEtx.ID); err != nil { return pkgerrors.Wrap(err, "SaveEthTxAttempt failed to save eth_tx") } DbEthTxToEthTx(dbEtx, etx) dbAttempt := DbEthTxAttemptFromEthTxAttempt(&attempt) - if err := tx.Get(&dbAttempt, `UPDATE eth_tx_attempts SET state = $1 WHERE id = $2 RETURNING *`, dbAttempt.State, dbAttempt.ID); err != nil { + if err := tx.Get(&dbAttempt, `UPDATE evm.tx_attempts SET state = $1 WHERE id = $2 RETURNING *`, dbAttempt.State, dbAttempt.ID); err != nil { return pkgerrors.Wrap(err, "SaveEthTxAttempt failed to save eth_tx_attempt") } return nil @@ -1364,13 +1364,13 @@ func (o *evmTxStore) UpdateTxUnstartedToInProgress(etx *Tx, attempt *TxAttempt, etx.State = txmgr.TxInProgress return qq.Transaction(func(tx pg.Queryer) error { // If a replay was triggered while unconfirmed transactions were pending, they will be marked as fatal_error => abandoned. - // In this case, we must remove the abandoned attempt from eth_tx_attempts before replacing it with a new one. In any other + // In this case, we must remove the abandoned attempt from evm.tx_attempts before replacing it with a new one. In any other // case, we uphold the constraint, leaving the original tx attempt as-is and returning the constraint violation error. // - // Note: the record of the original abandoned transaction will remain in eth_txes, only the attempt is replaced. (Any receipt + // Note: the record of the original abandoned transaction will remain in evm.txes, only the attempt is replaced. (Any receipt // associated with the abandoned attempt would also be lost, although this shouldn't happen since only unconfirmed transactions // can be abandoned.) - _, err := tx.Exec(`DELETE FROM eth_tx_attempts a USING eth_txes t + _, err := tx.Exec(`DELETE FROM evm.tx_attempts a USING evm.txes t WHERE t.id = a.eth_tx_id AND a.hash = $1 AND t.state = $2 AND t.error = 'abandoned'`, attempt.Hash, txmgr.TxFatalError, ) @@ -1388,12 +1388,10 @@ func (o *evmTxStore) UpdateTxUnstartedToInProgress(etx *Tx, attempt *TxAttempt, err = tx.Get(&dbAttempt, query, args...) if err != nil { var pqErr *pgconn.PgError - if isPqErr := errors.As(err, &pqErr); isPqErr { - switch pqErr.ConstraintName { - case "eth_tx_attempts_eth_tx_id_fkey": - return txmgr.ErrTxRemoved - default: - } + if isPqErr := errors.As(err, &pqErr); isPqErr && + pqErr.SchemaName == "evm" && + pqErr.ConstraintName == "eth_tx_attempts_eth_tx_id_fkey" { + return txmgr.ErrTxRemoved } if err != nil { return pkgerrors.Wrap(err, "UpdateTxUnstartedToInProgress failed to create eth_tx_attempt") @@ -1401,7 +1399,7 @@ func (o *evmTxStore) UpdateTxUnstartedToInProgress(etx *Tx, attempt *TxAttempt, } DbEthTxAttemptToEthTxAttempt(dbAttempt, attempt) dbEtx := DbEthTxFromEthTx(etx) - err = tx.Get(&dbEtx, `UPDATE eth_txes SET nonce=$1, state=$2, broadcast_at=$3, initial_broadcast_at=$4 WHERE id=$5 RETURNING *`, etx.Sequence, etx.State, etx.BroadcastAt, etx.InitialBroadcastAt, etx.ID) + err = tx.Get(&dbEtx, `UPDATE evm.txes SET nonce=$1, state=$2, broadcast_at=$3, initial_broadcast_at=$4 WHERE id=$5 RETURNING *`, etx.Sequence, etx.State, etx.BroadcastAt, etx.InitialBroadcastAt, etx.ID) DbEthTxToEthTx(dbEtx, etx) return pkgerrors.Wrap(err, "UpdateTxUnstartedToInProgress failed to update eth_tx") }) @@ -1419,7 +1417,7 @@ func (o *evmTxStore) GetTxInProgress(fromAddress common.Address, qopts ...pg.QOp } err = qq.Transaction(func(tx pg.Queryer) error { var dbEtx DbEthTx - err = tx.Get(&dbEtx, `SELECT * FROM eth_txes WHERE from_address = $1 and state = 'in_progress'`, fromAddress) + err = tx.Get(&dbEtx, `SELECT * FROM evm.txes WHERE from_address = $1 and state = 'in_progress'`, fromAddress) if errors.Is(err, sql.ErrNoRows) { etx = nil return nil @@ -1442,7 +1440,7 @@ func (o *evmTxStore) GetTxInProgress(fromAddress common.Address, qopts ...pg.QOp func (o *evmTxStore) HasInProgressTransaction(account common.Address, chainID *big.Int, qopts ...pg.QOpt) (exists bool, err error) { qq := o.q.WithOpts(qopts...) - err = qq.Get(&exists, `SELECT EXISTS(SELECT 1 FROM eth_txes WHERE state = 'in_progress' AND from_address = $1 AND evm_chain_id = $2)`, account, chainID.String()) + err = qq.Get(&exists, `SELECT EXISTS(SELECT 1 FROM evm.txes WHERE state = 'in_progress' AND from_address = $1 AND evm_chain_id = $2)`, account, chainID.String()) return exists, pkgerrors.Wrap(err, "hasInProgressTransaction failed") } @@ -1451,7 +1449,7 @@ func (o *evmTxStore) UpdateKeyNextSequence(newNextNonce, currentNextNonce evmtyp return qq.Transaction(func(tx pg.Queryer) error { // We filter by next_nonce here as an optimistic lock to make sure it // didn't get changed out from under us. Shouldn't happen but can't hurt. - res, err := tx.Exec(`UPDATE evm_key_states SET next_nonce = $1, updated_at = $2 WHERE address = $3 AND next_nonce = $4 AND evm_chain_id = $5`, newNextNonce.Int64(), time.Now(), address, currentNextNonce.Int64(), chainID.String()) + res, err := tx.Exec(`UPDATE evm.key_states SET next_nonce = $1, updated_at = $2 WHERE address = $3 AND next_nonce = $4 AND evm_chain_id = $5`, newNextNonce.Int64(), time.Now(), address, currentNextNonce.Int64(), chainID.String()) if err != nil { return pkgerrors.Wrap(err, "NonceSyncer#fastForwardNonceIfNecessary failed to update keys.next_nonce") } @@ -1468,7 +1466,7 @@ func (o *evmTxStore) UpdateKeyNextSequence(newNextNonce, currentNextNonce evmtyp func (o *evmTxStore) countTransactionsWithState(fromAddress common.Address, state txmgrtypes.TxState, chainID *big.Int, qopts ...pg.QOpt) (count uint32, err error) { qq := o.q.WithOpts(qopts...) - err = qq.Get(&count, `SELECT count(*) FROM eth_txes WHERE from_address = $1 AND state = $2 AND evm_chain_id = $3`, + err = qq.Get(&count, `SELECT count(*) FROM evm.txes WHERE from_address = $1 AND state = $2 AND evm_chain_id = $3`, fromAddress, state, chainID.String()) return count, pkgerrors.Wrap(err, "failed to countTransactionsWithState") } @@ -1489,7 +1487,7 @@ func (o *evmTxStore) CheckTxQueueCapacity(fromAddress common.Address, maxQueuedT return nil } var count uint64 - err = qq.Get(&count, `SELECT count(*) FROM eth_txes WHERE from_address = $1 AND state = 'unstarted' AND evm_chain_id = $2`, fromAddress, chainID.String()) + err = qq.Get(&count, `SELECT count(*) FROM evm.txes WHERE from_address = $1 AND state = 'unstarted' AND evm_chain_id = $2`, fromAddress, chainID.String()) if err != nil { err = pkgerrors.Wrap(err, "CheckTxQueueCapacity query failed") return @@ -1507,7 +1505,7 @@ func (o *evmTxStore) CreateTransaction(txRequest TxRequest, chainID *big.Int, qo err = qq.Transaction(func(tx pg.Queryer) error { if txRequest.PipelineTaskRunID != nil { - err = tx.Get(&dbEtx, `SELECT * FROM eth_txes WHERE pipeline_task_run_id = $1 AND evm_chain_id = $2`, txRequest.PipelineTaskRunID, chainID.String()) + err = tx.Get(&dbEtx, `SELECT * FROM evm.txes WHERE pipeline_task_run_id = $1 AND evm_chain_id = $2`, txRequest.PipelineTaskRunID, chainID.String()) // If no eth_tx matches (the common case) then continue if !errors.Is(err, sql.ErrNoRows) { if err != nil { @@ -1518,19 +1516,19 @@ func (o *evmTxStore) CreateTransaction(txRequest TxRequest, chainID *big.Int, qo } } err = tx.Get(&dbEtx, ` -INSERT INTO eth_txes (from_address, to_address, encoded_payload, value, gas_limit, state, created_at, meta, subject, evm_chain_id, min_confirmations, pipeline_task_run_id, transmit_checker, idempotency_key) +INSERT INTO evm.txes (from_address, to_address, encoded_payload, value, gas_limit, state, created_at, meta, subject, evm_chain_id, min_confirmations, pipeline_task_run_id, transmit_checker, idempotency_key) VALUES ( $1,$2,$3,$4,$5,'unstarted',NOW(),$6,$7,$8,$9,$10,$11,$12 ) -RETURNING "eth_txes".* +RETURNING "txes".* `, txRequest.FromAddress, txRequest.ToAddress, txRequest.EncodedPayload, assets.Eth(txRequest.Value), txRequest.FeeLimit, txRequest.Meta, txRequest.Strategy.Subject(), chainID.String(), txRequest.MinConfirmations, txRequest.PipelineTaskRunID, txRequest.Checker, txRequest.IdempotencyKey) if err != nil { - return pkgerrors.Wrap(err, "CreateEthTransaction failed to insert eth_tx") + return pkgerrors.Wrap(err, "CreateEthTransaction failed to insert evm tx") } var pruned int64 pruned, err = txRequest.Strategy.PruneQueue(o, pg.WithQueryer(tx)) if err != nil { - return pkgerrors.Wrap(err, "CreateEthTransaction failed to prune eth_txes") + return pkgerrors.Wrap(err, "CreateEthTransaction failed to prune evm.txes") } if pruned > 0 { o.logger.Warnw(fmt.Sprintf("Dropped %d old transactions from transaction queue", pruned), "fromAddress", txRequest.FromAddress, "toAddress", txRequest.ToAddress, "meta", txRequest.Meta, "subject", txRequest.Strategy.Subject(), "replacementID", dbEtx.ID) @@ -1546,12 +1544,12 @@ func (o *evmTxStore) PruneUnstartedTxQueue(queueSize uint32, subject uuid.UUID, qq := o.q.WithOpts(qopts...) err = qq.Transaction(func(tx pg.Queryer) error { res, err := qq.Exec(` -DELETE FROM eth_txes +DELETE FROM evm.txes WHERE state = 'unstarted' AND subject = $1 AND id < ( SELECT min(id) FROM ( SELECT id - FROM eth_txes + FROM evm.txes WHERE state = 'unstarted' AND subject = $2 ORDER BY id DESC LIMIT $3 @@ -1567,26 +1565,26 @@ id < ( } func (o *evmTxStore) ReapTxHistory(minBlockNumberToKeep int64, timeThreshold time.Time, chainID *big.Int) error { - // Delete old confirmed eth_txes + // Delete old confirmed evm.txes // NOTE that this relies on foreign key triggers automatically removing - // the eth_tx_attempts and eth_receipts linked to every eth_tx + // the evm.tx_attempts and evm.receipts linked to every eth_tx err := pg.Batch(func(_, limit uint) (count uint, err error) { res, err := o.q.Exec(` WITH old_enough_receipts AS ( - SELECT tx_hash FROM eth_receipts + SELECT tx_hash FROM evm.receipts WHERE block_number < $1 ORDER BY block_number ASC, id ASC LIMIT $2 ) -DELETE FROM eth_txes -USING old_enough_receipts, eth_tx_attempts -WHERE eth_tx_attempts.eth_tx_id = eth_txes.id -AND eth_tx_attempts.hash = old_enough_receipts.tx_hash -AND eth_txes.created_at < $3 -AND eth_txes.state = 'confirmed' +DELETE FROM evm.txes +USING old_enough_receipts, evm.tx_attempts +WHERE evm.tx_attempts.eth_tx_id = evm.txes.id +AND evm.tx_attempts.hash = old_enough_receipts.tx_hash +AND evm.txes.created_at < $3 +AND evm.txes.state = 'confirmed' AND evm_chain_id = $4`, minBlockNumberToKeep, limit, timeThreshold, chainID.String()) if err != nil { - return count, pkgerrors.Wrap(err, "ReapTxes failed to delete old confirmed eth_txes") + return count, pkgerrors.Wrap(err, "ReapTxes failed to delete old confirmed evm.txes") } rowsAffected, err := res.RowsAffected() if err != nil { @@ -1595,17 +1593,17 @@ AND evm_chain_id = $4`, minBlockNumberToKeep, limit, timeThreshold, chainID.Stri return uint(rowsAffected), err }) if err != nil { - return pkgerrors.Wrap(err, "TxmReaper#reapEthTxes batch delete of confirmed eth_txes failed") + return pkgerrors.Wrap(err, "TxmReaper#reapEthTxes batch delete of confirmed evm.txes failed") } - // Delete old 'fatal_error' eth_txes + // Delete old 'fatal_error' evm.txes err = pg.Batch(func(_, limit uint) (count uint, err error) { res, err := o.q.Exec(` -DELETE FROM eth_txes +DELETE FROM evm.txes WHERE created_at < $1 AND state = 'fatal_error' AND evm_chain_id = $2`, timeThreshold, chainID.String()) if err != nil { - return count, pkgerrors.Wrap(err, "ReapTxes failed to delete old fatally errored eth_txes") + return count, pkgerrors.Wrap(err, "ReapTxes failed to delete old fatally errored evm.txes") } rowsAffected, err := res.RowsAffected() if err != nil { @@ -1614,13 +1612,13 @@ AND evm_chain_id = $2`, timeThreshold, chainID.String()) return uint(rowsAffected), err }) if err != nil { - return pkgerrors.Wrap(err, "TxmReaper#reapEthTxes batch delete of fatally errored eth_txes failed") + return pkgerrors.Wrap(err, "TxmReaper#reapEthTxes batch delete of fatally errored evm.txes failed") } return nil } func (o *evmTxStore) Abandon(chainID *big.Int, addr common.Address) error { - _, err := o.q.Exec(`UPDATE eth_txes SET state='fatal_error', nonce = NULL, error = 'abandoned' WHERE state IN ('unconfirmed', 'in_progress', 'unstarted') AND evm_chain_id = $1 AND from_address = $2`, chainID.String(), addr) + _, err := o.q.Exec(`UPDATE evm.txes SET state='fatal_error', nonce = NULL, error = 'abandoned' WHERE state IN ('unconfirmed', 'in_progress', 'unstarted') AND evm_chain_id = $1 AND from_address = $2`, chainID.String(), addr) return err } diff --git a/core/chains/evm/txmgr/evm_tx_store_test.go b/core/chains/evm/txmgr/evm_tx_store_test.go index 777a179be45..0cf2fd83cfd 100644 --- a/core/chains/evm/txmgr/evm_tx_store_test.go +++ b/core/chains/evm/txmgr/evm_tx_store_test.go @@ -55,7 +55,7 @@ func TestORM_TransactionsWithAttempts(t *testing.T) { cltest.MustCreateUnstartedGeneratedTx(t, txStore, from, &cltest.FixtureChainID) var count int - err := db.Get(&count, `SELECT count(*) FROM eth_txes`) + err := db.Get(&count, `SELECT count(*) FROM evm.txes`) require.NoError(t, err) require.Equal(t, 3, count) @@ -100,7 +100,7 @@ func TestORM_Transactions(t *testing.T) { cltest.MustCreateUnstartedGeneratedTx(t, txStore, from, &cltest.FixtureChainID) var count int - err := db.Get(&count, `SELECT count(*) FROM eth_txes`) + err := db.Get(&count, `SELECT count(*) FROM evm.txes`) require.NoError(t, err) require.Equal(t, 3, count) @@ -130,7 +130,7 @@ func TestORM(t *testing.T) { err = orm.InsertTx(&etx) require.NoError(t, err) assert.Greater(t, int(etx.ID), 0) - cltest.AssertCount(t, db, "eth_txes", 1) + cltest.AssertCount(t, db, "evm.txes", 1) }) var attemptL txmgr.TxAttempt var attemptD txmgr.TxAttempt @@ -139,7 +139,7 @@ func TestORM(t *testing.T) { err = orm.InsertTxAttempt(&attemptD) require.NoError(t, err) assert.Greater(t, int(attemptD.ID), 0) - cltest.AssertCount(t, db, "eth_tx_attempts", 1) + cltest.AssertCount(t, db, "evm.tx_attempts", 1) attemptL = cltest.NewLegacyEthTxAttempt(t, etx.ID) attemptL.State = txmgrtypes.TxAttemptBroadcast @@ -147,7 +147,7 @@ func TestORM(t *testing.T) { err = orm.InsertTxAttempt(&attemptL) require.NoError(t, err) assert.Greater(t, int(attemptL.ID), 0) - cltest.AssertCount(t, db, "eth_tx_attempts", 2) + cltest.AssertCount(t, db, "evm.tx_attempts", 2) }) var r txmgr.Receipt t.Run("InsertReceipt", func(t *testing.T) { @@ -156,7 +156,7 @@ func TestORM(t *testing.T) { r.ID = id require.NoError(t, err) assert.Greater(t, int(r.ID), 0) - cltest.AssertCount(t, db, "eth_receipts", 1) + cltest.AssertCount(t, db, "evm.receipts", 1) }) t.Run("FindTxWithAttempts", func(t *testing.T) { etx, err = orm.FindTxWithAttempts(etx.ID) @@ -217,11 +217,11 @@ func TestORM_FindTxAttemptConfirmedByTxIDs(t *testing.T) { cltest.MustInsertUnconfirmedEthTxWithBroadcastLegacyAttempt(t, orm, 4, from) // tx5 var count int - err = db.Get(&count, `SELECT count(*) FROM eth_txes`) + err = db.Get(&count, `SELECT count(*) FROM evm.txes`) require.NoError(t, err) require.Equal(t, 5, count) - err = db.Get(&count, `SELECT count(*) FROM eth_tx_attempts`) + err = db.Get(&count, `SELECT count(*) FROM evm.tx_attempts`) require.NoError(t, err) require.Equal(t, 4, count) @@ -385,7 +385,7 @@ func TestORM_SetBroadcastBeforeBlockNum(t *testing.T) { headNum := int64(9000) var err error - t.Run("saves block num to unconfirmed eth_tx_attempts without one", func(t *testing.T) { + t.Run("saves block num to unconfirmed evm.tx_attempts without one", func(t *testing.T) { // Do the thing require.NoError(t, txStore.SetBroadcastBeforeBlockNum(headNum, chainID)) @@ -397,7 +397,7 @@ func TestORM_SetBroadcastBeforeBlockNum(t *testing.T) { assert.Equal(t, int64(9000), *attempt.BroadcastBeforeBlockNum) }) - t.Run("does not change eth_tx_attempts that already have BroadcastBeforeBlockNum set", func(t *testing.T) { + t.Run("does not change evm.tx_attempts that already have BroadcastBeforeBlockNum set", func(t *testing.T) { n := int64(42) attempt := newBroadcastLegacyEthTxAttempt(t, etx.ID, 2) attempt.BroadcastBeforeBlockNum = &n @@ -414,7 +414,7 @@ func TestORM_SetBroadcastBeforeBlockNum(t *testing.T) { assert.Equal(t, int64(42), *attempt.BroadcastBeforeBlockNum) }) - t.Run("only updates eth_tx_attempts for the current chain", func(t *testing.T) { + t.Run("only updates evm.tx_attempts for the current chain", func(t *testing.T) { require.NoError(t, ethKeyStore.Add(fromAddress, testutils.SimulatedChainID)) require.NoError(t, ethKeyStore.Enable(fromAddress, testutils.SimulatedChainID)) etxThisChain := cltest.MustInsertUnconfirmedEthTxWithBroadcastLegacyAttempt(t, txStore, 1, fromAddress, cfg.DefaultChainID()) @@ -654,11 +654,11 @@ func TestORM_FindReceiptsPendingConfirmation(t *testing.T) { pgtest.MustExec(t, db, `UPDATE pipeline_runs SET state = 'suspended' WHERE id = $1`, run.ID) etx := cltest.MustInsertConfirmedEthTxWithLegacyAttempt(t, txStore, 3, 1, fromAddress) - pgtest.MustExec(t, db, `UPDATE eth_txes SET meta='{"FailOnRevert": true}'`) + pgtest.MustExec(t, db, `UPDATE evm.txes SET meta='{"FailOnRevert": true}'`) attempt := etx.TxAttempts[0] cltest.MustInsertEthReceipt(t, txStore, head.Number-minConfirmations, head.Hash, attempt.Hash) - pgtest.MustExec(t, db, `UPDATE eth_txes SET pipeline_task_run_id = $1, min_confirmations = $2 WHERE id = $3`, &tr.ID, minConfirmations, etx.ID) + pgtest.MustExec(t, db, `UPDATE evm.txes SET pipeline_task_run_id = $1, min_confirmations = $2 WHERE id = $3`, &tr.ID, minConfirmations, etx.ID) receiptsPlus, err := txStore.FindReceiptsPendingConfirmation(testutils.Context(t), head.Number, ethClient.ConfiguredChainID()) require.NoError(t, err) @@ -1021,8 +1021,8 @@ func TestEthConfirmer_FindTxsRequiringResubmissionDueToInsufficientEth(t *testin }) t.Run("does not return confirmed or fatally errored eth_txes", func(t *testing.T) { - pgtest.MustExec(t, db, `UPDATE eth_txes SET state='confirmed' WHERE id = $1`, etx1.ID) - pgtest.MustExec(t, db, `UPDATE eth_txes SET state='fatal_error', nonce=NULL, error='foo', broadcast_at=NULL, initial_broadcast_at=NULL WHERE id = $1`, etx2.ID) + pgtest.MustExec(t, db, `UPDATE evm.txes SET state='confirmed' WHERE id = $1`, etx1.ID) + pgtest.MustExec(t, db, `UPDATE evm.txes SET state='fatal_error', nonce=NULL, error='foo', broadcast_at=NULL, initial_broadcast_at=NULL WHERE id = $1`, etx2.ID) etxs, err := txStore.FindTxsRequiringResubmissionDueToInsufficientFunds(fromAddress, &cltest.FixtureChainID) require.NoError(t, err) @@ -1102,7 +1102,7 @@ func TestORM_LoadEthTxesAttempts(t *testing.T) { newAttempt := cltest.NewDynamicFeeEthTxAttempt(t, etx.ID) dbAttempt := txmgr.DbEthTxAttemptFromEthTxAttempt(&newAttempt) err := q.Transaction(func(tx pg.Queryer) error { - const insertEthTxAttemptSQL = `INSERT INTO eth_tx_attempts (eth_tx_id, gas_price, signed_raw_tx, hash, broadcast_before_block_num, state, created_at, chain_specific_gas_limit, tx_type, gas_tip_cap, gas_fee_cap) VALUES ( + const insertEthTxAttemptSQL = `INSERT INTO evm.tx_attempts (eth_tx_id, gas_price, signed_raw_tx, hash, broadcast_before_block_num, state, created_at, chain_specific_gas_limit, tx_type, gas_tip_cap, gas_fee_cap) VALUES ( :eth_tx_id, :gas_price, :signed_raw_tx, :hash, :broadcast_before_block_num, :state, NOW(), :chain_specific_gas_limit, :tx_type, :gas_tip_cap, :gas_fee_cap ) RETURNING *` _, err := tx.NamedExec(insertEthTxAttemptSQL, dbAttempt) @@ -1262,7 +1262,7 @@ func TestORM_UpdateTxUnstartedToInProgress(t *testing.T) { attempt := cltest.NewLegacyEthTxAttempt(t, etx.ID) - err := q.ExecQ("DELETE FROM eth_txes WHERE id = $1", etx.ID) + err := q.ExecQ("DELETE FROM evm.txes WHERE id = $1", etx.ID) require.NoError(t, err) err = txStore.UpdateTxUnstartedToInProgress(&etx, &attempt) @@ -1574,10 +1574,10 @@ func TestORM_CreateTransaction(t *testing.T) { assert.Equal(t, big.Int(assets.NewEthValue(0)), etx.Value) assert.Equal(t, subject, etx.Subject.UUID) - cltest.AssertCount(t, db, "eth_txes", 1) + cltest.AssertCount(t, db, "evm.txes", 1) var dbEthTx txmgr.DbEthTx - require.NoError(t, db.Get(&dbEthTx, `SELECT * FROM eth_txes ORDER BY id ASC LIMIT 1`)) + require.NoError(t, db.Get(&dbEthTx, `SELECT * FROM evm.txes ORDER BY id ASC LIMIT 1`)) assert.Equal(t, dbEthTx.State, txmgrcommon.TxUnstarted) assert.Equal(t, gasLimit, dbEthTx.GasLimit) diff --git a/core/chains/evm/txmgr/nonce_syncer_test.go b/core/chains/evm/txmgr/nonce_syncer_test.go index 88dc5e22022..05a6d4c8c7b 100644 --- a/core/chains/evm/txmgr/nonce_syncer_test.go +++ b/core/chains/evm/txmgr/nonce_syncer_test.go @@ -42,8 +42,8 @@ func Test_NonceSyncer_Sync(t *testing.T) { require.Error(t, err) assert.Contains(t, err.Error(), "something exploded") - cltest.AssertCount(t, db, "eth_txes", 0) - cltest.AssertCount(t, db, "eth_tx_attempts", 0) + cltest.AssertCount(t, db, "evm.txes", 0) + cltest.AssertCount(t, db, "evm.tx_attempts", 0) assertDatabaseNonce(t, db, from, 0) }) @@ -66,8 +66,8 @@ func Test_NonceSyncer_Sync(t *testing.T) { sendingKeys := cltest.MustSendingKeyStates(t, ethKeyStore, testutils.FixtureChainID) require.NoError(t, ns.Sync(testutils.Context(t), sendingKeys[0].Address.Address())) - cltest.AssertCount(t, db, "eth_txes", 0) - cltest.AssertCount(t, db, "eth_tx_attempts", 0) + cltest.AssertCount(t, db, "evm.txes", 0) + cltest.AssertCount(t, db, "evm.tx_attempts", 0) assertDatabaseNonce(t, db, from, 0) }) @@ -91,8 +91,8 @@ func Test_NonceSyncer_Sync(t *testing.T) { sendingKeys := cltest.MustSendingKeyStates(t, ethKeyStore, testutils.FixtureChainID) require.NoError(t, ns.Sync(testutils.Context(t), sendingKeys[0].Address.Address())) - cltest.AssertCount(t, db, "eth_txes", 0) - cltest.AssertCount(t, db, "eth_tx_attempts", 0) + cltest.AssertCount(t, db, "evm.txes", 0) + cltest.AssertCount(t, db, "evm.tx_attempts", 0) assertDatabaseNonce(t, db, k1.Address, 32) }) @@ -166,7 +166,7 @@ func assertDatabaseNonce(t *testing.T, db *sqlx.DB, address common.Address, nonc t.Helper() var nextNonce int64 - err := db.Get(&nextNonce, `SELECT next_nonce FROM evm_key_states WHERE address = $1`, address) + err := db.Get(&nextNonce, `SELECT next_nonce FROM evm.key_states WHERE address = $1`, address) require.NoError(t, err) assert.Equal(t, nonce, nextNonce) } diff --git a/core/chains/evm/txmgr/reaper_test.go b/core/chains/evm/txmgr/reaper_test.go index 7f32761fa42..11843222999 100644 --- a/core/chains/evm/txmgr/reaper_test.go +++ b/core/chains/evm/txmgr/reaper_test.go @@ -76,7 +76,7 @@ func TestReaper_ReapTxes(t *testing.T) { err := r.ReapTxes(42) assert.NoError(t, err) - cltest.AssertCount(t, db, "eth_txes", 1) + cltest.AssertCount(t, db, "evm.txes", 1) }) t.Run("doesn't touch ethtxes with different chain ID", func(t *testing.T) { @@ -90,10 +90,10 @@ func TestReaper_ReapTxes(t *testing.T) { err := r.ReapTxes(42) assert.NoError(t, err) // Didn't delete because eth_tx has chain ID of 0 - cltest.AssertCount(t, db, "eth_txes", 1) + cltest.AssertCount(t, db, "evm.txes", 1) }) - t.Run("deletes confirmed eth_txes that exceed the age threshold with at least EVM.FinalityDepth blocks above their receipt", func(t *testing.T) { + t.Run("deletes confirmed evm.txes that exceed the age threshold with at least EVM.FinalityDepth blocks above their receipt", func(t *testing.T) { config := txmgrmocks.NewReaperConfig(t) config.On("FinalityDepth").Return(uint32(10)) @@ -104,24 +104,24 @@ func TestReaper_ReapTxes(t *testing.T) { err := r.ReapTxes(42) assert.NoError(t, err) // Didn't delete because eth_tx was not old enough - cltest.AssertCount(t, db, "eth_txes", 1) + cltest.AssertCount(t, db, "evm.txes", 1) - pgtest.MustExec(t, db, `UPDATE eth_txes SET created_at=$1`, oneDayAgo) + pgtest.MustExec(t, db, `UPDATE evm.txes SET created_at=$1`, oneDayAgo) err = r.ReapTxes(12) assert.NoError(t, err) // Didn't delete because eth_tx although old enough, was still within EVM.FinalityDepth of the current head - cltest.AssertCount(t, db, "eth_txes", 1) + cltest.AssertCount(t, db, "evm.txes", 1) err = r.ReapTxes(42) assert.NoError(t, err) // Now it deleted because the eth_tx was past EVM.FinalityDepth - cltest.AssertCount(t, db, "eth_txes", 0) + cltest.AssertCount(t, db, "evm.txes", 0) }) cltest.MustInsertFatalErrorEthTx(t, txStore, from) - t.Run("deletes errored eth_txes that exceed the age threshold", func(t *testing.T) { + t.Run("deletes errored evm.txes that exceed the age threshold", func(t *testing.T) { config := txmgrmocks.NewReaperConfig(t) config.On("FinalityDepth").Return(uint32(10)) @@ -132,13 +132,13 @@ func TestReaper_ReapTxes(t *testing.T) { err := r.ReapTxes(42) assert.NoError(t, err) // Didn't delete because eth_tx was not old enough - cltest.AssertCount(t, db, "eth_txes", 1) + cltest.AssertCount(t, db, "evm.txes", 1) - require.NoError(t, utils.JustError(db.Exec(`UPDATE eth_txes SET created_at=$1`, oneDayAgo))) + require.NoError(t, utils.JustError(db.Exec(`UPDATE evm.txes SET created_at=$1`, oneDayAgo))) err = r.ReapTxes(42) assert.NoError(t, err) // Deleted because it is old enough now - cltest.AssertCount(t, db, "eth_txes", 0) + cltest.AssertCount(t, db, "evm.txes", 0) }) } diff --git a/core/chains/evm/txmgr/resender_test.go b/core/chains/evm/txmgr/resender_test.go index 60b6bcdce20..d17156f4525 100644 --- a/core/chains/evm/txmgr/resender_test.go +++ b/core/chains/evm/txmgr/resender_test.go @@ -187,10 +187,10 @@ func Test_EthResender_Start(t *testing.T) { }() var dbEtx txmgr.DbEthTx - err := db.Get(&dbEtx, `SELECT * FROM eth_txes WHERE id = $1`, etx.ID) + err := db.Get(&dbEtx, `SELECT * FROM evm.txes WHERE id = $1`, etx.ID) require.NoError(t, err) var dbEtx2 txmgr.DbEthTx - err = db.Get(&dbEtx2, `SELECT * FROM eth_txes WHERE id = $1`, etx2.ID) + err = db.Get(&dbEtx2, `SELECT * FROM evm.txes WHERE id = $1`, etx2.ID) require.NoError(t, err) assert.Greater(t, dbEtx.BroadcastAt.Unix(), originalBroadcastAt.Unix()) diff --git a/core/chains/evm/txmgr/txmgr_test.go b/core/chains/evm/txmgr/txmgr_test.go index 854ccd6a4af..79fcf101d5f 100644 --- a/core/chains/evm/txmgr/txmgr_test.go +++ b/core/chains/evm/txmgr/txmgr_test.go @@ -137,10 +137,10 @@ func TestTxm_CreateTransaction(t *testing.T) { assert.Equal(t, big.Int(assets.NewEthValue(0)), etx.Value) assert.Equal(t, subject, etx.Subject.UUID) - cltest.AssertCount(t, db, "eth_txes", 1) + cltest.AssertCount(t, db, "evm.txes", 1) var dbEtx txmgr.DbEthTx - require.NoError(t, db.Get(&dbEtx, `SELECT * FROM eth_txes ORDER BY id ASC LIMIT 1`)) + require.NoError(t, db.Get(&dbEtx, `SELECT * FROM evm.txes ORDER BY id ASC LIMIT 1`)) assert.Equal(t, etx.State, txmgrcommon.TxUnstarted) assert.Equal(t, gasLimit, etx.FeeLimit) @@ -219,7 +219,7 @@ func TestTxm_CreateTransaction(t *testing.T) { }) t.Run("simulate transmit checker", func(t *testing.T) { - pgtest.MustExec(t, db, `DELETE FROM eth_txes`) + pgtest.MustExec(t, db, `DELETE FROM evm.txes`) checker := txmgr.TransmitCheckerSpec{ CheckerType: txmgr.TransmitCheckerTypeSimulate, @@ -234,9 +234,9 @@ func TestTxm_CreateTransaction(t *testing.T) { Checker: checker, }) assert.NoError(t, err) - cltest.AssertCount(t, db, "eth_txes", 1) + cltest.AssertCount(t, db, "evm.txes", 1) var dbEtx txmgr.DbEthTx - require.NoError(t, db.Get(&dbEtx, `SELECT * FROM eth_txes ORDER BY id ASC LIMIT 1`)) + require.NoError(t, db.Get(&dbEtx, `SELECT * FROM evm.txes ORDER BY id ASC LIMIT 1`)) var c txmgr.TransmitCheckerSpec require.NotNil(t, etx.TransmitChecker) @@ -245,7 +245,7 @@ func TestTxm_CreateTransaction(t *testing.T) { }) t.Run("meta and vrf checker", func(t *testing.T) { - pgtest.MustExec(t, db, `DELETE FROM eth_txes`) + pgtest.MustExec(t, db, `DELETE FROM evm.txes`) testDefaultSubID := uint64(2) testDefaultMaxLink := "1000000000000000000" testDefaultMaxEth := "2000000000000000000" @@ -278,9 +278,9 @@ func TestTxm_CreateTransaction(t *testing.T) { Checker: checker, }) assert.NoError(t, err) - cltest.AssertCount(t, db, "eth_txes", 1) + cltest.AssertCount(t, db, "evm.txes", 1) var dbEtx txmgr.DbEthTx - require.NoError(t, db.Get(&dbEtx, `SELECT * FROM eth_txes ORDER BY id ASC LIMIT 1`)) + require.NoError(t, db.Get(&dbEtx, `SELECT * FROM evm.txes ORDER BY id ASC LIMIT 1`)) m, err := etx.GetMeta() require.NoError(t, err) @@ -293,8 +293,8 @@ func TestTxm_CreateTransaction(t *testing.T) { }) t.Run("forwards tx when a proper forwarder is set up", func(t *testing.T) { - pgtest.MustExec(t, db, `DELETE FROM eth_txes`) - pgtest.MustExec(t, db, `DELETE FROM evm_forwarders`) + pgtest.MustExec(t, db, `DELETE FROM evm.txes`) + pgtest.MustExec(t, db, `DELETE FROM evm.forwarders`) evmConfig.maxQueued = uint64(1) // Create mock forwarder, mock authorizedsenders call. @@ -313,10 +313,10 @@ func TestTxm_CreateTransaction(t *testing.T) { Strategy: txmgrcommon.NewSendEveryStrategy(), }) assert.NoError(t, err) - cltest.AssertCount(t, db, "eth_txes", 1) + cltest.AssertCount(t, db, "evm.txes", 1) var dbEtx txmgr.DbEthTx - require.NoError(t, db.Get(&dbEtx, `SELECT * FROM eth_txes ORDER BY id ASC LIMIT 1`)) + require.NoError(t, db.Get(&dbEtx, `SELECT * FROM evm.txes ORDER BY id ASC LIMIT 1`)) m, err := etx.GetMeta() require.NoError(t, err) @@ -550,7 +550,7 @@ func TestTxm_CreateTransaction_OutOfEth(t *testing.T) { require.Equal(t, payload, etx.EncodedPayload) }) - require.NoError(t, utils.JustError(db.Exec(`DELETE FROM eth_txes WHERE from_address = $1`, thisKey.Address))) + require.NoError(t, utils.JustError(db.Exec(`DELETE FROM evm.txes WHERE from_address = $1`, thisKey.Address))) t.Run("if this key has any transactions with insufficient eth errors, inserts it anyway", func(t *testing.T) { payload := cltest.MustRandomBytes(t, 100) @@ -573,7 +573,7 @@ func TestTxm_CreateTransaction_OutOfEth(t *testing.T) { require.Equal(t, payload, etx.EncodedPayload) }) - require.NoError(t, utils.JustError(db.Exec(`DELETE FROM eth_txes WHERE from_address = $1`, thisKey.Address))) + require.NoError(t, utils.JustError(db.Exec(`DELETE FROM evm.txes WHERE from_address = $1`, thisKey.Address))) t.Run("if this key has transactions but no insufficient eth errors, transmits as normal", func(t *testing.T) { payload := cltest.MustRandomBytes(t, 100) @@ -626,7 +626,7 @@ func TestTxm_Lifecycle(t *testing.T) { sub := pgmocks.NewSubscription(t) sub.On("Events").Return(make(<-chan pg.Event)) - eventBroadcaster.On("Subscribe", "insert_on_eth_txes", "").Return(sub, nil) + eventBroadcaster.On("Subscribe", "evm.insert_on_txes", "").Return(sub, nil) evmConfig.bumpThreshold = uint64(1) require.NoError(t, txm.Start(testutils.Context(t))) @@ -695,7 +695,7 @@ func TestTxm_Reset(t *testing.T) { sub := pgmocks.NewSubscription(t) sub.On("Events").Return(make(<-chan pg.Event)) sub.On("Close") - eventBroadcaster.On("Subscribe", "insert_on_eth_txes", "").Return(sub, nil) + eventBroadcaster.On("Subscribe", "evm.insert_on_txes", "").Return(sub, nil) estimator := gas.NewEstimator(logger.TestLogger(t), ethClient, cfg.EVM(), cfg.EVM().GasEstimator()) txm, err := makeTestEvmTxm(t, db, ethClient, estimator, cfg.EVM(), cfg.EVM().GasEstimator(), cfg.EVM().Transactions(), cfg.Database(), cfg.Database().Listener(), kst.Eth(), eventBroadcaster) @@ -728,7 +728,7 @@ func TestTxm_Reset(t *testing.T) { f.AssertCalled(t) }) - t.Run("calls function and deletes relevant eth_txes if abandon=true", func(t *testing.T) { + t.Run("calls function and deletes relevant evm.txes if abandon=true", func(t *testing.T) { f := new(fnMock) err := txm.Reset(f.Fn, addr, true) @@ -737,13 +737,13 @@ func TestTxm_Reset(t *testing.T) { f.AssertCalled(t) var s string - err = db.Get(&s, `SELECT error FROM eth_txes WHERE from_address = $1 AND state = 'fatal_error'`, addr) + err = db.Get(&s, `SELECT error FROM evm.txes WHERE from_address = $1 AND state = 'fatal_error'`, addr) require.NoError(t, err) assert.Equal(t, "abandoned", s) // the other address didn't get touched var count int - err = db.Get(&count, `SELECT count(*) FROM eth_txes WHERE from_address = $1 AND state = 'fatal_error'`, addr2) + err = db.Get(&count, `SELECT count(*) FROM evm.txes WHERE from_address = $1 AND state = 'fatal_error'`, addr2) require.NoError(t, err) assert.Equal(t, 0, count) }) diff --git a/core/cmd/eth_keys_commands_test.go b/core/cmd/eth_keys_commands_test.go index 71dee517b27..da0a9ce5a66 100644 --- a/core/cmd/eth_keys_commands_test.go +++ b/core/cmd/eth_keys_commands_test.go @@ -177,7 +177,7 @@ func TestShell_CreateETHKey(t *testing.T) { db := app.GetSqlxDB() client, _ := app.NewShellAndRenderer() - cltest.AssertCount(t, db, "evm_key_states", 1) // The initial funding key + cltest.AssertCount(t, db, "evm.key_states", 1) // The initial funding key keys, err := app.KeyStore.Eth().GetAll() require.NoError(t, err) require.Equal(t, 1, len(keys)) @@ -200,7 +200,7 @@ func TestShell_CreateETHKey(t *testing.T) { require.NoError(t, set.Parse([]string{"-evmChainID", id.String()})) assert.NoError(t, client.CreateETHKey(c)) - cltest.AssertCount(t, db, "evm_key_states", 3) + cltest.AssertCount(t, db, "evm.key_states", 3) keys, err = app.KeyStore.Eth().GetAll() require.NoError(t, err) require.Equal(t, 3, len(keys)) @@ -304,7 +304,7 @@ func TestShell_ImportExportETHKey_NoChains(t *testing.T) { _, err = ethKeyStore.Get(address) require.Error(t, err) - cltest.AssertCount(t, app.GetSqlxDB(), "evm_key_states", 0) + cltest.AssertCount(t, app.GetSqlxDB(), "evm.key_states", 0) // Import the key set = flag.NewFlagSet("test", 0) diff --git a/core/cmd/evm_transaction_commands_test.go b/core/cmd/evm_transaction_commands_test.go index e1dcb5ec3bb..67e4da03752 100644 --- a/core/cmd/evm_transaction_commands_test.go +++ b/core/cmd/evm_transaction_commands_test.go @@ -167,7 +167,7 @@ func TestShell_SendEther_From_Txm(t *testing.T) { assert.NoError(t, client.SendEther(c)) dbEvmTx := txmgr.DbEthTx{} - require.NoError(t, db.Get(&dbEvmTx, `SELECT * FROM eth_txes`)) + require.NoError(t, db.Get(&dbEvmTx, `SELECT * FROM evm.txes`)) require.Equal(t, "100.500000000000000000", dbEvmTx.Value.String()) require.Equal(t, fromAddress, dbEvmTx.FromAddress) require.Equal(t, to, dbEvmTx.ToAddress.String()) @@ -179,7 +179,7 @@ func TestShell_SendEther_From_Txm(t *testing.T) { assert.Equal(t, fmt.Sprintf("%d", *dbEvmTx.Nonce), output.Nonce) dbEvmTxAttempt := txmgr.DbEthTxAttempt{} - require.NoError(t, db.Get(&dbEvmTxAttempt, `SELECT * FROM eth_tx_attempts`)) + require.NoError(t, db.Get(&dbEvmTxAttempt, `SELECT * FROM evm.tx_attempts`)) assert.Equal(t, dbEvmTxAttempt.Hash, output.Hash) } @@ -231,7 +231,7 @@ func TestShell_SendEther_From_Txm_WEI(t *testing.T) { assert.NoError(t, client.SendEther(c)) dbEvmTx := txmgr.DbEthTx{} - require.NoError(t, db.Get(&dbEvmTx, `SELECT * FROM eth_txes`)) + require.NoError(t, db.Get(&dbEvmTx, `SELECT * FROM evm.txes`)) require.Equal(t, "1.000000000000000000", dbEvmTx.Value.String()) require.Equal(t, fromAddress, dbEvmTx.FromAddress) require.Equal(t, to, dbEvmTx.ToAddress.String()) @@ -243,6 +243,6 @@ func TestShell_SendEther_From_Txm_WEI(t *testing.T) { assert.Equal(t, fmt.Sprintf("%d", *dbEvmTx.Nonce), output.Nonce) dbEvmTxAttempt := txmgr.DbEthTxAttempt{} - require.NoError(t, db.Get(&dbEvmTxAttempt, `SELECT * FROM eth_tx_attempts`)) + require.NoError(t, db.Get(&dbEvmTxAttempt, `SELECT * FROM evm.tx_attempts`)) assert.Equal(t, dbEvmTxAttempt.Hash, output.Hash) } diff --git a/core/internal/cltest/cltest.go b/core/internal/cltest/cltest.go index 63c1f49a664..e7a95d6254a 100644 --- a/core/internal/cltest/cltest.go +++ b/core/internal/cltest/cltest.go @@ -983,7 +983,7 @@ func AssertEthTxAttemptCountStays(t testing.TB, db *sqlx.DB, want int) []int64 { var err error g.Consistently(func() []int64 { txaIds = make([]int64, 0) - err = db.Select(&txaIds, `SELECT ID FROM eth_tx_attempts ORDER BY id ASC`) + err = db.Select(&txaIds, `SELECT ID FROM evm.tx_attempts ORDER BY id ASC`) assert.NoError(t, err) return txaIds }, AssertNoActionTimeout, DBPollingInterval).Should(gomega.HaveLen(want)) @@ -1536,7 +1536,7 @@ func AssertCountStays(t testing.TB, db *sqlx.DB, tableName string, want int64) { var count int64 var err error g.Consistently(func() int64 { - err = db.Get(&count, fmt.Sprintf(`SELECT count(*) FROM %q`, tableName)) + err = db.Get(&count, fmt.Sprintf(`SELECT count(*) FROM %s`, tableName)) assert.NoError(t, err) return count }, AssertNoActionTimeout, DBPollingInterval).Should(gomega.Equal(want)) diff --git a/core/internal/cltest/factories.go b/core/internal/cltest/factories.go index bfa479af624..f4b154218a6 100644 --- a/core/internal/cltest/factories.go +++ b/core/internal/cltest/factories.go @@ -443,7 +443,7 @@ func MustInsertRevertedEthReceipt(t *testing.T, txStore txmgr.TestEvmTxStore, bl return r } -// Inserts into eth_receipts but does not update eth_txes or eth_tx_attempts +// Inserts into evm.receipts but does not update evm.txes or evm.tx_attempts func MustInsertConfirmedEthTxWithReceipt(t *testing.T, txStore txmgr.TestEvmTxStore, fromAddress common.Address, nonce, blockNum int64) (etx txmgr.Tx) { etx = MustInsertConfirmedEthTxWithLegacyAttempt(t, txStore, nonce, blockNum, fromAddress) MustInsertEthReceipt(t, txStore, blockNum, utils.NewHash(), etx.TxAttempts[0].Hash) diff --git a/core/internal/testutils/testutils.go b/core/internal/testutils/testutils.go index 447475251c4..d50efcc799a 100644 --- a/core/internal/testutils/testutils.go +++ b/core/internal/testutils/testutils.go @@ -427,7 +427,7 @@ func AssertCount(t *testing.T, db *sqlx.DB, tableName string, expected int64) { func AssertCountPerSubject(t *testing.T, db *sqlx.DB, expected int64, subject uuid.UUID) { t.Helper() var count int64 - err := db.Get(&count, `SELECT COUNT(*) FROM eth_txes + err := db.Get(&count, `SELECT COUNT(*) FROM evm.txes WHERE state = 'unstarted' AND subject = $1;`, subject) require.NoError(t, err) require.Equal(t, expected, count) diff --git a/core/services/keeper/upkeep_executer_test.go b/core/services/keeper/upkeep_executer_test.go index c971152df3a..70982d7b7ce 100644 --- a/core/services/keeper/upkeep_executer_test.go +++ b/core/services/keeper/upkeep_executer_test.go @@ -316,7 +316,7 @@ func Test_UpkeepExecuter_PerformsUpkeep_Error(t *testing.T) { executer.OnNewLongestChain(testutils.Context(t), &head) g.Eventually(wasCalled.Load).Should(gomega.Equal(true)) - cltest.AssertCountStays(t, db, "eth_txes", 0) + cltest.AssertCountStays(t, db, "evm.txes", 0) } func ptr[T any](t T) *T { return &t } diff --git a/core/services/keystore/eth.go b/core/services/keystore/eth.go index ca776cf10e1..9909f398bf4 100644 --- a/core/services/keystore/eth.go +++ b/core/services/keystore/eth.go @@ -240,7 +240,7 @@ func (ks *eth) Add(address common.Address, chainID *big.Int, qopts ...pg.QOpt) e // caller must hold lock! func (ks *eth) addKey(address common.Address, chainID *big.Int, qopts ...pg.QOpt) error { state := new(ethkey.State) - sql := `INSERT INTO evm_key_states (address, next_nonce, disabled, evm_chain_id, created_at, updated_at) + sql := `INSERT INTO evm.key_states (address, next_nonce, disabled, evm_chain_id, created_at, updated_at) VALUES ($1, 0, false, $2, NOW(), NOW()) RETURNING *;` q := ks.orm.q.WithOpts(qopts...) @@ -267,7 +267,7 @@ func (ks *eth) Enable(address common.Address, chainID *big.Int, qopts ...pg.QOpt func (ks *eth) enable(address common.Address, chainID *big.Int, qopts ...pg.QOpt) error { state := new(ethkey.State) q := ks.orm.q.WithOpts(qopts...) - sql := `UPDATE evm_key_states SET disabled = false, updated_at = NOW() WHERE address = $1 AND evm_chain_id = $2 + sql := `UPDATE evm.key_states SET disabled = false, updated_at = NOW() WHERE address = $1 AND evm_chain_id = $2 RETURNING *;` if err := q.Get(state, sql, address, chainID.String()); err != nil { return errors.Wrap(err, "failed to enable state") @@ -291,7 +291,7 @@ func (ks *eth) Disable(address common.Address, chainID *big.Int, qopts ...pg.QOp func (ks *eth) disable(address common.Address, chainID *big.Int, qopts ...pg.QOpt) error { state := new(ethkey.State) q := ks.orm.q.WithOpts(qopts...) - sql := `UPDATE evm_key_states SET disabled = false, updated_at = NOW() WHERE address = $1 AND evm_chain_id = $2 + sql := `UPDATE evm.key_states SET disabled = false, updated_at = NOW() WHERE address = $1 AND evm_chain_id = $2 RETURNING id, next_nonce, address, evm_chain_id, disabled, created_at, updated_at;` if err := q.Get(state, sql, address, chainID.String()); err != nil { return errors.Wrap(err, "failed to enable state") @@ -305,7 +305,7 @@ func (ks *eth) disable(address common.Address, chainID *big.Int, qopts ...pg.QOp // Reset the key/chain nonce to the given one func (ks *eth) Reset(address common.Address, chainID *big.Int, nonce int64, qopts ...pg.QOpt) error { q := ks.orm.q.WithOpts(qopts...) - res, err := q.Exec(`UPDATE evm_key_states SET next_nonce = $1 WHERE address = $2 AND evm_chain_id = $3`, nonce, address, chainID.String()) + res, err := q.Exec(`UPDATE evm.key_states SET next_nonce = $1 WHERE address = $2 AND evm_chain_id = $3`, nonce, address, chainID.String()) if err != nil { return errors.Wrap(err, "failed to reset state") } @@ -337,7 +337,7 @@ func (ks *eth) Delete(id string) (ethkey.KeyV2, error) { return ethkey.KeyV2{}, err } err = ks.safeRemoveKey(key, func(tx pg.Queryer) error { - _, err2 := tx.Exec(`DELETE FROM evm_key_states WHERE address = $1`, key.Address) + _, err2 := tx.Exec(`DELETE FROM evm.key_states WHERE address = $1`, key.Address) return err2 }) if err != nil { @@ -587,7 +587,7 @@ func (ks *eth) XXXTestingOnlySetState(state ethkey.State) { panic(fmt.Sprintf("key not found with ID %s", state.KeyID())) } *existingState = state - sql := `UPDATE evm_key_states SET address = :address, next_nonce = :next_nonce, is_disabled = :is_disabled, evm_chain_id = :evm_chain_id, updated_at = NOW() + sql := `UPDATE evm.key_states SET address = :address, next_nonce = :next_nonce, is_disabled = :is_disabled, evm_chain_id = :evm_chain_id, updated_at = NOW() WHERE address = :address;` _, err := ks.orm.q.NamedExec(sql, state) if err != nil { @@ -669,7 +669,7 @@ func (ks *eth) addWithNonce(key ethkey.KeyV2, chainID *big.Int, nonce int64, isD defer ks.lock.Unlock() err = ks.safeAddKey(key, func(tx pg.Queryer) (merr error) { state := new(ethkey.State) - sql := `INSERT INTO evm_key_states (address, next_nonce, disabled, evm_chain_id, created_at, updated_at) + sql := `INSERT INTO evm.key_states (address, next_nonce, disabled, evm_chain_id, created_at, updated_at) VALUES ($1, $2, $3, $4, NOW(), NOW()) RETURNING *;` if err = ks.orm.q.Get(state, sql, key.Address, nonce, isDisabled, chainID); err != nil { return errors.Wrap(err, "failed to insert evm_key_state") diff --git a/core/services/keystore/eth_test.go b/core/services/keystore/eth_test.go index 678f11ea503..78131bec133 100644 --- a/core/services/keystore/eth_test.go +++ b/core/services/keystore/eth_test.go @@ -38,10 +38,10 @@ func Test_EthKeyStore(t *testing.T) { reset := func() { keyStore.ResetXXXTestOnly() require.NoError(t, utils.JustError(db.Exec("DELETE FROM encrypted_key_rings"))) - require.NoError(t, utils.JustError(db.Exec("DELETE FROM evm_key_states"))) + require.NoError(t, utils.JustError(db.Exec("DELETE FROM evm.key_states"))) require.NoError(t, keyStore.Unlock(cltest.Password)) } - const statesTableName = "evm_key_states" + const statesTableName = "evm.key_states" t.Run("Create / GetAll / Get", func(t *testing.T) { defer reset() @@ -104,7 +104,7 @@ func Test_EthKeyStore(t *testing.T) { cltest.AssertCount(t, db, statesTableName, 0) }) - t.Run("Delete removes key even if eth_txes are present", func(t *testing.T) { + t.Run("Delete removes key even if evm.txes are present", func(t *testing.T) { defer reset() key, err := ethKeyStore.Create(&cltest.FixtureChainID) require.NoError(t, err) @@ -170,7 +170,7 @@ func Test_EthKeyStore(t *testing.T) { require.NoError(t, err) key2, err := ethKeyStore.Create(big.NewInt(1337)) require.NoError(t, err) - testutils.AssertCount(t, db, "evm_key_states", 2) + testutils.AssertCount(t, db, "evm.key_states", 2) keys, err := ethKeyStore.GetAll() require.NoError(t, err) assert.Len(t, keys, 2) @@ -363,7 +363,7 @@ func Test_EthKeyStore_E2E(t *testing.T) { reset := func() { keyStore.ResetXXXTestOnly() require.NoError(t, utils.JustError(db.Exec("DELETE FROM encrypted_key_rings"))) - require.NoError(t, utils.JustError(db.Exec("DELETE FROM evm_key_states"))) + require.NoError(t, utils.JustError(db.Exec("DELETE FROM evm.key_states"))) require.NoError(t, keyStore.Unlock(cltest.Password)) } @@ -552,10 +552,10 @@ func Test_EthKeyStore_EnsureKeys(t *testing.T) { keyStore := cltest.NewKeyStore(t, db, cfg.Database()) ks := keyStore.Eth() - testutils.AssertCount(t, db, "evm_key_states", 0) + testutils.AssertCount(t, db, "evm.key_states", 0) err := ks.EnsureKeys(testutils.FixtureChainID, testutils.SimulatedChainID) require.NoError(t, err) - testutils.AssertCount(t, db, "evm_key_states", 2) + testutils.AssertCount(t, db, "evm.key_states", 2) keys, err := ks.GetAll() require.NoError(t, err) assert.Len(t, keys, 2) @@ -570,7 +570,7 @@ func Test_EthKeyStore_EnsureKeys(t *testing.T) { // Add one enabled key _, err := ks.Create(testutils.FixtureChainID) require.NoError(t, err) - testutils.AssertCount(t, db, "evm_key_states", 1) + testutils.AssertCount(t, db, "evm.key_states", 1) keys, err := ks.GetAll() require.NoError(t, err) assert.Len(t, keys, 1) @@ -578,7 +578,7 @@ func Test_EthKeyStore_EnsureKeys(t *testing.T) { // this adds one more key for the additional chain err = ks.EnsureKeys(testutils.FixtureChainID, testutils.SimulatedChainID) require.NoError(t, err) - testutils.AssertCount(t, db, "evm_key_states", 2) + testutils.AssertCount(t, db, "evm.key_states", 2) keys, err = ks.GetAll() require.NoError(t, err) assert.Len(t, keys, 2) @@ -593,7 +593,7 @@ func Test_EthKeyStore_EnsureKeys(t *testing.T) { // Add one enabled key k, err := ks.Create(testutils.FixtureChainID) require.NoError(t, err) - testutils.AssertCount(t, db, "evm_key_states", 1) + testutils.AssertCount(t, db, "evm.key_states", 1) keys, err := ks.GetAll() require.NoError(t, err) assert.Len(t, keys, 1) @@ -605,7 +605,7 @@ func Test_EthKeyStore_EnsureKeys(t *testing.T) { // this does nothing err = ks.EnsureKeys(testutils.FixtureChainID) require.NoError(t, err) - testutils.AssertCount(t, db, "evm_key_states", 1) + testutils.AssertCount(t, db, "evm.key_states", 1) keys, err = ks.GetAll() require.NoError(t, err) assert.Len(t, keys, 1) @@ -728,7 +728,7 @@ func Test_IncrementNextSequence(t *testing.T) { err = ks.IncrementNextSequence(evmAddr1, testutils.FixtureChainID, evmtypes.Nonce(randNonce)) require.NoError(t, err) var nonce int64 - require.NoError(t, db.Get(&nonce, `SELECT next_nonce FROM evm_key_states WHERE address = $1 AND evm_chain_id = $2`, addr1, testutils.FixtureChainID.String())) + require.NoError(t, db.Get(&nonce, `SELECT next_nonce FROM evm.key_states WHERE address = $1 AND evm_chain_id = $2`, addr1, testutils.FixtureChainID.String())) assert.Equal(t, randNonce+1, nonce) err = ks.IncrementNextSequence(evmAddr1, testutils.SimulatedChainID, evmtypes.Nonce(randNonce+1)) @@ -745,7 +745,7 @@ func Test_IncrementNextSequence(t *testing.T) { assert.Contains(t, err.Error(), fmt.Sprintf("key with address %s does not exist", randAddr2.Hex())) // verify it didnt get changed by any erroring calls - require.NoError(t, db.Get(&nonce, `SELECT next_nonce FROM evm_key_states WHERE address = $1 AND evm_chain_id = $2`, addr1, testutils.FixtureChainID.String())) + require.NoError(t, db.Get(&nonce, `SELECT next_nonce FROM evm.key_states WHERE address = $1 AND evm_chain_id = $2`, addr1, testutils.FixtureChainID.String())) assert.Equal(t, randNonce+1, nonce) } @@ -768,7 +768,7 @@ func Test_EthKeyStore_Delete(t *testing.T) { require.NoError(t, ks.Add(addr1, testutils.SimulatedChainID)) require.NoError(t, ks.Enable(addr1, testutils.SimulatedChainID)) - testutils.AssertCount(t, db, "evm_key_states", 4) + testutils.AssertCount(t, db, "evm.key_states", 4) keys, err := ks.GetAll() require.NoError(t, err) assert.Len(t, keys, 3) @@ -781,7 +781,7 @@ func Test_EthKeyStore_Delete(t *testing.T) { require.NoError(t, err) assert.Equal(t, addr1, deletedK.Address) - testutils.AssertCount(t, db, "evm_key_states", 2) + testutils.AssertCount(t, db, "evm.key_states", 2) keys, err = ks.GetAll() require.NoError(t, err) assert.Len(t, keys, 2) diff --git a/core/services/keystore/orm.go b/core/services/keystore/orm.go index d71b8378532..1396b544205 100644 --- a/core/services/keystore/orm.go +++ b/core/services/keystore/orm.go @@ -67,8 +67,8 @@ func (orm ksORM) getEncryptedKeyRing() (kr encryptedKeyRing, err error) { func (orm ksORM) loadKeyStates() (*keyStates, error) { ks := newKeyStates() var ethkeystates []*ethkey.State - if err := orm.q.Select(ðkeystates, `SELECT id, address, evm_chain_id, next_nonce, disabled, created_at, updated_at FROM evm_key_states`); err != nil { - return ks, errors.Wrap(err, "error loading evm_key_states from DB") + if err := orm.q.Select(ðkeystates, `SELECT id, address, evm_chain_id, next_nonce, disabled, created_at, updated_at FROM evm.key_states`); err != nil { + return ks, errors.Wrap(err, "error loading evm.key_states from DB") } for _, state := range ethkeystates { ks.add(state) @@ -76,20 +76,20 @@ func (orm ksORM) loadKeyStates() (*keyStates, error) { return ks, nil } -// getNextNonce returns evm_key_states.next_nonce for the given address +// getNextNonce returns evm.key_states.next_nonce for the given address func (orm ksORM) getNextNonce(address common.Address, chainID *big.Int, qopts ...pg.QOpt) (nonce int64, err error) { q := orm.q.WithOpts(qopts...) - err = q.Get(&nonce, "SELECT next_nonce FROM evm_key_states WHERE address = $1 AND evm_chain_id = $2 AND disabled = false", address, chainID.String()) + err = q.Get(&nonce, "SELECT next_nonce FROM evm.key_states WHERE address = $1 AND evm_chain_id = $2 AND disabled = false", address, chainID.String()) if errors.Is(err, sql.ErrNoRows) { return 0, errors.Wrapf(sql.ErrNoRows, "key with address %s is not enabled for chain %s", address.Hex(), chainID.String()) } return nonce, errors.Wrap(err, "failed to load next nonce") } -// incrementNextNonce increments evm_key_states.next_nonce by 1 +// incrementNextNonce increments evm.key_states.next_nonce by 1 func (orm ksORM) incrementNextNonce(address common.Address, chainID *big.Int, currentNonce int64, qopts ...pg.QOpt) (incrementedNonce int64, err error) { q := orm.q.WithOpts(qopts...) - err = q.Get(&incrementedNonce, "UPDATE evm_key_states SET next_nonce = next_nonce + 1, updated_at = NOW() WHERE address = $1 AND next_nonce = $2 AND evm_chain_id = $3 AND disabled = false RETURNING next_nonce", address, currentNonce, chainID.String()) + err = q.Get(&incrementedNonce, "UPDATE evm.key_states SET next_nonce = next_nonce + 1, updated_at = NOW() WHERE address = $1 AND next_nonce = $2 AND evm_chain_id = $3 AND disabled = false RETURNING next_nonce", address, currentNonce, chainID.String()) return incrementedNonce, errors.Wrap(err, "IncrementNextNonce failed to update keys") } diff --git a/core/services/ocr2/plugins/ocr2keeper/evm21/upkeepstate/orm.go b/core/services/ocr2/plugins/ocr2keeper/evm21/upkeepstate/orm.go index d441b71819e..5db2f8bd0f3 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evm21/upkeepstate/orm.go +++ b/core/services/ocr2/plugins/ocr2keeper/evm21/upkeepstate/orm.go @@ -65,7 +65,7 @@ func (o *orm) BatchInsertRecords(state []persistedStateRecord, qopts ...pg.QOpt) }) } - return q.ExecQNamed(`INSERT INTO evm_upkeep_states + return q.ExecQNamed(`INSERT INTO evm.upkeep_states (evm_chain_id, work_id, completion_state, block_number, inserted_at, upkeep_id, ineligibility_reason) VALUES (:evm_chain_id, :work_id, :completion_state, :block_number, :inserted_at, :upkeep_id, :ineligibility_reason) ON CONFLICT (evm_chain_id, work_id) DO NOTHING`, rows) } @@ -76,7 +76,7 @@ func (o *orm) SelectStatesByWorkIDs(workIDs []string, qopts ...pg.QOpt) (states q := o.q.WithOpts(qopts...) err = q.Select(&states, `SELECT upkeep_id, work_id, completion_state, block_number, ineligibility_reason, inserted_at - FROM evm_upkeep_states + FROM evm.upkeep_states WHERE work_id = ANY($1) AND evm_chain_id = $2::NUMERIC`, pq.Array(workIDs), o.chainID) if err != nil { @@ -89,7 +89,7 @@ func (o *orm) SelectStatesByWorkIDs(workIDs []string, qopts ...pg.QOpt) (states // DeleteExpired prunes stored states older than to the provided time func (o *orm) DeleteExpired(expired time.Time, qopts ...pg.QOpt) error { q := o.q.WithOpts(qopts...) - _, err := q.Exec(`DELETE FROM evm_upkeep_states WHERE inserted_at <= $1 AND evm_chain_id::NUMERIC = $2`, expired, o.chainID) + _, err := q.Exec(`DELETE FROM evm.upkeep_states WHERE inserted_at <= $1 AND evm_chain_id::NUMERIC = $2`, expired, o.chainID) return err } diff --git a/core/services/ocr2/plugins/ocr2keeper/evm21/upkeepstate/store_test.go b/core/services/ocr2/plugins/ocr2keeper/evm21/upkeepstate/store_test.go index cc4f6d0a23f..49851b584e8 100644 --- a/core/services/ocr2/plugins/ocr2keeper/evm21/upkeepstate/store_test.go +++ b/core/services/ocr2/plugins/ocr2keeper/evm21/upkeepstate/store_test.go @@ -350,7 +350,7 @@ func TestUpkeepStateStore_SetSelectIntegration(t *testing.T) { t.Cleanup(func() { t.Log("cleaning up database") - if _, err := db.Exec(`DELETE FROM evm_upkeep_states`); err != nil { + if _, err := db.Exec(`DELETE FROM evm.upkeep_states`); err != nil { t.Logf("error in cleanup: %s", err) } }) diff --git a/core/services/pg/channels.go b/core/services/pg/channels.go index 7b0b768bdab..93213a2be19 100644 --- a/core/services/pg/channels.go +++ b/core/services/pg/channels.go @@ -1,8 +1,8 @@ package pg -// Postgres channel to listen for new eth_txes +// Postgres channel to listen for new evm.txes const ( - ChannelInsertOnTx = "insert_on_eth_txes" + ChannelInsertOnTx = "evm.insert_on_txes" ChannelInsertOnCosmosMsg = "insert_on_cosmos_msg" ChannelInsertOnEVMLogs = "insert_on_evm_logs" ) diff --git a/core/services/promreporter/prom_reporter.go b/core/services/promreporter/prom_reporter.go index 508e424c3b0..c0b48b46e3a 100644 --- a/core/services/promreporter/prom_reporter.go +++ b/core/services/promreporter/prom_reporter.go @@ -176,7 +176,7 @@ func (pr *promReporter) reportHeadMetrics(ctx context.Context, head *evmtypes.He func (pr *promReporter) reportPendingEthTxes(ctx context.Context, evmChainID *big.Int) (err error) { var unconfirmed int64 - if err := pr.db.QueryRowContext(ctx, `SELECT count(*) FROM eth_txes WHERE state = 'unconfirmed' AND evm_chain_id = $1`, evmChainID.String()).Scan(&unconfirmed); err != nil { + if err := pr.db.QueryRowContext(ctx, `SELECT count(*) FROM evm.txes WHERE state = 'unconfirmed' AND evm_chain_id = $1`, evmChainID.String()).Scan(&unconfirmed); err != nil { return errors.Wrap(err, "failed to query for unconfirmed eth_tx count") } pr.backend.SetUnconfirmedTransactions(evmChainID, unconfirmed) @@ -186,7 +186,7 @@ func (pr *promReporter) reportPendingEthTxes(ctx context.Context, evmChainID *bi func (pr *promReporter) reportMaxUnconfirmedAge(ctx context.Context, evmChainID *big.Int) (err error) { var broadcastAt null.Time now := time.Now() - if err := pr.db.QueryRowContext(ctx, `SELECT min(initial_broadcast_at) FROM eth_txes WHERE state = 'unconfirmed' AND evm_chain_id = $1`, evmChainID.String()).Scan(&broadcastAt); err != nil { + if err := pr.db.QueryRowContext(ctx, `SELECT min(initial_broadcast_at) FROM evm.txes WHERE state = 'unconfirmed' AND evm_chain_id = $1`, evmChainID.String()).Scan(&broadcastAt); err != nil { return errors.Wrap(err, "failed to query for unconfirmed eth_tx count") } var seconds float64 @@ -201,11 +201,11 @@ func (pr *promReporter) reportMaxUnconfirmedAge(ctx context.Context, evmChainID func (pr *promReporter) reportMaxUnconfirmedBlocks(ctx context.Context, head *evmtypes.Head) (err error) { var earliestUnconfirmedTxBlock null.Int err = pr.db.QueryRowContext(ctx, ` -SELECT MIN(broadcast_before_block_num) FROM eth_tx_attempts -JOIN eth_txes ON eth_txes.id = eth_tx_attempts.eth_tx_id -WHERE eth_txes.state = 'unconfirmed' +SELECT MIN(broadcast_before_block_num) FROM evm.tx_attempts +JOIN evm.txes ON evm.txes.id = evm.tx_attempts.eth_tx_id +WHERE evm.txes.state = 'unconfirmed' AND evm_chain_id = $1 -AND eth_txes.state = 'unconfirmed'`, head.EVMChainID.String()).Scan(&earliestUnconfirmedTxBlock) +AND evm.txes.state = 'unconfirmed'`, head.EVMChainID.String()).Scan(&earliestUnconfirmedTxBlock) if err != nil { return errors.Wrap(err, "failed to query for min broadcast_before_block_num") } diff --git a/core/services/promreporter/prom_reporter_test.go b/core/services/promreporter/prom_reporter_test.go index 62fbef64ea9..9629045cb0b 100644 --- a/core/services/promreporter/prom_reporter_test.go +++ b/core/services/promreporter/prom_reporter_test.go @@ -54,7 +54,7 @@ func Test_PromReporter_OnNewLongestChain(t *testing.T) { require.Eventually(t, func() bool { return subscribeCalls.Load() >= 1 }, 12*time.Second, 100*time.Millisecond) }) - t.Run("with unconfirmed eth_txes", func(t *testing.T) { + t.Run("with unconfirmed evm.txes", func(t *testing.T) { db := pgtest.NewSqlxDB(t) cfg := configtest.NewGeneralConfig(t, nil) txStore := cltest.NewTestTxStore(t, db, cfg.Database()) @@ -82,7 +82,7 @@ func Test_PromReporter_OnNewLongestChain(t *testing.T) { etx := cltest.MustInsertUnconfirmedEthTxWithBroadcastLegacyAttempt(t, txStore, 0, fromAddress) cltest.MustInsertUnconfirmedEthTxWithBroadcastLegacyAttempt(t, txStore, 1, fromAddress) cltest.MustInsertUnconfirmedEthTxWithBroadcastLegacyAttempt(t, txStore, 2, fromAddress) - require.NoError(t, utils.JustError(db.Exec(`UPDATE eth_tx_attempts SET broadcast_before_block_num = 7 WHERE eth_tx_id = $1`, etx.ID))) + require.NoError(t, utils.JustError(db.Exec(`UPDATE evm.tx_attempts SET broadcast_before_block_num = 7 WHERE eth_tx_id = $1`, etx.ID))) head := newHead() reporter.OnNewLongestChain(testutils.Context(t), &head) diff --git a/core/services/vrf/delegate.go b/core/services/vrf/delegate.go index 733c21b45a7..cc6c05cacdd 100644 --- a/core/services/vrf/delegate.go +++ b/core/services/vrf/delegate.go @@ -367,24 +367,24 @@ func getRespCounts(q pg.Q, chainID uint64, evmFinalityDepth uint32) ( RequestID string Count int }{} - // This query should use the idx_eth_txes_state_from_address_evm_chain_id + // This query should use the idx_evm.txes_state_from_address_evm_chain_id // index, since the quantity of unconfirmed/unstarted/in_progress transactions _should_ be small // relative to the rest of the data. unconfirmedQuery := ` SELECT meta->'RequestID' AS request_id, count(meta->'RequestID') AS count -FROM eth_txes et +FROM evm.txes et WHERE et.meta->'RequestID' IS NOT NULL AND et.state IN ('unconfirmed', 'unstarted', 'in_progress') GROUP BY meta->'RequestID' ` // Fetch completed transactions only as far back as the given cutoffBlockNumber. This avoids - // a table scan of the eth_txes table, which could be large if it is unpruned. + // a table scan of the evm.txes table, which could be large if it is unpruned. confirmedQuery := ` SELECT meta->'RequestID' AS request_id, count(meta->'RequestID') AS count -FROM eth_txes et JOIN eth_tx_attempts eta on et.id = eta.eth_tx_id - join eth_receipts er on eta.hash = er.tx_hash +FROM evm.txes et JOIN evm.tx_attempts eta on et.id = eta.eth_tx_id + join evm.receipts er on eta.hash = er.tx_hash WHERE et.meta->'RequestID' is not null -AND er.block_number >= (SELECT number FROM evm_heads WHERE evm_chain_id = $1 ORDER BY number DESC LIMIT 1) - $2 +AND er.block_number >= (SELECT number FROM evm.heads WHERE evm_chain_id = $1 ORDER BY number DESC LIMIT 1) - $2 GROUP BY meta->'RequestID' ` query := unconfirmedQuery + "\nUNION ALL\n" + confirmedQuery diff --git a/core/services/vrf/delegate_test.go b/core/services/vrf/delegate_test.go index b26e5511c16..1541c80a400 100644 --- a/core/services/vrf/delegate_test.go +++ b/core/services/vrf/delegate_test.go @@ -413,7 +413,7 @@ func TestDelegate_InvalidLog(t *testing.T) { // Ensure we have NOT queued up an eth transaction var ethTxes []txmgr.DbEthTx - err = vuni.prm.GetQ().Select(ðTxes, `SELECT * FROM eth_txes;`) + err = vuni.prm.GetQ().Select(ðTxes, `SELECT * FROM evm.txes;`) require.NoError(t, err) require.Len(t, ethTxes, 0) } diff --git a/core/services/vrf/v2/integration_v2_test.go b/core/services/vrf/v2/integration_v2_test.go index e7f11f1c6b7..40622b84594 100644 --- a/core/services/vrf/v2/integration_v2_test.go +++ b/core/services/vrf/v2/integration_v2_test.go @@ -128,22 +128,22 @@ type coordinatorV2Universe struct { } const ( - ConfirmedEthTxesV2Query = `SELECT * FROM eth_txes - WHERE eth_txes.state = 'confirmed' - AND eth_txes.meta->>'RequestID' = $1 - AND CAST(eth_txes.meta->>'SubId' AS NUMERIC) = $2 LIMIT 1` - ConfirmedEthTxesV2PlusQuery = `SELECT * FROM eth_txes - WHERE eth_txes.state = 'confirmed' - AND eth_txes.meta->>'RequestID' = $1 - AND CAST(eth_txes.meta->>'GlobalSubId' AS NUMERIC) = $2 LIMIT 1` + ConfirmedEthTxesV2Query = `SELECT * FROM evm.txes + WHERE evm.txes.state = 'confirmed' + AND evm.txes.meta->>'RequestID' = $1 + AND CAST(evm.txes.meta->>'SubId' AS NUMERIC) = $2 LIMIT 1` + ConfirmedEthTxesV2PlusQuery = `SELECT * FROM evm.txes + WHERE evm.txes.state = 'confirmed' + AND evm.txes.meta->>'RequestID' = $1 + AND CAST(evm.txes.meta->>'GlobalSubId' AS NUMERIC) = $2 LIMIT 1` ConfirmedEthTxesV2BatchQuery = ` - SELECT * FROM eth_txes - WHERE eth_txes.state = 'confirmed' - AND CAST(eth_txes.meta->>'SubId' AS NUMERIC) = $1` + SELECT * FROM evm.txes + WHERE evm.txes.state = 'confirmed' + AND CAST(evm.txes.meta->>'SubId' AS NUMERIC) = $1` ConfirmedEthTxesV2PlusBatchQuery = ` - SELECT * FROM eth_txes - WHERE eth_txes.state = 'confirmed' - AND CAST(eth_txes.meta->>'GlobalSubId' AS NUMERIC) = $1` + SELECT * FROM evm.txes + WHERE evm.txes.state = 'confirmed' + AND CAST(evm.txes.meta->>'GlobalSubId' AS NUMERIC) = $1` ) func newVRFCoordinatorV2Universe(t *testing.T, key ethkey.KeyV2, numConsumers int) coordinatorV2Universe { @@ -1997,7 +1997,7 @@ func TestFulfillmentCost(t *testing.T) { func TestStartingCountsV1(t *testing.T) { cfg, db := heavyweight.FullTestDBNoFixturesV2(t, "vrf_test_starting_counts", nil) - _, err := db.Exec(`INSERT INTO evm_heads (hash, number, parent_hash, created_at, timestamp, evm_chain_id) + _, err := db.Exec(`INSERT INTO evm.heads (hash, number, parent_hash, created_at, timestamp, evm_chain_id) VALUES ($1, 4, $2, NOW(), NOW(), 1337)`, utils.NewHash(), utils.NewHash()) require.NoError(t, err) @@ -2101,7 +2101,7 @@ func TestStartingCountsV1(t *testing.T) { ChainID: chainID.ToInt(), }) } - sql := `INSERT INTO eth_txes (nonce, from_address, to_address, encoded_payload, value, gas_limit, state, created_at, broadcast_at, initial_broadcast_at, meta, subject, evm_chain_id, min_confirmations, pipeline_task_run_id) + sql := `INSERT INTO evm.txes (nonce, from_address, to_address, encoded_payload, value, gas_limit, state, created_at, broadcast_at, initial_broadcast_at, meta, subject, evm_chain_id, min_confirmations, pipeline_task_run_id) VALUES (:nonce, :from_address, :to_address, :encoded_payload, :value, :gas_limit, :state, :created_at, :broadcast_at, :initial_broadcast_at, :meta, :subject, :evm_chain_id, :min_confirmations, :pipeline_task_run_id);` for _, tx := range append(confirmedTxes, unconfirmedTxes...) { dbEtx := txmgr.DbEthTxFromEthTx(&tx) @@ -2109,7 +2109,7 @@ VALUES (:nonce, :from_address, :to_address, :encoded_payload, :value, :gas_limit require.NoError(t, err) } - // add eth_tx_attempts for confirmed + // add evm.tx_attempts for confirmed broadcastBlock := int64(1) var txAttempts []txmgr.TxAttempt for i := range confirmedTxes { @@ -2124,7 +2124,7 @@ VALUES (:nonce, :from_address, :to_address, :encoded_payload, :value, :gas_limit ChainSpecificFeeLimit: uint32(100), }) } - // add eth_tx_attempts for unconfirmed + // add evm.tx_attempts for unconfirmed for i := range unconfirmedTxes { txAttempts = append(txAttempts, txmgr.TxAttempt{ TxID: int64(i + 1 + len(confirmedTxes)), @@ -2139,7 +2139,7 @@ VALUES (:nonce, :from_address, :to_address, :encoded_payload, :value, :gas_limit for _, txAttempt := range txAttempts { t.Log("tx attempt eth tx id: ", txAttempt.TxID) } - sql = `INSERT INTO eth_tx_attempts (eth_tx_id, gas_price, signed_raw_tx, hash, state, created_at, chain_specific_gas_limit) + sql = `INSERT INTO evm.tx_attempts (eth_tx_id, gas_price, signed_raw_tx, hash, state, created_at, chain_specific_gas_limit) VALUES (:eth_tx_id, :gas_price, :signed_raw_tx, :hash, :state, :created_at, :chain_specific_gas_limit)` for _, attempt := range txAttempts { dbAttempt := txmgr.DbEthTxAttemptFromEthTxAttempt(&attempt) //nolint:gosec // just copying fields @@ -2148,7 +2148,7 @@ VALUES (:nonce, :from_address, :to_address, :encoded_payload, :value, :gas_limit txmgr.DbEthTxAttemptToEthTxAttempt(dbAttempt, &attempt) //nolint:gosec // just copying fields } - // add eth_receipts + // add evm.receipts receipts := []txmgr.Receipt{} for i := 0; i < 4; i++ { receipts = append(receipts, txmgr.Receipt{ @@ -2160,7 +2160,7 @@ VALUES (:nonce, :from_address, :to_address, :encoded_payload, :value, :gas_limit CreatedAt: time.Now(), }) } - sql = `INSERT INTO eth_receipts (block_hash, tx_hash, block_number, transaction_index, receipt, created_at) + sql = `INSERT INTO evm.receipts (block_hash, tx_hash, block_number, transaction_index, receipt, created_at) VALUES (:block_hash, :tx_hash, :block_number, :transaction_index, :receipt, :created_at)` for _, r := range receipts { _, err := db.NamedExec(sql, &r) diff --git a/core/services/vrf/v2/listener_v2.go b/core/services/vrf/v2/listener_v2.go index 9b643d4f571..461840c6f3c 100644 --- a/core/services/vrf/v2/listener_v2.go +++ b/core/services/vrf/v2/listener_v2.go @@ -72,7 +72,7 @@ const ( backoffFactor = 1.3 V2ReservedLinkQuery = `SELECT SUM(CAST(meta->>'MaxLink' AS NUMERIC(78, 0))) - FROM eth_txes + FROM evm.txes WHERE meta->>'MaxLink' IS NOT NULL AND evm_chain_id = $1 AND CAST(meta->>'SubId' AS NUMERIC) = $2 @@ -80,7 +80,7 @@ const ( GROUP BY meta->>'SubId'` V2PlusReservedLinkQuery = `SELECT SUM(CAST(meta->>'MaxLink' AS NUMERIC(78, 0))) - FROM eth_txes + FROM evm.txes WHERE meta->>'MaxLink' IS NOT NULL AND evm_chain_id = $1 AND CAST(meta->>'GlobalSubId' AS NUMERIC) = $2 @@ -88,7 +88,7 @@ const ( GROUP BY meta->>'GlobalSubId'` V2PlusReservedEthQuery = `SELECT SUM(CAST(meta->>'MaxEth' AS NUMERIC(78, 0))) - FROM eth_txes + FROM evm.txes WHERE meta->>'MaxEth' IS NOT NULL AND evm_chain_id = $1 AND CAST(meta->>'GlobalSubId' AS NUMERIC) = $2 diff --git a/core/services/vrf/v2/listener_v2_test.go b/core/services/vrf/v2/listener_v2_test.go index dd63ec8208e..4da20a2a7e8 100644 --- a/core/services/vrf/v2/listener_v2_test.go +++ b/core/services/vrf/v2/listener_v2_test.go @@ -34,17 +34,17 @@ import ( ) const ( - addEthTxQuery = `INSERT INTO eth_txes (from_address, to_address, encoded_payload, value, gas_limit, state, created_at, meta, subject, evm_chain_id, min_confirmations, pipeline_task_run_id) + addEthTxQuery = `INSERT INTO evm.txes (from_address, to_address, encoded_payload, value, gas_limit, state, created_at, meta, subject, evm_chain_id, min_confirmations, pipeline_task_run_id) VALUES ( $1, $2, $3, $4, $5, $6, NOW(), $7, $8, $9, $10, $11 ) - RETURNING "eth_txes".*` + RETURNING "txes".*` - addConfirmedEthTxQuery = `INSERT INTO eth_txes (nonce, broadcast_at, initial_broadcast_at, error, from_address, to_address, encoded_payload, value, gas_limit, state, created_at, meta, subject, evm_chain_id, min_confirmations, pipeline_task_run_id) + addConfirmedEthTxQuery = `INSERT INTO evm.txes (nonce, broadcast_at, initial_broadcast_at, error, from_address, to_address, encoded_payload, value, gas_limit, state, created_at, meta, subject, evm_chain_id, min_confirmations, pipeline_task_run_id) VALUES ( $1, NOW(), NOW(), NULL, $2, $3, $4, $5, $6, 'confirmed', NOW(), $7, $8, $9, $10, $11 ) - RETURNING "eth_txes".*` + RETURNING "txes".*` ) func txMetaSubIDs(t *testing.T, vrfVersion vrfcommon.Version, subID *big.Int) (*uint64, *string) { diff --git a/core/store/migrate/migrations/0194_evm_schema.sql b/core/store/migrate/migrations/0194_evm_schema.sql new file mode 100644 index 00000000000..76fc7af1807 --- /dev/null +++ b/core/store/migrate/migrations/0194_evm_schema.sql @@ -0,0 +1,106 @@ +-- +goose Up +CREATE SCHEMA evm; +SET search_path TO evm,public; + +ALTER TABLE public.evm_forwarders SET SCHEMA evm; +ALTER TABLE evm.evm_forwarders RENAME TO forwarders; + +ALTER TABLE public.evm_heads SET SCHEMA evm; +ALTER TABLE evm.evm_heads RENAME TO heads; + +ALTER TABLE public.evm_key_states SET SCHEMA evm; +ALTER TABLE evm.evm_key_states RENAME TO key_states; + +ALTER TABLE public.evm_log_poller_blocks SET SCHEMA evm; +ALTER TABLE evm.evm_log_poller_blocks RENAME TO log_poller_blocks; + +ALTER TABLE public.evm_log_poller_filters SET SCHEMA evm; +ALTER TABLE evm.evm_log_poller_filters RENAME TO log_poller_filters; + +ALTER TABLE public.evm_logs SET SCHEMA evm; +ALTER TABLE evm.evm_logs RENAME TO logs; + +ALTER TABLE public.evm_upkeep_states SET SCHEMA evm; +ALTER TABLE evm.evm_upkeep_states RENAME TO upkeep_states; + +ALTER TABLE public.eth_receipts SET SCHEMA evm; +ALTER TABLE evm.eth_receipts RENAME TO receipts; + +ALTER TABLE public.eth_tx_attempts SET SCHEMA evm; +ALTER TABLE evm.eth_tx_attempts RENAME TO tx_attempts; + +-- Handle tx triggers + +DROP TRIGGER IF EXISTS notify_eth_tx_insertion on public.eth_txes; +DROP FUNCTION IF EXISTS public.notifyethtxinsertion(); + +ALTER TABLE public.eth_txes SET SCHEMA evm; +ALTER TABLE evm.eth_txes RENAME TO txes; + + +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION evm.notifytxinsertion() RETURNS trigger + LANGUAGE plpgsql + AS $$ + BEGIN + PERFORM pg_notify('evm.insert_on_txes'::text, encode(NEW.from_address, 'hex')); + RETURN NULL; + END + $$; + +DROP TRIGGER IF EXISTS notify_tx_insertion on evm.txes; +CREATE TRIGGER notify_tx_insertion AFTER INSERT ON evm.txes FOR EACH ROW EXECUTE PROCEDURE evm.notifytxinsertion(); +-- +goose StatementEnd + + +-- +goose Down +SET search_path TO evm,public; +ALTER TABLE evm.forwarders SET SCHEMA public; +ALTER TABLE public.forwarders RENAME TO evm_forwarders; + +ALTER TABLE evm.heads SET SCHEMA public; +ALTER TABLE public.heads RENAME TO evm_heads; + +ALTER TABLE evm.key_states SET SCHEMA public; +ALTER TABLE public.key_states RENAME TO evm_key_states; + +ALTER TABLE evm.log_poller_blocks SET SCHEMA public; +ALTER TABLE public.log_poller_blocks RENAME TO evm_log_poller_blocks; + +ALTER TABLE evm.log_poller_filters SET SCHEMA public; +ALTER TABLE public.log_poller_filters RENAME TO evm_log_poller_filters; + +ALTER TABLE evm.logs SET SCHEMA public; +ALTER TABLE public.logs RENAME TO evm_logs; + +ALTER TABLE evm.upkeep_states SET SCHEMA public; +ALTER table public.upkeep_states RENAME TO evm_upkeep_states; + +ALTER TABLE evm.receipts SET SCHEMA public; +ALTER TABLE public.receipts RENAME TO eth_receipts; + +ALTER TABLE evm.tx_attempts SET SCHEMA public; +ALTER TABLE public.tx_attempts RENAME TO eth_tx_attempts; + + +DROP TRIGGER IF EXISTS notify_tx_insertion on evm.txes; +DROP FUNCTION IF EXISTS evm.notifytxinsertion(); + +ALTER TABLE evm.txes SET SCHEMA public; +ALTER TABLE public.txes RENAME TO eth_txes; + +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION public.notifyethtxinsertion() RETURNS trigger + LANGUAGE plpgsql + AS $$ + BEGIN + PERFORM pg_notify('insert_on_eth_txes'::text, encode(NEW.from_address, 'hex')); + RETURN NULL; + END + $$; + +DROP TRIGGER IF EXISTS notify_eth_tx_insertion on public.eth_txes; +CREATE TRIGGER notify_eth_tx_insertion AFTER INSERT ON public.eth_txes FOR EACH ROW EXECUTE PROCEDURE public.notifyethtxinsertion(); +-- +goose StatementEnd + +DROP SCHEMA evm; diff --git a/core/web/eth_keys_controller_test.go b/core/web/eth_keys_controller_test.go index 0ef01257e17..d656d94e6a8 100644 --- a/core/web/eth_keys_controller_test.go +++ b/core/web/eth_keys_controller_test.go @@ -409,7 +409,7 @@ func TestETHKeysController_ChainSuccess_ResetWithAbandon(t *testing.T) { assert.NoError(t, err) var count int - err = app.GetSqlxDB().Get(&count, `SELECT count(*) FROM eth_txes WHERE from_address = $1 AND state = 'fatal_error'`, addr) + err = app.GetSqlxDB().Get(&count, `SELECT count(*) FROM evm.txes WHERE from_address = $1 AND state = 'fatal_error'`, addr) require.NoError(t, err) assert.Equal(t, 0, count) @@ -436,7 +436,7 @@ func TestETHKeysController_ChainSuccess_ResetWithAbandon(t *testing.T) { assert.Equal(t, false, updatedKey.Disabled) var s string - err = app.GetSqlxDB().Get(&s, `SELECT error FROM eth_txes WHERE from_address = $1 AND state = 'fatal_error'`, addr) + err = app.GetSqlxDB().Get(&s, `SELECT error FROM evm.txes WHERE from_address = $1 AND state = 'fatal_error'`, addr) require.NoError(t, err) assert.Equal(t, "abandoned", s) } diff --git a/core/web/evm_transfer_controller_test.go b/core/web/evm_transfer_controller_test.go index 51c53a54ef3..8ca3102d7a8 100644 --- a/core/web/evm_transfer_controller_test.go +++ b/core/web/evm_transfer_controller_test.go @@ -65,7 +65,7 @@ func TestTransfersController_CreateSuccess_From(t *testing.T) { assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Len(t, errors.Errors, 0) - cltest.AssertCount(t, app.GetSqlxDB(), "eth_txes", 1) + cltest.AssertCount(t, app.GetSqlxDB(), "evm.txes", 1) } func TestTransfersController_CreateSuccess_From_WEI(t *testing.T) { @@ -105,7 +105,7 @@ func TestTransfersController_CreateSuccess_From_WEI(t *testing.T) { assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Len(t, errors.Errors, 0) - cltest.AssertCount(t, app.GetSqlxDB(), "eth_txes", 1) + cltest.AssertCount(t, app.GetSqlxDB(), "evm.txes", 1) } func TestTransfersController_CreateSuccess_From_BalanceMonitorDisabled(t *testing.T) { @@ -150,7 +150,7 @@ func TestTransfersController_CreateSuccess_From_BalanceMonitorDisabled(t *testin assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Len(t, errors.Errors, 0) - cltest.AssertCount(t, app.GetSqlxDB(), "eth_txes", 1) + cltest.AssertCount(t, app.GetSqlxDB(), "evm.txes", 1) } func TestTransfersController_TransferZeroAddressError(t *testing.T) { @@ -314,7 +314,7 @@ func TestTransfersController_CreateSuccess_eip1559(t *testing.T) { err = web.ParseJSONAPIResponse(cltest.ParseResponseBody(t, resp), &resource) assert.NoError(t, err) - cltest.AssertCount(t, app.GetSqlxDB(), "eth_txes", 1) + cltest.AssertCount(t, app.GetSqlxDB(), "evm.txes", 1) // check returned data assert.NotEmpty(t, resource.Hash)