Skip to content

Commit 8acd3f7

Browse files
Patches for rate usage
fix tests
1 parent 81972c6 commit 8acd3f7

File tree

13 files changed

+154
-22
lines changed

13 files changed

+154
-22
lines changed

app/src/main/cpp/keys.c

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,19 @@ Java_com_alphawallet_app_repository_KeyProviderJNIImpl_getSecondaryInfuraKey( JN
9292
#endif
9393
}
9494

95+
JNIEXPORT jstring JNICALL
96+
Java_com_alphawallet_app_repository_KeyProviderJNIImpl_getTertiaryInfuraKey( JNIEnv* env, jobject thiz )
97+
{
98+
#if (HAS_KEYS == 1)
99+
return getDecryptedKey(env, tertiaryInfuraKey);
100+
#elif (HAS_INFURA == 1)
101+
return (*env)->NewStringUTF(env, IFKEY);
102+
#else
103+
const jstring key = "da3717f25f824cc1baa32d812386d93f";
104+
return (*env)->NewStringUTF(env, key);
105+
#endif
106+
}
107+
95108
JNIEXPORT jstring JNICALL
96109
Java_com_alphawallet_app_repository_KeyProviderJNIImpl_getKlaytnKey( JNIEnv* env, jobject thiz )
97110
{

app/src/main/java/com/alphawallet/app/entity/CoinGeckoTicker.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,15 @@ public static List<CoinGeckoTicker> buildTickerList(String jsonData, String curr
4545
fiatPrice = obj.getDouble(currencyIsoSymbol.toLowerCase());
4646
fiatChangeStr = obj.getString(currencyIsoSymbol.toLowerCase() + "_24h_change");
4747
}
48-
else
48+
else if (obj.has("usd"))
4949
{
5050
fiatPrice = obj.getDouble("usd") * currentConversionRate;
5151
fiatChangeStr = obj.getString("usd_24h_change");
5252
}
53+
else
54+
{
55+
continue; //handle empty/corrupt returns
56+
}
5357

5458
res.add(new CoinGeckoTicker(address, fiatPrice, getFiatChange(fiatChangeStr)));
5559
}

app/src/main/java/com/alphawallet/app/repository/EthereumNetworkBase.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,32 @@ public abstract class EthereumNetworkBase implements EthereumNetworkRepositoryTy
185185
// Add deprecated testnet IDs here
186186
));
187187

