@@ -72,6 +72,8 @@ public static class Builder {
7272 private Integer port ;
7373 private boolean usePlaintext = false ;
7474 private boolean useLoadBalancing = true ;
75+ private boolean autoConnect = false ;
76+ private boolean waitForAuth = false ;
7577
7678 /**
7779 * Default Netty config allows messages up to 4Mb, but in practice Ethereum RPC responses may be larger. Here it allows up to 32Mb by default.
@@ -143,6 +145,27 @@ public Builder disableLoadBalancing() {
143145 return this ;
144146 }
145147
148+ /**
149+ * Automatically authenticate on Emerald API when the connection is built.
150+ * By default, it authenticates on the first request, which may cause delays.
151+ *
152+ * @return builder
153+ */
154+ public Builder withAutoConnect () {
155+ this .autoConnect = true ;
156+ return this ;
157+ }
158+
159+ /**
160+ * When auto-connect is enabled, wait for authentication to complete before returning the EmeraldConnection instance.
161+ *
162+ * @return builder
163+ */
164+ public Builder withWaitingForAuth () {
165+ this .waitForAuth = true ;
166+ return this ;
167+ }
168+
146169 /**
147170 * St max inbound message size. Default is 32mb.
148171 *
@@ -185,6 +208,24 @@ protected void initDefaults() {
185208 }
186209 }
187210
211+ /**
212+ * Setup the credentials instance
213+ *
214+ * @param channel the existing channel to use for authentication
215+ * @return credentials instance
216+ */
217+ protected TokenCredentials getOrCreateCredentials (Channel channel ) {
218+ TokenCredentials result = new TokenCredentials (secretToken , AuthGrpc .newBlockingStub (channel ));
219+ if (autoConnect ) {
220+ if (waitForAuth ) {
221+ result .authSync ();
222+ } else {
223+ result .authAsync ();
224+ }
225+ }
226+ return result ;
227+ }
228+
188229 /**
189230 * Build the API instance
190231 *
@@ -223,7 +264,7 @@ public EmeraldConnection build() {
223264 if (usePlaintext ) {
224265 System .err .println ("WARNING: Authentication with a secret token over an unsecure plaintext connection." );
225266 }
226- AuthHolder holder = new AuthHolder (new TokenCredentials ( secretToken , AuthGrpc . newBlockingStub ( channel ) ));
267+ AuthHolder holder = new AuthHolder (getOrCreateCredentials ( channel ));
227268 authInterceptor = new AuthInterceptor (holder );
228269 }
229270
0 commit comments