Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

STL launchpad TokenScript URI #3370

Merged
merged 4 commits into from
Mar 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions app/src/main/java/com/alphawallet/app/C.java
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@ public abstract class C {
public static final String APP_FOREGROUND_STATE = "com.alphawallet.APP_FOREGROUND_STATE";
public static final String EXTRA_APP_FOREGROUND = "com.alphawallet.IS_FOREGORUND";
public static final String QRCODE_SCAN = "com.alphawallet.QRSCAN";
public static final String AWALLET_CODE = "com.alphawallet.AWALLET";
public static final String SIGNAL_NFT_SYNC = "com.alphawallet.SYNC_NFT";
public static final String SYNC_STATUS = "com.alphawallet.SYNC_STATUS";

Expand Down Expand Up @@ -278,6 +279,7 @@ public interface Key {
public static final String DAPP_SUFFIX_RECEIVE = "receive";
public static final String DAPP_PREFIX_MAPS = "maps.google.com/maps?daddr=";
public static final String DAPP_PREFIX_WALLETCONNECT = "wc";
public static final String DAPP_PREFIX_AWALLET = "awallet";

public static final String ENS_SCAN_BLOCK = "ens_check_block";
public static final String ENS_HISTORY = "ensHistory";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import com.alphawallet.app.entity.walletconnect.WalletConnectSessionItem;
import com.alphawallet.app.entity.walletconnect.WalletConnectV2SessionItem;
import com.alphawallet.app.service.RealmManager;
import com.walletconnect.web3.wallet.client.Wallet;
import com.walletconnect.web3.wallet.client.Web3Wallet;

Expand All @@ -15,12 +14,10 @@

public class WalletConnectInteract
{
private final RealmManager realmManager;

@Inject
public WalletConnectInteract(RealmManager realmManager)
public WalletConnectInteract()
{
this.realmManager = realmManager;

}

public int getSessionsCount()
Expand All @@ -30,15 +27,25 @@ public int getSessionsCount()

public List<WalletConnectSessionItem> getSessions()
{
List<WalletConnectSessionItem> result = new ArrayList<>();
result.addAll(getWalletConnectV2SessionItems());
List<WalletConnectSessionItem> result = new ArrayList<>(getWalletConnectV2SessionItems());

//now sort for active/newness
result.sort((l, r) -> Long.compare(r.expiryTime, l.expiryTime));

return result;
}

public void fetchSessions(SessionFetchCallback sessionFetchCallback)
{
fetch(sessionFetchCallback);
}

private void fetch(SessionFetchCallback sessionFetchCallback)
{
List<WalletConnectSessionItem> result = new ArrayList<>(getWalletConnectV2SessionItems());
sessionFetchCallback.onFetched(result);
}

private List<WalletConnectSessionItem> getWalletConnectV2SessionItems()
{
List<WalletConnectSessionItem> result = new ArrayList<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@

import static com.alphawallet.app.repository.TokenRepository.getWeb3jService;
import static com.alphawallet.app.repository.TokensRealmSource.IMAGES_DB;
import static com.alphawallet.ethereum.EthereumNetworkBase.MAINNET_ID;
import static com.alphawallet.token.tools.TokenDefinition.TOKENSCRIPT_ADDRESS;
import static com.alphawallet.token.tools.TokenDefinition.TOKENSCRIPT_CHAIN;
import static com.alphawallet.token.tools.TokenDefinition.TOKENSCRIPT_CURRENT_SCHEMA;
import static com.alphawallet.token.tools.TokenDefinition.TOKENSCRIPT_REPO_SERVER;
import static com.alphawallet.token.tools.TokenDefinition.TOKENSCRIPT_STORE_SERVER;
import static com.alphawallet.token.tools.TokenDefinition.UNCHANGED_SCRIPT;

import android.Manifest;
Expand Down Expand Up @@ -67,6 +71,8 @@
import com.alphawallet.token.tools.TokenDefinition;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONObject;
import org.web3j.abi.DefaultFunctionEncoder;
import org.web3j.abi.FunctionEncoder;
import org.web3j.abi.datatypes.Function;
Expand Down Expand Up @@ -385,9 +391,10 @@ private void handleFileLoadError(Throwable throwable, File file)

private TokenDefinition fileLoadComplete(List<ContractLocator> originContracts, TokenScriptFile file, TokenDefinition td)
{
if (originContracts.size() == 0 || td.getAttestation() != null) return td; //no action needed, not accessible to Attestation //TODO: Refactor once we handle multiple attestations
if (originContracts.isEmpty() || td.getAttestation() != null) return td; //no action needed, not accessible to Attestation //TODO: Refactor once we handle multiple attestations

boolean hasEvents = td.hasEvents();
long primaryChainId = !originContracts.isEmpty() ? originContracts.iterator().next().chainId : MAINNET_ID;

try (Realm realm = realmManager.getRealmInstance(ASSET_DEFINITION_DB))
{
Expand All @@ -396,7 +403,7 @@ private TokenDefinition fileLoadComplete(List<ContractLocator> originContracts,
{
//delete this file and check downloads for update
removeFile(file.getAbsolutePath());
loadScriptFromServer(getFileName(file));
loadScriptFromServer(primaryChainId, getFileName(file));
return td;
}

Expand Down Expand Up @@ -1011,7 +1018,7 @@ private TokenScriptFile locateTokenScriptFile(String fileName)
* Get asset definition given contract address
*
* @param address
* @return
* @return The Token Definition for the given chain, address
*/
public TokenDefinition getAssetDefinition(long chainId, String address)
{
Expand All @@ -1026,7 +1033,7 @@ public TokenDefinition getAssetDefinition(long chainId, String address)
if (assetDef == null && !address.equals("ethereum"))
{
//try web
loadScriptFromServer(address.toLowerCase()); //this will complete asynchronously and display will be updated
loadScriptFromServer(chainId, address.toLowerCase()); //this will complete asynchronously and display will be updated
}

return assetDef; // if nothing found use default
Expand Down Expand Up @@ -1066,10 +1073,10 @@ public Single<TokenDefinition> getAssetDefinitionASync(long chainId, String addr
}

String convertedAddr = (address.equalsIgnoreCase(tokensService.getCurrentAddress())) ? "ethereum" : address.toLowerCase();
return getAssetDefinitionASync(getDefinition(getTSDataKey(chainId, address)), convertedAddr);
return getAssetDefinitionASync(getDefinition(getTSDataKey(chainId, address)), chainId, convertedAddr);
}

private Single<TokenDefinition> getAssetDefinitionASync(final TokenDefinition assetDef, final String contractName)
private Single<TokenDefinition> getAssetDefinitionASync(final TokenDefinition assetDef, final long chainId, final String contractName)
{
if (assetDef != null)
{
Expand All @@ -1078,7 +1085,7 @@ private Single<TokenDefinition> getAssetDefinitionASync(final TokenDefinition as
else if (!contractName.equals("ethereum"))
{
//at this stage, this script isn't replacing any existing script, so it's safe to write to database without checking if we need to delete anything
return fetchXMLFromServer(contractName.toLowerCase())
return fetchXMLFromServer(chainId, contractName.toLowerCase())
.flatMap(this::handleNewTSFile);
}
else return Single.fromCallable(TokenDefinition::new);
Expand All @@ -1095,7 +1102,7 @@ public Single<TokenDefinition> getAssetDefinitionASync(Token token)
// hold until asset definitions have finished loading
waitForAssets();

return getAssetDefinitionASync(getDefinition(token.getTSKey()), contractName);
return getAssetDefinitionASync(getDefinition(token.getTSKey()), token.tokenInfo.chainId, contractName);
}

private void waitForAssets()
Expand Down Expand Up @@ -1169,12 +1176,12 @@ public String getIssuerName(Token token)
return issuer;
}

private void loadScriptFromServer(String correctedAddress)
private void loadScriptFromServer(long chainId, String correctedAddress)
{
//first check the last time we tried this session
if (assetChecked.get(correctedAddress) == null || (System.currentTimeMillis() > (assetChecked.get(correctedAddress) + 1000L * 60L * 60L)))
{
fetchXMLFromServer(correctedAddress)
fetchXMLFromServer(chainId, correctedAddress)
.flatMap(this::handleNewTSFile)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
Expand Down Expand Up @@ -1416,23 +1423,23 @@ private boolean matchesExistingScript(Token token, String uri)
return false;
}

private Single<File> tryServerIfRequired(File contractScript, String address)
private Single<File> tryServerIfRequired(File contractScript, String address, long chainId)
{
if (contractScript.exists() || contractScript.getName().equals(UNCHANGED_SCRIPT))
{
return Single.fromCallable(() -> contractScript);
}
else
{
return fetchXMLFromServer(address);
return fetchXMLFromServer(chainId, address);
}
}

private Single<File> fetchXMLFromServer(String address)
private Single<File> fetchXMLFromServer(long chainId, String address)
{
return Single.fromCallable(() -> {
final File defaultReturn = new File("");
if (address.equals("")) return defaultReturn;
if (address.isEmpty()) return defaultReturn;

File result = getDownloadedXMLFile(address);

Expand All @@ -1459,15 +1466,19 @@ private Single<File> fetchXMLFromServer(String address)
if (assetChecked.get(address) != null && (System.currentTimeMillis() > (assetChecked.get(address) + 1000L * 60L * 60L)))
return result;

String sb = TOKENSCRIPT_REPO_SERVER +
TOKENSCRIPT_CURRENT_SCHEMA +
"/" +
address;
//use the updated server
String sb = TOKENSCRIPT_STORE_SERVER.replace(TOKENSCRIPT_ADDRESS, address).replace(TOKENSCRIPT_CHAIN, Long.toString(chainId));

Pair<String, Boolean> downloadResponse = downloadScript(sb, fileTime);
if (!TextUtils.isEmpty(downloadResponse.first))
String offchainScriptUri = getOffchainScriptUri(downloadResponse);

if (!TextUtils.isEmpty(offchainScriptUri))
{
result = storeFile(address, downloadResponse);
downloadResponse = downloadScript(offchainScriptUri, fileTime);
if (!TextUtils.isEmpty(downloadResponse.first))
{
storeFile(address, downloadResponse);
}
}

assetChecked.put(address, System.currentTimeMillis());
Expand All @@ -1476,6 +1487,27 @@ private Single<File> fetchXMLFromServer(String address)
});
}

private String getOffchainScriptUri(Pair<String, Boolean> downloadResponse)
{
String offchainScriptResponse = "";
try
{
JSONObject response = new JSONObject(downloadResponse.first);
JSONObject scriptUri = response.getJSONObject("scriptURI");
JSONArray offchainLinks = scriptUri.getJSONArray("offchain");
if (offchainLinks.length() > 0)
{
offchainScriptResponse = offchainLinks.getString(0);
}
}
catch (Exception e)
{
offchainScriptResponse = "";
}

return offchainScriptResponse;
}

private Pair<String, Boolean> downloadScript(String Uri, long currentFileTime)
{
if (Uri.equals(UNCHANGED_SCRIPT))
Expand Down Expand Up @@ -3116,7 +3148,7 @@ public Single<TokenDefinition> checkServerForScript(Token token, MutableLiveData

//try the contractURI, then server
return fetchTokenScriptFromContract(token, updateFlag)
.flatMap(file -> tryServerIfRequired(file, token.getAddress().toLowerCase()))
.flatMap(file -> tryServerIfRequired(file, token.getAddress().toLowerCase(), token.tokenInfo.chainId))
.flatMap(this::handleNewTSFile)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ public Single<Token[]> getTokens(String address,
//process this page of results
processOpenseaTokens(foundTokens, assets, address, networkId, networkName, tokensService);
currentPage++;
pageCursor = result.getString("next");
pageCursor = result.has("next") ? result.getString("next") : "";
if (TextUtils.isEmpty(pageCursor))
{
break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
Expand All @@ -21,6 +20,9 @@
@AndroidEntryPoint
public class WalletConnectV2Service extends Service
{
private static final String TAG = WalletConnectV2Service.class.getName();

final String CHANNEL_ID = "WalletConnectV2Service";
@Override
public IBinder onBind(Intent intent)
{
Expand All @@ -32,32 +34,38 @@ public IBinder onBind(Intent intent)
public void onCreate()
{
super.onCreate();
String CHANNEL_ID = "my_channel_01";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
"WalletConnect V2",
NotificationManager.IMPORTANCE_DEFAULT);
}

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
private Notification createNotification()
{
Intent notificationIntent = new Intent(this, WalletConnectNotificationActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);

Intent intent = new Intent(getApplicationContext(), WalletConnectNotificationActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_IMMUTABLE);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_logo)
.setOnlyAlertOnce(true)
return new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(getString(R.string.notify_wallet_connect_title))
.setContentText(getString(R.string.notify_wallet_connect_content))
.setSmallIcon(R.drawable.ic_logo)
.setContentIntent(pendingIntent)
.build();

startForeground(1, notification);
notificationManager.notify(1, notification);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
@RequiresApi(api = Build.VERSION_CODES.O)
private void createNotificationChannel()
{
return super.onStartCommand(intent, flags, startId);
CharSequence name = getString(R.string.notify_wallet_connect_title);
String description = getString(R.string.notify_wallet_connect_content);
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotificationChannel();
Notification notification = createNotification();
startForeground(1, notification);
return START_STICKY;
}

@Override
Expand Down
Loading
Loading