188+
private static final String INFURA_ENDPOINT = ".infura.io/v3/";
189+
190+
@Override
191+
public String getDappBrowserRPC(long chainId)
192+
{
193+
NetworkInfo info = getNetworkByChain(chainId);
194+
195+
if (info == null)
196+
{
197+
return "";
198+
}
199+
else if (chainId == MAINNET_ID)
200+
{
201+
int index = info.rpcServerUrl.indexOf(INFURA_ENDPOINT);
202+
return info.rpcServerUrl.substring(0, index + INFURA_ENDPOINT.length()) + keyProvider.getTertiaryInfuraKey();
203+
}
204+
else if (info.backupNodeUrl != null)
205+
{
206+
return info.backupNodeUrl;
207+
}
208+
else
209+
{
210+
return info.rpcServerUrl;
211+
}
212+
}
213+
188214
// for reset built-in network
189215
private static final LongSparseArray<NetworkInfo> builtinNetworkMap = new LongSparseArray<NetworkInfo>()
190216
{

app/src/main/java/com/alphawallet/app/repository/EthereumNetworkRepositoryType.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import com.alphawallet.app.entity.NetworkInfo;
66
import com.alphawallet.app.entity.Wallet;
77
import com.alphawallet.app.entity.tokens.Token;
8-
import com.alphawallet.app.repository.entity.RealmToken;
98

109
import org.web3j.protocol.Web3j;
1110

@@ -54,6 +53,7 @@ public interface EthereumNetworkRepositoryType {
5453
void setHasSetNetworkFilters();
5554
boolean isMainNetSelected();
5655
void setActiveMainnet(boolean isMainNet);
56+
String getDappBrowserRPC(long chainId);
5757

5858
void saveCustomRPCNetwork(String networkName, String rpcUrl, long chainId, String symbol, String blockExplorerUrl, String explorerApiUrl, boolean isTestnet, Long oldChainId);
5959
void removeCustomRPCNetwork(long chainId);

app/src/main/java/com/alphawallet/app/repository/KeyProvider.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ public interface KeyProvider
2020

2121
String getSecondaryInfuraKey();
2222

23+
String getTertiaryInfuraKey();
24+
2325
String getRampKey();
2426

2527
String getOpenSeaKey();

app/src/main/java/com/alphawallet/app/repository/KeyProviderJNIImpl.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ public KeyProviderJNIImpl()
1111

1212
public native String getSecondaryInfuraKey();
1313

14+
public native String getTertiaryInfuraKey();
15+
1416
public native String getBSCExplorerKey();
1517

1618
public native String getAnalyticsKey();

app/src/main/java/com/alphawallet/app/service/TickerService.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ public class TickerService
101101
private static String currentCurrencySymbol;
102102
private static final Map<Long, Long> canUpdate = new ConcurrentHashMap<>();
103103
private static final Map<String, TokenCardMeta> dexGuruQuery = new ConcurrentHashMap<>();
104+
private static long lastTickerUpdate;
104105

105106
@Nullable
106107
private Disposable tickerUpdateTimer;
@@ -119,11 +120,12 @@ public TickerService(OkHttpClient httpClient, PreferenceRepositoryType sharedPre
119120

120121
resetTickerUpdate();
121122
initCurrency();
123+
lastTickerUpdate = 0;
122124
}
123125

124126
public void updateTickers()
125127
{
126-
if (mainTickerUpdate != null && !mainTickerUpdate.isDisposed())
128+
if (mainTickerUpdate != null && !mainTickerUpdate.isDisposed() && System.currentTimeMillis() > (lastTickerUpdate + DateUtils.MINUTE_IN_MILLIS))
127129
{
128130
return; //do not update if update is currently in progress
129131
}
@@ -151,6 +153,7 @@ private void tickersUpdated(int tickerCount)
151153
{
152154
Timber.d("Tickers Updated: %s", tickerCount);
153155
mainTickerUpdate = null;
156+
lastTickerUpdate = System.currentTimeMillis();
154157
}
155158

156159
public Single<Double> updateCurrencyConversion()

app/src/main/java/com/alphawallet/app/util/ens/EnsResolver.java

Lines changed: 77 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,8 @@
5959
import java.util.ArrayList;
6060
import java.util.Arrays;
6161
import java.util.List;
62+
import java.util.Map;
63+
import java.util.concurrent.ConcurrentHashMap;
6264

6365
import okhttp3.MediaType;
6466
import okhttp3.OkHttpClient;
@@ -76,6 +78,7 @@ public class EnsResolver implements Resolvable
7678

7779
// Permit number offchain calls for a single contract call.
7880
public static final int LOOKUP_LIMIT = 4;
81+
private static final long ENS_CACHE_TIME_VALIDITY = 10 * (1000*60); //10 minutes
7982

8083
public static final String REVERSE_NAME_SUFFIX = ".addr.reverse";
8184

@@ -112,11 +115,61 @@ public EnsResolver(Web3j web3j) {
112115
this(web3j, Keys.ADDRESS_LENGTH_IN_HEX);
113116
}
114117

115-
protected ContractAddress obtainOffchainResolverAddr(String ensName) throws Exception
118+
protected ContractAddress obtainOffChainResolverAddress(String ensName) throws Exception
116119
{
117120
return new ContractAddress(chainId, getResolverAddress(ensName));
118121
}
119122

123+
private static class CachedENSRead
124+
{
125+
public final String cachedResult;
126+
public final long cachedResultTime;
127+
128+
public CachedENSRead(String result)
129+
{
130+
cachedResult = result;
131+
cachedResultTime = System.currentTimeMillis();
132+
}
133+
134+
public boolean isValid()
135+
{
136+
return System.currentTimeMillis() < (cachedResultTime + ENS_CACHE_TIME_VALIDITY); //10 minutes cache validity
137+
}
138+
}
139+
140+
//Need to cache results for Resolve
141+
private static final Map<String, CachedENSRead> cachedNameReads = new ConcurrentHashMap<>();
142+
143+
private String cacheKey(String ensName, String addrFunction)
144+
{
145+
return ((ensName != null) ? ensName : "") + "%" + ((addrFunction != null) ? addrFunction : "");
146+
}
147+
148+
private String resolveWithCaching(String ensName, byte[] nameHash, String resolverAddr) throws Exception
149+
{
150+
String dnsEncoded = NameHash.dnsEncode(ensName);
151+
String addrFunction = encodeResolverAddr(nameHash);
152+
153+
CachedENSRead lookupData = cachedNameReads.get(cacheKey(ensName, addrFunction));
154+
String lookupDataHex = lookupData != null ? lookupData.cachedResult : null;
155+
156+
if (lookupData == null || !lookupData.isValid())
157+
{
158+
EthCall result =
159+
resolve(
160+
Numeric.hexStringToByteArray(dnsEncoded),
161+
Numeric.hexStringToByteArray(addrFunction),
162+
resolverAddr);
163+
lookupDataHex = result.isReverted() ? Utils.removeDoubleQuotes(result.getError().getData()) : result.getValue();// .toString();
164+
if (!TextUtils.isEmpty(lookupDataHex) && !lookupDataHex.equals("0x"))
165+
{
166+
cachedNameReads.put(cacheKey(ensName, addrFunction), new CachedENSRead(lookupDataHex));
167+
}
168+
}
169+
170+
return lookupDataHex;
171+
}
172+
120173
/**
121174
* Returns the address of the resolver for the specified node.
122175
*
@@ -133,24 +186,15 @@ public String resolve(String ensName) throws Exception
133186
try {
134187
if (isValidEnsName(ensName, addressLength))
135188
{
136-
ContractAddress resolverAddress = obtainOffchainResolverAddr(ensName);
189+
ContractAddress resolverAddress = obtainOffChainResolverAddress(ensName);
137190

138191
boolean supportWildcard =
139192
supportsInterface(EnsUtils.ENSIP_10_INTERFACE_ID, resolverAddress.address);
140193
byte[] nameHash = NameHash.nameHashAsBytes(ensName);
141194

142195
String resolvedName;
143196
if (supportWildcard) {
144-
String dnsEncoded = NameHash.dnsEncode(ensName);
145-
String addrFunction = encodeResolverAddr(nameHash);
146-
147-
EthCall result =
148-
resolve(
149-
Numeric.hexStringToByteArray(dnsEncoded),
150-
Numeric.hexStringToByteArray(addrFunction),
151-
resolverAddress.address);
152-
153-
String lookupDataHex = result.isReverted() ? Utils.removeDoubleQuotes(result.getError().getData()) : result.getValue();// .toString();
197+
String lookupDataHex = resolveWithCaching(ensName, nameHash, resolverAddress.address);
154198
resolvedName = resolveOffchain(lookupDataHex, resolverAddress, LOOKUP_LIMIT);
155199
} else {
156200
try {
@@ -359,7 +403,7 @@ public String reverseResolve(String address) throws Exception
359403
if (WalletUtils.isValidAddress(address, addressLength))
360404
{
361405
String reverseName = Numeric.cleanHexPrefix(address) + REVERSE_NAME_SUFFIX;
362-
ContractAddress resolverAddress = obtainOffchainResolverAddr(reverseName);
406+
ContractAddress resolverAddress = obtainOffChainResolverAddress(reverseName);
363407

364408
byte[] nameHash = NameHash.nameHashAsBytes(reverseName);
365409
String name;
@@ -438,11 +482,27 @@ public boolean supportsInterface(byte[] interfaceID, String address) throws Exce
438482

439483
public String resolverAddr(byte[] node, String address) throws Exception
440484
{
441-
final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_addr,
442-
Arrays.<Type>asList(new org.web3j.abi.datatypes.generated.Bytes32(node)),
443-
Arrays.<TypeReference<?>>asList(new TypeReference<Address>() {}));
485+
//use caching
486+
String nodeData = Numeric.toHexString(node);
487+
CachedENSRead resolverData = cachedNameReads.get(cacheKey(nodeData, address));
488+
String resolverAddr = resolverData != null ? resolverData.cachedResult : null;
444489

445-
return getContractData(address, function, "");
490+
if (resolverData == null || !resolverData.isValid())
491+
{
492+
final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_addr,
493+
Arrays.<Type>asList(new org.web3j.abi.datatypes.generated.Bytes32(node)),
494+
Arrays.<TypeReference<?>>asList(new TypeReference<Address>()
495+
{
496+
}));
497+
498+
resolverAddr = getContractData(address, function, "");
499+
if (!TextUtils.isEmpty(resolverAddr) && resolverAddr.length() > 2)
500+
{
501+
cachedNameReads.put(cacheKey(nodeData, address), new CachedENSRead(resolverAddr));
502+
}
503+
}
504+
505+
return resolverAddr;
446506
}
447507

448508
public String encodeResolverAddr(byte[] node)

app/src/main/java/com/alphawallet/app/viewmodel/DappBrowserViewModel.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -375,9 +375,10 @@ public Single<BigInteger> calculateGasEstimate(Wallet wallet, Web3Transaction tr
375375
}
376376
}
377377

378+
// Use the backup node if avail
378379
public String getNetworkNodeRPC(long chainId)
379380
{
380-
return ethereumNetworkRepository.getNetworkByChain(chainId).rpcServerUrl;
381+
return ethereumNetworkRepository.getDappBrowserRPC(chainId);
381382
}
382383

383384
public NetworkInfo getNetworkInfo(long chainId)

app/src/test/java/com/alphawallet/app/ENSTest.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,15 @@ public void testResolve() throws Exception {
6969

7070
assertEquals(
7171
ensResolver.resolve("offchainexample.eth"), ("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045").toLowerCase());
72+
73+
//Now test the cache
74+
assertEquals(
75+
ensResolver.resolve("1.offchainexample.eth"), ("0x41563129cdbbd0c5d3e1c86cf9563926b243834d").toLowerCase());
76+
assertEquals(
77+
ensResolver.resolve("1.offchainexample.eth"), ("0x41563129cdbbd0c5d3e1c86cf9563926b243834d").toLowerCase());
78+
79+
assertEquals(
80+
ensResolver.resolve("web3j.eth"), ("0x7bfd522dea355ddee2be3c01dfa4419451759310").toLowerCase());
7281
}
7382

7483
//Temporarily remove - DAS seems to be acting up

0 commit comments

Comments
 (0)