Skip to content
Draft
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
100 changes: 69 additions & 31 deletions modules/statics/src/coins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,14 @@ allCoinsAndTokens.forEach((coin) => {
// onboarding doesn't require hand-maintaining that map for every new EVM family.
registerErc20Families(erc20FamilySupportsEip1559);

// implement the old method where we had extracted the tokenInitialisation to a different function
export function createToken(token: AmsTokenConfig): Readonly<BaseCoin> | undefined {
// known coins are returned untouched: base chains are never replaced, and token
// refreshes are owned by the map builders that hold the CoinMap being returned
const existingCoin = findExistingCoin(token);
if (existingCoin) {
return existingCoin;
}
if (!token.isToken) {
try {
return buildDynamicCoin(token);
Expand All @@ -93,6 +100,10 @@ export function createToken(token: AmsTokenConfig): Readonly<BaseCoin> | undefin
return undefined;
}
}
return constructToken(token);
}

function constructToken(token: AmsTokenConfig): Readonly<BaseCoin> | undefined {
const initializerMap: Record<string, unknown> = {
algo: algoToken,
apt: aptToken,
Expand Down Expand Up @@ -150,18 +161,6 @@ export function createToken(token: AmsTokenConfig): Readonly<BaseCoin> | undefin
initializerMap[key] = erc721Token;
});

//return the BaseCoin from default coin map if present
if (isCoinPresentInCoinMap({ ...token })) {
if (coins.has(token.name)) {
return coins.get(token.name);
}
if (coins.has(token.id)) {
return coins.get(token.id);
}
if (token.alias && coins.has(token.alias)) {
return coins.get(token.alias);
}
}
const family = token.family;
const initializer = initializerMap[family] as (...args: unknown[]) => Readonly<BaseCoin>;
if (!initializer) {
Expand Down Expand Up @@ -454,6 +453,22 @@ export function isCoinPresentInCoinMap({ name, id, alias }: { name: string; id?:
return Boolean(coins.has(name) || (id && coins.has(id)) || (alias && coins.has(alias)));
}

function findExistingCoin({
name,
id,
alias,
}: {
name: string;
id?: string;
alias?: string;
}): Readonly<BaseCoin> | undefined {
return (
coins.getOrUndefined(name) ??
(id ? coins.getOrUndefined(id) : undefined) ??
(alias ? coins.getOrUndefined(alias) : undefined)
);
}

export function createTokenMapUsingConfigDetails(tokenConfigMap: Record<string, AmsTokenConfig[]>): CoinMap {
const BaseCoins: Map<string, Readonly<BaseCoin>> = new Map();

Expand Down Expand Up @@ -501,27 +516,47 @@ export function createTokenMapUsingConfigDetails(tokenConfigMap: Record<string,
for (const tokenConfigs of Object.values(tokenConfigMap)) {
if (!tokenConfigs.length) continue;
const tokenConfig = tokenConfigs[0];

if (!isCoinPresentInCoinMap({ ...tokenConfig }) && !nftAndOtherTokens.has(tokenConfig.name)) {
try {
const token = createToken(tokenConfig);
// A token whose name is absent from the accumulated map can still reuse a contract address
// (or NFT collection id) already claimed by a static or previously-accepted AMS token.
// Adding it would make the final CoinMap.fromCoins throw, so skip it instead.
if (token && !accumulatedMap.hasTokenAddressConflict(token)) {
BaseCoins.set(token.name, token);
accumulatedMap.addCoin(token);
} else if (token) {
const existingCoin = findExistingCoin({ ...tokenConfig });
// instead of skipping, let known tokens flow so the AMS record can refresh
// them; known base chains are never replaced
if (existingCoin && !(tokenConfig.isToken && existingCoin.isToken)) continue;
if (!nftAndOtherTokens.has(tokenConfig.name)) {
if (existingCoin) {
// The skip above guarantees both records are tokens — base chains never
// flow through, so an AMS entry can never swap a known coin's class.
// Guard rejections throw inside replace before mutating, so the seeded
// entries stay correct and only the warn fires.
try {
const refreshedCoin = constructToken(tokenConfig);
if (refreshedCoin) {
coins.replace(refreshedCoin);
BaseCoins.set(refreshedCoin.name, refreshedCoin);
accumulatedMap.replace(refreshedCoin);
}
} catch (error) {
console.warn(`Failed to refresh coin ${tokenConfig.name} (${tokenConfig.id}):`, error);
}
} else {
try {
const token = createToken(tokenConfig);
// A token whose name is absent from the accumulated map can still reuse a contract address
// (or NFT collection id) already claimed by a static or previously-accepted AMS token.
// Adding it would make the final CoinMap.fromCoins throw, so skip it instead.
if (token && !accumulatedMap.hasTokenAddressConflict(token)) {
BaseCoins.set(token.name, token);
accumulatedMap.addCoin(token);
} else if (token) {
console.warn(
`Skipping token with conflicting contract address or NFT collection id: name="${tokenConfig.name}" id="${tokenConfig.id}"`
);
}
} catch (e) {
console.warn(
`Skipping token with conflicting contract address or NFT collection id: name="${tokenConfig.name}" id="${tokenConfig.id}"`
`Skipping malformed token: name="${tokenConfig.name}" id="${tokenConfig.id}" family="${
tokenConfig.family
}" error=${(e as Error).message}`
);
}
} catch (e) {
console.warn(
`Skipping malformed token: name="${tokenConfig.name}" id="${tokenConfig.id}" family="${
tokenConfig.family
}" error=${(e as Error).message}`
);
}
}
}
Expand Down Expand Up @@ -568,7 +603,10 @@ export function createTokenMapUsingTrimmedConfigDetails(
for (const tokenConfig of tokenConfigs) {
const network = networkNameMap.get(tokenConfig.network.name);

if (isCoinPresentInCoinMap({ ...tokenConfig })) continue;
// instead of skipping, let known tokens continue so the AMS record can
// refresh them; known base chains are never replaced
const existingCoin = findExistingCoin({ ...tokenConfig });
if (existingCoin && !(tokenConfig.isToken && existingCoin.isToken)) continue;

if (!tokenConfig.isToken) {
// Dynamic base chain — network must be pre-registered in networkByName map before calling this function.
Expand Down
16 changes: 16 additions & 0 deletions modules/statics/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,19 @@ export class ChainIdNotFoundError extends BitGoStaticsError {
Object.setPrototypeOf(this, CoinNotDefinedError.prototype);
}
}

export class CoinClassMismatchError extends BitGoStaticsError {
public constructor(coinName: string, existingClass: string, newClass: string) {
super(
`cannot replace coin '${coinName}': existing class ${existingClass} differs from replacement class ${newClass}`
);
Object.setPrototypeOf(this, CoinClassMismatchError.prototype);
}
}

export class CoinImmutableFieldsMismatchError extends BitGoStaticsError {
public constructor(coinName: string, field: string) {
super(`cannot replace coin '${coinName}': immutable field mismatch — ${field}`);
Object.setPrototypeOf(this, CoinImmutableFieldsMismatchError.prototype);
}
}
2 changes: 1 addition & 1 deletion modules/statics/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export {
SUPPORTED_SOL_TOKEN_EXTENSION_NAMES,
getUnsupportedSolTokenExtensions,
} from './account';
export { CoinMap } from './map';
export { CoinMap, assertImmutableFieldsUnchanged } from './map';
export {
networkFeatureMapForTokens,
registerNetworkFeatures,
Expand Down
56 changes: 54 additions & 2 deletions modules/statics/src/map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,58 @@ import { BaseCoin } from './base';
import {
DuplicateCoinDefinitionError,
CoinNotDefinedError,
CoinClassMismatchError,
CoinImmutableFieldsMismatchError,
DuplicateCoinIdDefinitionError,
DuplicateContractAddressDefinitionError,
DuplicateNftCollectionIdDefinitionError,
} from './errors';
import { ContractAddressDefinedToken, NFTCollectionIdDefinedToken } from './account';
import { EthereumNetwork } from './networks';

type ContractAddressRecord = { contractAddress?: string; tokenAddress?: string };

function getContractAddress(coin: Readonly<BaseCoin> | ContractAddressRecord): string | undefined {
// BaseCoin doesn't declare the optional address fields (they live on token
// subclasses); the structural read casts once inside this boundary
const record = coin as ContractAddressRecord;
return (record.contractAddress ?? record.tokenAddress)?.toLowerCase();
}

/**
* Identity fields an AMS refresh must never redefine. Throws
* CoinImmutableFieldsMismatchError on the first mismatched field.
*/
export function assertImmutableFieldsUnchanged(
existingCoin: Readonly<BaseCoin>,
// accepts either a full coin or the identity fields of an AMS token record
replacement: { id: string; name: string; alias?: string } & ContractAddressRecord
): void {
if (existingCoin.id !== replacement.id) {
throw new CoinImmutableFieldsMismatchError(existingCoin.name, `id '${existingCoin.id}' -> '${replacement.id}'`);
}
if (existingCoin.name !== replacement.name) {
throw new CoinImmutableFieldsMismatchError(
existingCoin.name,
`name '${existingCoin.name}' -> '${replacement.name}'`
);
}
if (existingCoin.alias !== replacement.alias) {
throw new CoinImmutableFieldsMismatchError(
existingCoin.name,
`alias '${existingCoin.alias ?? 'none'}' -> '${replacement.alias ?? 'none'}'`
);
}
const existingAddress = getContractAddress(existingCoin);
const replacementAddress = getContractAddress(replacement);
if (existingAddress !== replacementAddress) {
throw new CoinImmutableFieldsMismatchError(
existingCoin.name,
`contractAddress '${existingAddress ?? 'none'}' -> '${replacementAddress ?? 'none'}'`
);
}
}

export class CoinMap {
private readonly _map = new Map<string, Readonly<BaseCoin>>();
private readonly _coinByIds = new Map<string, Readonly<BaseCoin>>();
Expand Down Expand Up @@ -111,8 +156,15 @@ export class CoinMap {
* @param {Readonly<BaseCoin>} coin new coin object
*/
public replace(coin: Readonly<BaseCoin>): void {
if (this.has(coin.id)) {
const oldCoin = this.get(coin.id);
const oldCoin = this.getOrUndefined(coin.id);
if (oldCoin) {
// an id match must always be the same coin class — swapping classes would
// silently change behavior for every consumer keyed off this map
if (oldCoin.constructor !== coin.constructor) {
throw new CoinClassMismatchError(oldCoin.name, oldCoin.constructor.name, coin.constructor.name);
}
// immutable identity fields (id, name, alias, contract address) must survive a replacement
assertImmutableFieldsUnchanged(oldCoin, coin);
this._map.delete(oldCoin.name);
this._coinByIds.delete(oldCoin.id);
if (oldCoin.alias) {
Expand Down
Loading
Loading