Skip to content

Commit 1621141

Browse files
authored
feat: add time advance call to anvil client (#2043)
* feat: add time advance call to anvil client * fix: linting * fix: linting
1 parent 17f3dff commit 1621141

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

framework/rpc/rpc.go

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import (
66
"encoding/json"
77
"fmt"
88
"math/big"
9-
"math/rand"
9+
"math/rand/v2"
1010
"net/http"
1111
"os"
1212
"strconv"
@@ -51,6 +51,21 @@ func New(url string, headers http.Header) *RPCClient {
5151
}
5252
}
5353

54+
// EVMIncreaseTime jumps forward in time by `seconds`.
55+
// The parameter is a JSON number (in seconds)
56+
func (m *RPCClient) EVMIncreaseTime(seconds uint64) error {
57+
payload := map[string]interface{}{
58+
"jsonrpc": "2.0",
59+
"method": "evm_increaseTime",
60+
"params": []interface{}{seconds},
61+
"id": rand.Int(), //nolint:gosec
62+
}
63+
if _, err := m.client.R().SetBody(payload).Post(m.URL); err != nil {
64+
return errors.Wrap(err, "evm_increaseTime")
65+
}
66+
return nil
67+
}
68+
5469
// AnvilAutoImpersonate sets auto impersonification to true or false
5570
func (m *RPCClient) AnvilAutoImpersonate(b bool) error {
5671
//nolint:gosec

framework/rpc/rpc_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,4 +243,38 @@ func TestRPCAPI(t *testing.T) {
243243
require.GreaterOrEqual(t, int64(block.Transactions().Len()), txnInBlock)
244244
}
245245
})
246+
247+
t.Run("(anvil) evm_increaseTime advances timestamp", func(t *testing.T) {
248+
ac, err := StartAnvil([]string{"--no-mine"})
249+
require.NoError(t, err)
250+
client, err := ethclient.Dial(ac.URL)
251+
require.NoError(t, err)
252+
253+
anvil := New(ac.URL, nil)
254+
255+
// Mine an initial block to establish a baseline timestamp
256+
require.NoError(t, anvil.AnvilMine([]interface{}{1}))
257+
258+
// Read latest header/time
259+
h1, err := client.HeaderByNumber(context.Background(), nil)
260+
require.NoError(t, err)
261+
t1 := h1.Time // uint64 (seconds)
262+
263+
// Jump forward in time, then mine exactly one block so the new timestamp is materialized
264+
advance := uint64(60) // 1 minute
265+
require.NoError(t, anvil.EVMIncreaseTime(advance))
266+
require.NoError(t, anvil.AnvilMine([]interface{}{1}))
267+
268+
// Read new header/time
269+
h2, err := client.HeaderByNumber(context.Background(), nil)
270+
require.NoError(t, err)
271+
t2 := h2.Time
272+
273+
// Assert the delta is at least the requested advance
274+
// (Anvil should add exactly `advance`, but we allow >= to be safe.)
275+
require.GreaterOrEqual(t, t2-t1, advance, "timestamp did not advance by expected seconds")
276+
277+
t.Logf("advanced time by %d seconds: %d -> %d (Δ=%d)", advance, t1, t2, t2-t1)
278+
})
279+
246280
}

0 commit comments

Comments
 (0)