457 lines
20 KiB
JavaScript
457 lines
20 KiB
JavaScript
"use strict";
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.transformTransaction = exports.getTokens = exports.getAmount = exports.getDetails = exports.getTxType = exports.getTargets = exports.extractAccountBalanceDiff = exports.transformTokenInfo = exports.tokenStandardToTokenProgramName = exports.getTokenNameAndSymbol = exports.getTokenMetadata = exports.tokenProgramsInfo = exports.SERUM_ASSET_OWNER_PHANTOM_DEPLOYMENT_PROGRAM_ID = exports.SERUM_ASSET_OWNER_PROGRAM_ID = exports.COMPUTE_BUDGET_PROGRAM_ID = exports.STAKE_PROGRAM_PUBLIC_KEY = exports.WSOL_MINT = exports.SYSTEM_PROGRAM_PUBLIC_KEY = exports.ASSOCIATED_TOKEN_PROGRAM_PUBLIC_KEY = exports.TOKEN_2022_PROGRAM_PUBLIC_KEY = exports.TOKEN_PROGRAM_PUBLIC_KEY = void 0;
|
|
exports.getNativeEffects = getNativeEffects;
|
|
const ts_belt_1 = require("@mobily/ts-belt");
|
|
const env_utils_1 = require("@trezor/env-utils");
|
|
const utils_1 = require("@trezor/utils");
|
|
const bigNumber_1 = require("@trezor/utils/lib/bigNumber");
|
|
const utils_2 = require("./utils");
|
|
exports.TOKEN_PROGRAM_PUBLIC_KEY = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';
|
|
exports.TOKEN_2022_PROGRAM_PUBLIC_KEY = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb';
|
|
exports.ASSOCIATED_TOKEN_PROGRAM_PUBLIC_KEY = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL';
|
|
exports.SYSTEM_PROGRAM_PUBLIC_KEY = '11111111111111111111111111111111';
|
|
exports.WSOL_MINT = 'So11111111111111111111111111111111111111112';
|
|
exports.STAKE_PROGRAM_PUBLIC_KEY = 'Stake11111111111111111111111111111111111111';
|
|
exports.COMPUTE_BUDGET_PROGRAM_ID = 'ComputeBudget111111111111111111111111111111';
|
|
exports.SERUM_ASSET_OWNER_PROGRAM_ID = '4MNPdKu9wFMvEeZBMt3Eipfs5ovVWTJb31pEXDJAAxX5';
|
|
exports.SERUM_ASSET_OWNER_PHANTOM_DEPLOYMENT_PROGRAM_ID = 'DeJBGdMFa1uynnnKiwrVioatTuHmNLpyFKnmB5kaFdzQ';
|
|
const tokenProgramNames = ['spl-token', 'spl-token-2022'];
|
|
exports.tokenProgramsInfo = {
|
|
'spl-token': {
|
|
publicKey: exports.TOKEN_PROGRAM_PUBLIC_KEY,
|
|
tokenStandard: 'SPL',
|
|
},
|
|
'spl-token-2022': {
|
|
publicKey: exports.TOKEN_2022_PROGRAM_PUBLIC_KEY,
|
|
tokenStandard: 'SPL-2022',
|
|
},
|
|
};
|
|
const getTokenMetadata = async () => {
|
|
const env = (0, env_utils_1.isCodesignBuild)() ? 'stable' : 'develop';
|
|
const response = await fetch(`https://data.trezor.io/suite/definitions/${env}/solana.advanced.coin.definitions.v1.json`);
|
|
if (!response.ok) {
|
|
throw Error(response.statusText);
|
|
}
|
|
const data = await response.json();
|
|
data[exports.WSOL_MINT] = { symbol: 'wSOL', name: 'Wrapped SOL' };
|
|
return data;
|
|
};
|
|
exports.getTokenMetadata = getTokenMetadata;
|
|
const getTokenNameAndSymbol = (mint, tokenDetailByMint) => {
|
|
const tokenDetail = tokenDetailByMint[mint];
|
|
return tokenDetail
|
|
? { name: tokenDetail.name, symbol: tokenDetail.symbol }
|
|
: {
|
|
name: mint,
|
|
symbol: (0, utils_2.formatTokenSymbol)(mint),
|
|
};
|
|
};
|
|
exports.getTokenNameAndSymbol = getTokenNameAndSymbol;
|
|
const isTokenProgramName = (programName) => tokenProgramNames.some(name => name === programName);
|
|
const tokenStandardToTokenProgramName = (standard) => {
|
|
const tokenProgram = Object.entries(exports.tokenProgramsInfo).find(([_, programInfo]) => programInfo.tokenStandard === standard);
|
|
if (!tokenProgram)
|
|
throw new Error(`Cannot convert token standard ${standard} to Solana token program name`);
|
|
return tokenProgram[0];
|
|
};
|
|
exports.tokenStandardToTokenProgramName = tokenStandardToTokenProgramName;
|
|
const isSplTokenAccount = (tokenAccount) => {
|
|
const { parsed } = tokenAccount.account.data;
|
|
return (isTokenProgramName(tokenAccount.account.data.program) &&
|
|
'info' in parsed &&
|
|
!!parsed.info &&
|
|
'mint' in parsed.info &&
|
|
typeof parsed.info.mint === 'string' &&
|
|
'tokenAmount' in parsed.info &&
|
|
!!parsed.info.tokenAmount &&
|
|
typeof parsed.info.tokenAmount === 'object' &&
|
|
'amount' in parsed.info.tokenAmount &&
|
|
typeof parsed.info.tokenAmount.amount === 'string' &&
|
|
'decimals' in parsed.info.tokenAmount &&
|
|
typeof parsed.info.tokenAmount.decimals === 'number');
|
|
};
|
|
const transformTokenInfo = (tokenAccounts, tokenDetailByMint) => {
|
|
const tokens = ts_belt_1.F.toMutable((0, ts_belt_1.pipe)(tokenAccounts, ts_belt_1.A.filter(isSplTokenAccount), ts_belt_1.A.map(tokenAccount => {
|
|
const { parsed: { info }, program, } = tokenAccount.account.data;
|
|
return {
|
|
type: exports.tokenProgramsInfo[program].tokenStandard,
|
|
contract: info.mint,
|
|
balance: info.tokenAmount.amount,
|
|
decimals: info.tokenAmount.decimals,
|
|
...(0, exports.getTokenNameAndSymbol)(info.mint, tokenDetailByMint),
|
|
address: tokenAccount.pubkey,
|
|
standard: exports.tokenProgramsInfo[program].tokenStandard,
|
|
};
|
|
}), ts_belt_1.A.reduce({}, (acc, token) => {
|
|
if (acc[token.contract] != null) {
|
|
acc[token.contract].balance = new bigNumber_1.BigNumber(acc[token.contract].balance || '0')
|
|
.plus(token.balance || '0')
|
|
.toString();
|
|
acc[token.contract].accounts.push({
|
|
publicKey: token.address,
|
|
balance: token.balance || '0',
|
|
});
|
|
}
|
|
else {
|
|
const { type, standard, contract, balance, decimals, name, symbol } = token;
|
|
acc[token.contract] = {
|
|
type,
|
|
standard,
|
|
contract,
|
|
balance,
|
|
decimals,
|
|
name,
|
|
symbol,
|
|
accounts: [{ publicKey: token.address, balance: balance || '0' }],
|
|
};
|
|
}
|
|
return acc;
|
|
}), ts_belt_1.D.values));
|
|
return tokens;
|
|
};
|
|
exports.transformTokenInfo = transformTokenInfo;
|
|
const extractAccountBalanceDiff = (transaction, address, isTokenDiff = false) => {
|
|
const pubKeyIndex = transaction.transaction.message.accountKeys.findIndex(ak => ak.pubkey === address);
|
|
if (pubKeyIndex === -1) {
|
|
return null;
|
|
}
|
|
if (isTokenDiff) {
|
|
const preBalance = transaction.meta?.preTokenBalances?.find(balance => balance.accountIndex === pubKeyIndex)?.uiTokenAmount.amount;
|
|
const postBalance = transaction.meta?.postTokenBalances?.find(balance => balance.accountIndex === pubKeyIndex)?.uiTokenAmount.amount;
|
|
return {
|
|
preBalance: new bigNumber_1.BigNumber(preBalance ?? 0),
|
|
postBalance: new bigNumber_1.BigNumber(postBalance ?? 0),
|
|
};
|
|
}
|
|
const preBalance = transaction.meta?.preBalances[pubKeyIndex];
|
|
const postBalance = transaction.meta?.postBalances[pubKeyIndex];
|
|
return {
|
|
preBalance: new bigNumber_1.BigNumber(preBalance?.toString(10) ?? 0),
|
|
postBalance: new bigNumber_1.BigNumber(postBalance?.toString(10) ?? 0),
|
|
};
|
|
};
|
|
exports.extractAccountBalanceDiff = extractAccountBalanceDiff;
|
|
const isWSolTransfer = (ixs) => ixs.find(ix => 'parsed' in ix &&
|
|
!!ix.parsed.info &&
|
|
'mint' in ix.parsed.info &&
|
|
ix.parsed.info.mint === exports.WSOL_MINT);
|
|
function getNativeEffects(transaction) {
|
|
const wSolTransferInstruction = isWSolTransfer(transaction.transaction.message.instructions || []);
|
|
return transaction.transaction.message.accountKeys
|
|
.map(ak => {
|
|
const targetAddress = ak.pubkey;
|
|
const balanceDiff = (0, exports.extractAccountBalanceDiff)(transaction, targetAddress);
|
|
if (wSolTransferInstruction && 'parsed' in wSolTransferInstruction) {
|
|
if ((!!wSolTransferInstruction.parsed.info &&
|
|
'destination' in wSolTransferInstruction.parsed.info &&
|
|
wSolTransferInstruction.parsed.info.destination === targetAddress) ||
|
|
(!!wSolTransferInstruction.parsed.info &&
|
|
'source' in wSolTransferInstruction.parsed.info &&
|
|
wSolTransferInstruction.parsed.info.source === targetAddress)) {
|
|
return null;
|
|
}
|
|
}
|
|
if (!balanceDiff) {
|
|
return null;
|
|
}
|
|
return {
|
|
address: targetAddress,
|
|
amount: balanceDiff.postBalance.minus(balanceDiff.preBalance),
|
|
};
|
|
})
|
|
.filter((effect) => !!effect)
|
|
.filter(({ amount }) => !amount.isZero());
|
|
}
|
|
const getTargets = (effects, txType, accountAddress) => effects
|
|
.filter(effect => {
|
|
if (txType === 'self') {
|
|
return false;
|
|
}
|
|
if (txType === 'unknown') {
|
|
return false;
|
|
}
|
|
if (txType !== 'sent' && effect.address !== accountAddress) {
|
|
return false;
|
|
}
|
|
return effect.amount.isGreaterThan(0);
|
|
})
|
|
.map((effect, i) => {
|
|
const target = {
|
|
n: i,
|
|
addresses: [effect.address],
|
|
isAddress: true,
|
|
amount: effect.amount.abs().toString(),
|
|
isAccountTarget: effect.address === accountAddress && txType !== 'sent',
|
|
};
|
|
return target;
|
|
});
|
|
exports.getTargets = getTargets;
|
|
const getTokenTransferTxType = (transfers) => {
|
|
if (transfers.some(transfer => transfer.to === transfer.from)) {
|
|
return 'self';
|
|
}
|
|
if (transfers.some(({ type }) => type === 'recv')) {
|
|
return 'recv';
|
|
}
|
|
if (transfers.some(({ type }) => type === 'sent')) {
|
|
return 'sent';
|
|
}
|
|
return 'unknown';
|
|
};
|
|
const getNativeTransferTxType = (effects, accountAddress, transaction) => {
|
|
if (effects.length === 1 &&
|
|
effects[0]?.address === accountAddress &&
|
|
effects[0]?.amount.abs().isEqualTo(new bigNumber_1.BigNumber(transaction.meta?.fee.toString() || 0))) {
|
|
return 'self';
|
|
}
|
|
const [senders, receivers] = (0, utils_1.arrayPartition)(effects, ({ amount }) => amount.isNegative());
|
|
if (senders.some(({ address }) => address === accountAddress)) {
|
|
return 'sent';
|
|
}
|
|
if (receivers.some(({ address }) => address === accountAddress)) {
|
|
return 'recv';
|
|
}
|
|
return 'unknown';
|
|
};
|
|
const getTxType = (transaction, effects, accountAddress, tokenTransfers) => {
|
|
if (transaction.meta?.err) {
|
|
return 'failed';
|
|
}
|
|
const isUnknownProgramInstruction = (instruction) => ![
|
|
exports.SYSTEM_PROGRAM_PUBLIC_KEY,
|
|
...Object.values(exports.tokenProgramsInfo).map(info => info.publicKey),
|
|
exports.ASSOCIATED_TOKEN_PROGRAM_PUBLIC_KEY,
|
|
exports.STAKE_PROGRAM_PUBLIC_KEY,
|
|
exports.COMPUTE_BUDGET_PROGRAM_ID,
|
|
exports.SERUM_ASSET_OWNER_PROGRAM_ID,
|
|
exports.SERUM_ASSET_OWNER_PHANTOM_DEPLOYMENT_PROGRAM_ID,
|
|
].includes(instruction.programId);
|
|
if (transaction.transaction.message.instructions.some(isUnknownProgramInstruction)) {
|
|
return 'contract';
|
|
}
|
|
const parsedInstructions = transaction.transaction.message.instructions.filter((instruction) => 'parsed' in instruction);
|
|
if (parsedInstructions.length === 0) {
|
|
return 'unknown';
|
|
}
|
|
const isInstructionCreatingTokenAccount = (instruction) => instruction.program === 'spl-associated-token-account' &&
|
|
(instruction.parsed.type === 'create' || instruction.parsed.type === 'createIdempotent');
|
|
const isTransfer = parsedInstructions.every(instruction => instruction.parsed.type === 'transfer' ||
|
|
instruction.parsed.type === 'transferChecked' ||
|
|
(instruction.program === 'system' && instruction.parsed.type === 'advanceNonce') ||
|
|
isInstructionCreatingTokenAccount(instruction));
|
|
if (isTransfer) {
|
|
return tokenTransfers.length > 0
|
|
? getTokenTransferTxType(tokenTransfers)
|
|
: getNativeTransferTxType(effects, accountAddress, transaction);
|
|
}
|
|
return 'unknown';
|
|
};
|
|
exports.getTxType = getTxType;
|
|
const getDetails = (transaction, effects, accountAddress, txType) => {
|
|
const senders = effects.filter(({ amount }) => amount.isNegative());
|
|
const receivers = effects
|
|
.filter(({ amount, address }) => amount.isPositive() && (txType !== 'sent' ? address === accountAddress : true))
|
|
.filter(({ address }) => !(txType === 'self' && address === accountAddress));
|
|
const getVin = ({ address, amount }, i) => ({
|
|
txid: transaction.transaction.signatures[0].toString(),
|
|
version: transaction.version?.toString(),
|
|
isAddress: true,
|
|
isAccountOwned: address === accountAddress,
|
|
n: i,
|
|
value: amount?.abs().toString(),
|
|
addresses: [address],
|
|
});
|
|
const vin = senders.map((sender, i) => getVin(sender, i));
|
|
const vout = receivers.map((receiver, i) => getVin(receiver, i));
|
|
if (txType === 'self') {
|
|
vout.push(getVin({ address: accountAddress }, vout.length));
|
|
}
|
|
return {
|
|
size: transaction.meta?.computeUnitsConsumed != null
|
|
? Number(transaction.meta?.computeUnitsConsumed)
|
|
: 0,
|
|
totalInput: senders
|
|
.reduce((acc, curr) => acc.plus(curr.amount.abs()), new bigNumber_1.BigNumber(0))
|
|
.toString(),
|
|
totalOutput: receivers
|
|
.reduce((acc, curr) => acc.plus(curr.amount.abs()), new bigNumber_1.BigNumber(0))
|
|
.toString(),
|
|
vin,
|
|
vout,
|
|
};
|
|
};
|
|
exports.getDetails = getDetails;
|
|
const getAmount = (accountEffect, txType) => {
|
|
if (!accountEffect) {
|
|
return '0';
|
|
}
|
|
if (txType === 'self') {
|
|
return '0';
|
|
}
|
|
return accountEffect.amount.abs().toString();
|
|
};
|
|
exports.getAmount = getAmount;
|
|
const isTokenTransferInstruction = (ix) => {
|
|
if (!('parsed' in ix)) {
|
|
return false;
|
|
}
|
|
const { parsed } = ix;
|
|
return ('program' in ix &&
|
|
typeof ix.program === 'string' &&
|
|
isTokenProgramName(ix.program) &&
|
|
'type' in parsed &&
|
|
typeof parsed.type === 'string' &&
|
|
(parsed.type === 'transferChecked' || parsed.type === 'transfer') &&
|
|
'info' in parsed &&
|
|
typeof parsed.info === 'object' &&
|
|
(('authority' in parsed.info && typeof parsed.info.authority === 'string') ||
|
|
('multisigAuthority' in parsed.info &&
|
|
typeof parsed.info.multisigAuthority === 'string')) &&
|
|
'source' in parsed.info &&
|
|
typeof parsed.info.source === 'string' &&
|
|
'destination' in parsed.info &&
|
|
typeof parsed.info.destination === 'string' &&
|
|
(('tokenAmount' in parsed.info &&
|
|
!!parsed.info.tokenAmount &&
|
|
typeof parsed.info.tokenAmount === 'object' &&
|
|
'amount' in parsed.info.tokenAmount &&
|
|
typeof parsed.info.tokenAmount.amount === 'string') ||
|
|
('amount' in parsed.info && typeof parsed.info.amount === 'string')));
|
|
};
|
|
const getTokens = (tx, accountAddress, tokenDetailByMint, tokenAccountsInfos) => {
|
|
const getUiType = ({ parsed }) => {
|
|
const accountAddresses = [
|
|
...tokenAccountsInfos.map(({ address }) => address),
|
|
accountAddress,
|
|
];
|
|
const isAccountDestination = accountAddresses.includes(parsed.info.destination);
|
|
const isAccountSource = accountAddresses.includes(parsed.info.multisigAuthority || parsed.info.authority || parsed.info.source);
|
|
if (isAccountDestination && isAccountSource) {
|
|
return 'self';
|
|
}
|
|
if (isAccountDestination) {
|
|
return 'recv';
|
|
}
|
|
return 'sent';
|
|
};
|
|
const matchTokenAccountInfo = ({ parsed }, address) => address === parsed.info?.source ||
|
|
address === parsed.info.destination ||
|
|
address === parsed.info?.authority;
|
|
const instructions = [
|
|
...tx.transaction.message.instructions,
|
|
...(tx.meta?.innerInstructions?.flatMap(innerIx => innerIx.instructions) ?? []),
|
|
];
|
|
const effects = instructions
|
|
.filter((instruction) => isTokenTransferInstruction(instruction) &&
|
|
tokenAccountsInfos.some(tokenAccountInfo => matchTokenAccountInfo(instruction, tokenAccountInfo.address)))
|
|
.map((ix) => {
|
|
const { parsed, program } = ix;
|
|
const instructionTokenInfo = tokenAccountsInfos.find(tokenAccountInfo => matchTokenAccountInfo(ix, tokenAccountInfo.address));
|
|
const mint = parsed.info.mint || instructionTokenInfo?.mint || 'Unknown token contract';
|
|
const decimals = Number(parsed.info.tokenAmount?.decimals || instructionTokenInfo?.decimals || 0);
|
|
const amount = parsed.info.tokenAmount?.amount || parsed.info.amount || '-1';
|
|
const source = parsed.info.authority || parsed.info.source;
|
|
const from = source === instructionTokenInfo?.address ? accountAddress : source;
|
|
const to = parsed.info.destination === instructionTokenInfo?.address
|
|
? accountAddress
|
|
: parsed.info.destination;
|
|
return {
|
|
type: getUiType(ix),
|
|
standard: exports.tokenProgramsInfo[program].tokenStandard,
|
|
from,
|
|
to,
|
|
contract: mint,
|
|
decimals,
|
|
...(0, exports.getTokenNameAndSymbol)(mint, tokenDetailByMint),
|
|
amount,
|
|
};
|
|
})
|
|
.filter(effect => effect.to === accountAddress || effect.from === accountAddress);
|
|
return effects;
|
|
};
|
|
exports.getTokens = getTokens;
|
|
function getTransactionStakeType(tx) {
|
|
const { instructions } = tx.transaction.message;
|
|
if (!instructions) {
|
|
throw new Error('Invalid transaction data');
|
|
}
|
|
for (const instruction of instructions) {
|
|
if (instruction.programId === exports.STAKE_PROGRAM_PUBLIC_KEY && 'parsed' in instruction) {
|
|
const { type } = instruction.parsed || {};
|
|
if (type === 'delegate')
|
|
return 'stake';
|
|
if (type === 'deactivate')
|
|
return 'unstake';
|
|
if (type === 'withdraw')
|
|
return 'claim';
|
|
}
|
|
}
|
|
return undefined;
|
|
}
|
|
const getUnstakeAmount = (tx) => {
|
|
const { transaction, meta } = tx;
|
|
const { instructions, accountKeys } = transaction.message;
|
|
if (!instructions || !meta) {
|
|
throw new Error('Invalid transaction data');
|
|
}
|
|
const stakeAccountIndexes = instructions
|
|
.filter((instruction) => instruction.programId === exports.STAKE_PROGRAM_PUBLIC_KEY &&
|
|
'parsed' in instruction &&
|
|
instruction.parsed?.type === 'deactivate')
|
|
.map(instruction => {
|
|
if (typeof instruction.parsed?.info === 'object' &&
|
|
'stakeAccount' in instruction.parsed.info) {
|
|
const stakeAccount = instruction.parsed.info?.stakeAccount;
|
|
return accountKeys.findIndex(key => key.pubkey === stakeAccount);
|
|
}
|
|
return -1;
|
|
})
|
|
.filter(index => index >= 0);
|
|
const totalPostBalance = stakeAccountIndexes.reduce((sum, stakeAccountIndex) => sum.plus(new bigNumber_1.BigNumber(meta.postBalances[stakeAccountIndex]?.toString(10) || 0)), new bigNumber_1.BigNumber(0));
|
|
return totalPostBalance.toString();
|
|
};
|
|
const determineTransactionType = (type, stakeType) => {
|
|
if (type !== 'unknown' || !stakeType) {
|
|
return type;
|
|
}
|
|
switch (stakeType) {
|
|
case 'claim':
|
|
return 'recv';
|
|
case 'stake':
|
|
case 'unstake':
|
|
return 'sent';
|
|
default:
|
|
return 'unknown';
|
|
}
|
|
};
|
|
const transformTransaction = (tx, accountAddress, tokenAccountsInfos, tokenDetailByMint = {}) => {
|
|
const nativeEffects = getNativeEffects(tx);
|
|
const tokens = (0, exports.getTokens)(tx, accountAddress, tokenDetailByMint, tokenAccountsInfos);
|
|
const type = (0, exports.getTxType)(tx, nativeEffects, accountAddress, tokens);
|
|
const stakeType = getTransactionStakeType(tx);
|
|
const txType = determineTransactionType(type, stakeType);
|
|
const targets = (0, exports.getTargets)(nativeEffects, txType, accountAddress);
|
|
const amount = stakeType === 'unstake'
|
|
? getUnstakeAmount(tx)
|
|
: (0, exports.getAmount)(nativeEffects.find(({ address }) => address === accountAddress), type);
|
|
const details = (0, exports.getDetails)(tx, nativeEffects, accountAddress, type);
|
|
return {
|
|
type: txType,
|
|
txid: tx.transaction.signatures[0].toString(),
|
|
blockTime: tx.blockTime == null ? undefined : Number(tx.blockTime),
|
|
amount,
|
|
fee: tx.meta.fee.toString(),
|
|
targets,
|
|
tokens,
|
|
internalTransfers: [],
|
|
details,
|
|
blockHash: tx.transaction.message.recentBlockhash,
|
|
solanaSpecific: {
|
|
status: 'confirmed',
|
|
stakeType,
|
|
},
|
|
};
|
|
};
|
|
exports.transformTransaction = transformTransaction;
|
|
//# sourceMappingURL=solana.js.map
|