Skip to content

Commit

Permalink
migrating from networkId to networkCode
Browse files Browse the repository at this point in the history
  • Loading branch information
pellicceama committed Aug 16, 2022
1 parent c9ce596 commit ca16838
Show file tree
Hide file tree
Showing 16 changed files with 47 additions and 53 deletions.
6 changes: 3 additions & 3 deletions src/db/asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export async function assetsForEach(callback: AssetInfoCallback, complete?: () =
try {
const networks = await getNetworks();
await Promise.all(networks.map(async network => {
const assets = await getAssetsForNetwork(network.networkId);
const assets = await getAssetsForNetwork(network.networkCode);
return Promise.all(assets.map(async asset => {
return callback(asset);
}));
Expand Down Expand Up @@ -41,13 +41,13 @@ export async function assetForId(id: string, callback: AssetInfoCallback) {
}

export async function findAssetByNetworkIdAndAddress(
networkId: string,
networkCode: string,
address: string,
callback: AssetInfoCallback
) {

try {
const asset = (await getAssetsForNetwork(networkId)).find((asset) => asset.address === address);
const asset = (await getAssetsForNetwork(networkCode)).find((asset) => asset.address === address);
return callback(asset);
} catch (err) {
throw err;
Expand Down
8 changes: 4 additions & 4 deletions src/db/assets.json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ export const ETHEREUM_ASSETS = [
{
active: true,
address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
networkId: "ethereum",
networkCode: "ethereum",
color: null,
decimals: 6,
description: {},
Expand Down Expand Up @@ -37,7 +37,7 @@ export const ETHEREUM_ASSETS = [
{
active: true,
address: "0x6B175474E89094C44Da98b954EedeAC495271d0F",
networkId: "ethereum",
networkCode: "ethereum",
color: null,
decimals: 18,
description: {},
Expand Down Expand Up @@ -74,7 +74,7 @@ export const POLYGON_ASSETS = [
{
active: true,
address: "0x2791bca1f2de4661ed88a30c99a7a9449aa84174",
networkId: "polygon",
networkCode: "polygon",
color: null,
decimals: 6,
description: {},
Expand Down Expand Up @@ -113,7 +113,7 @@ export const POLYGON_ASSETS = [
{
active: true,
address: "0x8f3cf7ad23cd3cadbd9735aff958023239c6a063",
networkId: "polygon",
networkCode: "polygon",
color: null,
decimals: 18,
description:{},
Expand Down
10 changes: 2 additions & 8 deletions src/db/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,19 +31,13 @@ export async function networkForId (id: string, callback: NetworkInfoCallback) {
}
}

export async function findNetworkByNetworkId(networkId: string, callback: NetworkInfoCallback) {
export async function findNetworkByNetworkId(networkCode: string, callback: NetworkInfoCallback) {
try {
const networks = await getNetworks();
const network = networks.find((network) => network.networkId === networkId);
const network = networks.find((network) => network.networkCode === networkCode);
return callback(network);

} catch (err) {
throw err;
}
}

async function getMockNetworks(networkId?: string): Promise<Network[]> {
// @ts-ignore
return (networkId ? MOCK_NETWORKS.filter((n) => n.networkId === networkId) : MOCK_NETWORKS) as Network[];
}

4 changes: 2 additions & 2 deletions src/db/networks.json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const MOCK_NETWORKS = [
svg: "https://raw.githubusercontent.com/map3xyz/assets/master/networks/ethereum/logo.svg"
},
name: "Ethereum",
networkId: "ethereum",
networkCode: "ethereum",
regex: {
address: "^0x[a-fA-F0-9]{40}$",
memo: null,
Expand Down Expand Up @@ -64,7 +64,7 @@ export const MOCK_NETWORKS = [
svg: "https://raw.githubusercontent.com/map3xyz/assets/master/networks/polygon/logo.svg"
},
name: "Polygon",
networkId: "polygon",
networkCode: "polygon",
regex: {
address: "^(0x)[0-9A-Fa-f]{40}$",
memo: null,
Expand Down
2 changes: 1 addition & 1 deletion src/model/Asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export class Asset extends RepoObject {
static async fromTokenlistTokenInfo(info: TokenInfoExt, source?: string): Promise<Asset> {
try {
const baseToken: Asset = new Asset({
networkId: (await getNetworkForChainId(info.chainId)).networkId,
networkCode: (await getNetworkForChainId(info.chainId)).networkCode,
address: info.address,
name: info.name,
symbol: info.symbol,
Expand Down
6 changes: 3 additions & 3 deletions src/model/Network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ export class Network extends RepoObject {
constructor(info: Partial<Network>) {
super(info);

if(!this.name || toHyphenCase(this.networkId) !== info.networkId) {
if(!this.name || toHyphenCase(this.networkCode) !== info.networkCode) {
const err = `'Network requires a name that is the hyphencase version of the id. '`
+ ' Passed: name=' + this.name
+ ' Network Id=' + this.networkId
+ ' Network Id=' + this.networkCode
+ ' hyphenatedName=' + toHyphenCase(this.name)
+ ' hyphenatedNetworkId=' + toHyphenCase(this.networkId);
+ ' hyphenatedNetworkCode=' + toHyphenCase(this.networkCode);

throw new Error(err);
}
Expand Down
8 changes: 4 additions & 4 deletions src/model/RepoObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export type ObjectType = 'network' | 'asset';

export abstract class RepoObject {
id: string;
networkId: string;
networkCode: string;
active: boolean;
color: string | null;
decimals: number;
Expand All @@ -26,10 +26,10 @@ export abstract class RepoObject {

constructor(info: Partial<RepoObject>) {
this.id = info.id? info.id : getUUID();
if(!info.networkId) {
throw new Error('AssetsRepoObject requires a networkId');
if(!info.networkCode) {
throw new Error('AssetsRepoObject requires a networkCode');
}
this.networkId = info.networkId;
this.networkCode = info.networkCode;

this.active = info.active === undefined ? true : info.active;
this.color = info.color || null;
Expand Down
4 changes: 2 additions & 2 deletions src/tokenlist/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,8 @@ export async function ingestTokenList(listLocation: string, directory: string, b

let listToIngest: TokenList = JSON.parse(fs.readFileSync(listLocation, 'utf8'));

const networkId = directory.split('/')[directory.split('/').length - 3];
const networkInfoFile = JSON.parse(fs.readFileSync(path.join(directory.split(networkId)[0], networkId, 'info.json'), 'utf8'));
const networkCode = directory.split('/')[directory.split('/').length - 3];
const networkInfoFile = JSON.parse(fs.readFileSync(path.join(directory.split(networkCode)[0], networkCode, 'info.json'), 'utf8'));

const chainId = networkInfoFile?.identifiers.chainId;

Expand Down
10 changes: 5 additions & 5 deletions src/trustwallet/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,12 @@ export async function getTwaTokenInfo(t: Asset, chainId: number, twaRepoLoc: str
const network = await getNetworkForChainId(chainId);
await cloneOrPullRepoAndUpdateSubmodules(TWA_REPO_CLONE_URL, twaRepoLoc, false, "master");

// note: if trustwallet names the network different to our networkId,
// note: if trustwallet names the network different to our networkCode,
// even if they have the same chainId we may encounter issues
// as we may not find the infoFilePath.
// TODO; Handle this case better
const infoFilePath = path.join(twaRepoLoc, 'blockchains', network.networkId, 'assets', t.address, 'info.json');
const logoHttpPath = `${TWA_USER_CONTENT_BASE}/blockchains/${network.networkId}/assets/${t.address}/logo.png`;
const infoFilePath = path.join(twaRepoLoc, 'blockchains', network.networkCode, 'assets', t.address, 'info.json');
const logoHttpPath = `${TWA_USER_CONTENT_BASE}/blockchains/${network.networkCode}/assets/${t.address}/logo.png`;

if(!fs.existsSync(infoFilePath)) {
console.error(`getTwaTokenInfo No info.json found for ${t.address}`);
Expand All @@ -62,7 +62,7 @@ export async function getTwaTokenInfo(t: Asset, chainId: number, twaRepoLoc: str
decimals: i.decimals,
id: getUUID(),
links: getLinks(i),
networkId: network.networkId,
networkCode: network.networkCode,
active: i.status === 'active',
spam: i.status === 'spam',
logo: Logos.getLogosFromUri(logoHttpPath),
Expand Down Expand Up @@ -98,7 +98,7 @@ export async function getTwaNetworkInfo(twaNetworkName: string, addressRegex: st
decimals: i.decimals,
id: getUUID(),
links: getLinks(i),
networkId: twaNetworkName,
networkCode: twaNetworkName,
active: i.status === 'active',
spam: i.status === 'spam',
logo: Logos.getLogosFromUri(logoHttpPath),
Expand Down
4 changes: 2 additions & 2 deletions src/trustwallet/trustwallet.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ test("We are able to convert trustwallet assets to map3 assets, active asset", a
name: "USD Coin",
symbol: "USDC",
decimals: 6,
networkId: "ethereum",
networkCode: "ethereum",
id: "foofaaId",
logo: undefined
});
Expand Down Expand Up @@ -44,7 +44,7 @@ test("We are able to convert trustwallet assets to map3 assets, inactive asset",
name: "Trias Token",
symbol: "TRY",
decimals: 18,
networkId: "ethereum",
networkCode: "ethereum",
id: "foofaaIdX",
});
const twaAsset = await getTwaTokenInfo(asset, 1);
Expand Down
2 changes: 1 addition & 1 deletion src/tsv/AssetsTsv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export class AssetsTsv implements IAssetsTsv {
throw `AssetsTsv.deserialise: persistDir ${persistDir} does not exist`;
}

const networkDirs = (await getNetworks()).map(network => network.networkId);
const networkDirs = (await getNetworks()).map(network => network.networkCode);

let tsv = `${HEADER_ROW_START}\t${networkDirs.sort().join('\t')}\n`;

Expand Down
2 changes: 1 addition & 1 deletion src/tsv/AssetsTsvRow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export class AssetsTsvRow implements IAssetsTsvRow {
static async prepare(primaryId: RepoPointer, primaryNetwork: string, name: string, symbol: string, networks: { [network: string]: RepoPointer[];}): Promise<AssetsTsvRow> {
try {
if(networkDirs.length === 0) {
networkDirs = (await getNetworks()).map(network => network.networkId);
networkDirs = (await getNetworks()).map(network => network.networkCode);
}

if(!networkDirs.includes(primaryNetwork)) {
Expand Down
22 changes: 11 additions & 11 deletions src/tsv/RepoFileGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,14 @@ export class RepoFileGenerator {
try {
const networks = await getNetworks(repoLoc);
let networksMap = {};
networks.map(n => n.networkId).forEach(networkId => {
networksMap[networkId] = [];
networks.map(n => n.networkCode).forEach(networkCode => {
networksMap[networkCode] = [];
});

// TODO; add support for testnets fetching
for (const network of networks) {

const mainNetworkAssetMappedTo = EXAMPLE_ASSET_MAP.find(a => a.fromNetwork === network.networkId && a.fromAsset === `id:${network.id}`);
const mainNetworkAssetMappedTo = EXAMPLE_ASSET_MAP.find(a => a.fromNetwork === network.networkCode && a.fromAsset === `id:${network.id}`);

let row = assetsCsv.get(`id:${network.id}`);

Expand All @@ -45,9 +45,9 @@ export class RepoFileGenerator {
row = assetsCsv.get(mainNetworkAssetMappedTo.toAsset);
if(!row) {
// handle case where the asset its mapped to does not exist, yet.
const assetInfo = networks.find(n => n.networkId === mainNetworkAssetMappedTo.toAsset.split(':')[1])
const assetInfo = networks.find(n => n.networkCode === mainNetworkAssetMappedTo.toAsset.split(':')[1])
|| (await getAssetsForNetwork(mainNetworkAssetMappedTo.toNetwork, repoLoc)).find(a => a.id === mainNetworkAssetMappedTo.toAsset.split(":")[1]);
row = assetsCsv.append(await AssetsTsvRow.prepare(`id:${assetInfo.id}`, assetInfo.networkId, assetInfo.name, assetInfo.symbol, shallowClone(networksMap)));
row = assetsCsv.append(await AssetsTsvRow.prepare(`id:${assetInfo.id}`, assetInfo.networkCode, assetInfo.name, assetInfo.symbol, shallowClone(networksMap)));
}
}
row.networks[mainNetworkAssetMappedTo.fromNetwork].push(mainNetworkAssetMappedTo.fromAsset);
Expand All @@ -59,18 +59,18 @@ export class RepoFileGenerator {
console.log(`Skipping network ${network.id} because it has the same name or symbol as another asset`);
} else {
// create the network asset
assetsCsv.append(await AssetsTsvRow.prepare(`id:${network.id}`, network.networkId, network.name, network.symbol, shallowClone(networksMap)));
assetsCsv.append(await AssetsTsvRow.prepare(`id:${network.id}`, network.networkCode, network.name, network.symbol, shallowClone(networksMap)));
}
}

const networkAssets: Asset[] = await getAssetsForNetwork(network.networkId, repoLoc);
const networkAssets: Asset[] = await getAssetsForNetwork(network.networkCode, repoLoc);

if(!networkAssets || networkAssets.length === 0) {
continue;
}

for(const asset of networkAssets) {
const assetMappedToAnotherOne = EXAMPLE_ASSET_MAP.find(a => a.fromNetwork === network.networkId && a.fromAsset === `id:${asset.id}`);
const assetMappedToAnotherOne = EXAMPLE_ASSET_MAP.find(a => a.fromNetwork === network.networkCode && a.fromAsset === `id:${asset.id}`);
let row = assetsCsv.get(`id:${asset.id}`);

if(assetMappedToAnotherOne) {
Expand All @@ -83,9 +83,9 @@ export class RepoFileGenerator {

if(!row) {
// handle case where the asset its mapped to does not exist, yet.
const assetInfo = networks.find(n => n.networkId === mainNetworkAssetMappedTo.toAsset.split(':')[1])
const assetInfo = networks.find(n => n.networkCode === mainNetworkAssetMappedTo.toAsset.split(':')[1])
|| (await getAssetsForNetwork(assetMappedToAnotherOne.toNetwork, repoLoc)).find(a => a.id === assetMappedToAnotherOne.toAsset.split(":")[1]);
row = assetsCsv.append(await AssetsTsvRow.prepare(`id:${assetInfo.id}`, assetInfo.networkId, assetInfo.name, assetInfo.symbol, shallowClone(networksMap)));
row = assetsCsv.append(await AssetsTsvRow.prepare(`id:${assetInfo.id}`, assetInfo.networkCode, assetInfo.name, assetInfo.symbol, shallowClone(networksMap)));
}
}
row.networks[assetMappedToAnotherOne.fromNetwork].push(assetMappedToAnotherOne.fromAsset);
Expand All @@ -98,7 +98,7 @@ export class RepoFileGenerator {
continue;
}
// create the network asset
assetsCsv.append(await AssetsTsvRow.prepare(`id:${asset.id}`, asset.networkId, asset.name, asset.symbol, shallowClone(networksMap)));
assetsCsv.append(await AssetsTsvRow.prepare(`id:${asset.id}`, asset.networkCode, asset.name, asset.symbol, shallowClone(networksMap)));
}
}
}
Expand Down
8 changes: 4 additions & 4 deletions src/utils/chainId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,24 +14,24 @@ async function getChainIdMap() {
networks = await getNetworks();

networks.forEach(network => {
chainIdMap[network.networkId.toLowerCase()] = network.identifiers.chainId;
chainIdMap[network.networkCode.toLowerCase()] = network.identifiers.chainId;
});

return chainIdMap;
} catch (err) {
throw err;
}
}
export async function getChainIdForNetwork(networkId: string): Promise<number> {
export async function getChainIdForNetwork(networkCode: string): Promise<number> {
try {
if(!chainIdMap || Object.keys(chainIdMap).length === 0) {
chainIdMap = await getChainIdMap();
}

const res = chainIdMap[networkId.toLowerCase()];
const res = chainIdMap[networkCode.toLowerCase()];

if(!res) {
throw new Error(`getChainIdForNetwork ChainId does not exist for network ${networkId} on the Map3 repo (yet!) or is not cached by utils/chainId. State: ${JSON.stringify(chainIdMap)}`);
throw new Error(`getChainIdForNetwork ChainId does not exist for network ${networkCode} on the Map3 repo (yet!) or is not cached by utils/chainId. State: ${JSON.stringify(chainIdMap)}`);
}

return res;
Expand Down
2 changes: 1 addition & 1 deletion src/validate/rules/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const skipDirs = [
]

// TODO; check that assetIds / /assets/{address}/info.json ids are unique.
// Also check that networkIds are unique
// Also check that networkCodes are unique

const coreRules = [
...EditorPermissionRules,
Expand Down
2 changes: 1 addition & 1 deletion src/validate/rules/network/NetworkDirectoryRules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export const NetworkDirectoryRules: ValidationRule[] = [
valid = false;
}

// TODO: check that the networkId in the info.json file matches the directory name.
// TODO: check that the networkCode in the info.json file matches the directory name.

resolve({
valid: valid,
Expand Down

0 comments on commit ca16838

Please sign in to comment.