Skip to content
Open
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: 1 addition & 1 deletion eslint-suppressions.json
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@
},
"packages/solana-wallet-snap/src/core/sdk-extensions/transaction-messages.ts": {
"@typescript-eslint/explicit-function-return-type": {
"count": 4
"count": 3
},
"@typescript-eslint/no-unused-vars": {
"count": 1
Expand Down
2 changes: 0 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,6 @@
"@metamask/snaps-execution-environments": "11.3.0",
"@metamask/snaps-sdk": "12.0.1",
"@metamask/snaps-utils": "12.6.0",
"@solana/addresses": "2.1.0",
"@solana/kit": "2.1.0",
"@stellar/stellar-sdk/axios@npm:1.15.0": "1.18.1",
"@types/react": "18.2.4",
"@types/react-dom": "18.2.4",
Expand Down
1 change: 1 addition & 0 deletions packages/solana-wallet-snap/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- **BREAKING** Update the Solana Name Service integration to SNS SDK v1 and the Kit 6.9-compatible Solana program clients
- Migrate `trackError` and `withCatchAndThrowSnapError` to `@metamask/snap-networks-utils` `createSnapErrorHandling`, and add `getSnapProvider` for Snap RPC access
- Extract Snap-owned assets domain logic into `SnapAssetsAdapter`; `AssetsService` is a thin facade that delegates metadata, market data, fetch, persist, and account asset reads through the adapter (no Core routing yet). ([#121](https://github.com/MetaMask/internal-snaps/pull/121))
- Align `AssetsService` read API with `snap-networks-utils` / AssetsController shapes by adding `getAccountAssetByID`, `getAccountAssetsByIDs`, `getAccountAssetsByScope`, and `getAccountAssets`, and routing Keyring and Send through them (still Snap-owned storage). ([#120](https://github.com/MetaMask/internal-snaps/pull/120))
Expand Down
12 changes: 6 additions & 6 deletions packages/solana-wallet-snap/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,12 @@
"@metamask/superstruct": "^3.4.1",
"@metamask/utils": "^11.11.0",
"@noble/ed25519": "2.1.0",
"@solana-name-service/sns-sdk-kit": "0.9.0-beta",
"@solana-program/compute-budget": "0.7.0",
"@solana-program/system": "0.7.0",
"@solana-program/token": "0.5.1",
"@solana-program/token-2022": "^0.5.0",
"@solana/kit": "2.1.0",
"@solana-name-service/sns-sdk-kit": "^1.0.0",
"@solana-program/compute-budget": "^0.15.0",
"@solana-program/system": "^0.12.0",
"@solana-program/token": "^0.14.0",
"@solana-program/token-2022": "^0.12.0",
"@solana/kit": "^6.9.0",
"@testing-library/jest-dom": "^6.6.2",
"@types/express": "^5.0.0",
"@types/lodash": "^4.17.15",
Expand Down
6 changes: 3 additions & 3 deletions packages/solana-wallet-snap/src/core/fees/FeeCalculator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
} from '@solana-program/compute-budget';
import type {
CompiledTransactionMessage,
IInstructionWithData,
InstructionWithData,
Transaction as KitTransaction,
Lamports,
} from '@solana/kit';
Expand Down Expand Up @@ -185,7 +185,7 @@ export class FeeCalculator {
}

return parseSetComputeUnitLimitInstruction(
computeUnitLimitInstruction as IInstructionWithData<Uint8Array>,
computeUnitLimitInstruction as InstructionWithData<Uint8Array>,
).data.units;
}

Expand All @@ -202,7 +202,7 @@ export class FeeCalculator {
}

return parseSetComputeUnitPriceInstruction(
computeUnitPriceInstruction as IInstructionWithData<Uint8Array>,
computeUnitPriceInstruction as InstructionWithData<Uint8Array>,
).data.microLamports;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ describe('normalizeCompiledTransactionMessage', () => {
]),
},
],
version: 0,
} as unknown as CompiledTransactionMessage;

const result = normalizeCompiledTransactionMessage(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,36 @@
import type { CompiledTransactionMessage } from '@solana/kit';
import type {
CompiledTransactionMessage,
LegacyCompiledTransactionMessage,
V0CompiledTransactionMessage,
} from '@solana/kit';

import type { NormalizedInput } from './types';

type SupportedCompiledTransactionMessage =
| LegacyCompiledTransactionMessage
| V0CompiledTransactionMessage;

const isSupportedCompiledTransactionMessage = (
compiledTransactionMessage: CompiledTransactionMessage,
): compiledTransactionMessage is SupportedCompiledTransactionMessage =>
compiledTransactionMessage.version === 'legacy' ||
compiledTransactionMessage.version === 0;

export const normalizeCompiledTransactionMessage = (
compiledTransactionMessage: CompiledTransactionMessage,
): NormalizedInput => ({
ed25519Signatures: ['signature'], // The compiled transaction message doesn't have ed25519 signatures yet. Best guess is that there will be exactly one, so we fake it.
instructions: compiledTransactionMessage.instructions.map((item) => ({
accounts: [], // We don't need them
data: item.data ?? new Uint8Array(),
programAddress:
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
compiledTransactionMessage.staticAccounts[item.programAddressIndex]!,
})),
});
): NormalizedInput => {
if (!isSupportedCompiledTransactionMessage(compiledTransactionMessage)) {
throw new Error('Version 1 transaction messages are not supported');
}

return {
ed25519Signatures: ['signature'], // The compiled transaction message doesn't have ed25519 signatures yet. Best guess is that there will be exactly one, so we fake it.
instructions: compiledTransactionMessage.instructions.map((item) => ({
accounts: [], // We don't need them
data: item.data ?? new Uint8Array(),
programAddress:
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
compiledTransactionMessage.staticAccounts[item.programAddressIndex]!,
})),
};
};
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type {
CompiledTransactionMessage,
IInstruction,
Instruction,
Transaction as KitTransaction,
} from '@solana/kit';

Expand All @@ -14,5 +14,5 @@ export type NormalizableInput =

export type NormalizedInput = {
ed25519Signatures: readonly any[];
instructions: readonly IInstruction[];
instructions: readonly Instruction[];
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import type { Address } from '@solana/kit';

import { nameResolutionService } from '../../../snapContext';
import { Network } from '../../constants/solana';
import { onNameLookupHandler } from './onNameLookup';

jest.mock('../../../snapContext', () => ({
nameResolutionService: {
resolveAddress: jest.fn(),
resolveDomain: jest.fn(),
tld: '.sns',
},
}));

describe('onNameLookupHandler', () => {
const mockNameResolutionService = nameResolutionService as jest.Mocked<
typeof nameResolutionService
>;

const chainId = Network.Mainnet;
const resolvedAddress =
'36Dn3RWhB8x4c83W6ebQ2C2eH9sh5bQX2nMdkP2cWaA4' as Address;

beforeEach(() => {
jest.clearAllMocks();
});

it.each(['example.sns', 'example.sol'])(
'resolves %s domains',
async (domain) => {
mockNameResolutionService.resolveDomain.mockResolvedValue(
resolvedAddress,
);

const result = await onNameLookupHandler({
chainId,
domain,
});

expect(mockNameResolutionService.resolveDomain).toHaveBeenCalledWith(
chainId,
domain,
);
expect(result).toStrictEqual({
resolvedAddresses: [
{
resolvedAddress,
protocol: 'Solana Name Service',
domainName: domain,
},
],
});
},
);

it.each(['.sns', '.sol', 'example.eth'])(
'does not resolve invalid or unsupported domain %s',
async (domain) => {
const result = await onNameLookupHandler({
chainId,
domain,
});

expect(mockNameResolutionService.resolveDomain).not.toHaveBeenCalled();
expect(result).toBeNull();
},
);

it('resolves addresses to domains', async () => {
mockNameResolutionService.resolveAddress.mockResolvedValue('example.sns');

const result = await onNameLookupHandler({
chainId,
address: resolvedAddress,
});

expect(mockNameResolutionService.resolveAddress).toHaveBeenCalledWith(
chainId,
resolvedAddress,
);
expect(result).toStrictEqual({
resolvedDomains: [
{
resolvedDomain: 'example.sns',
protocol: 'Solana Name Service',
},
],
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@
import { SolanaNameLookupRequestStruct } from './structs';

const SOLANA_NAME_SERVICE_PROTOCOL = 'Solana Name Service';
const SOLANA_NAME_SERVICE_TLDS = ['.sns', '.sol'];

export const onNameLookupHandler: OnNameLookupHandler = async (request) => {
assert(request, SolanaNameLookupRequestStruct);

const { chainId, domain, address } = request;

// regex to match valid .sol domains (at least one character before .sol)
// regex to match valid SNS domains (at least one character before the TLD)
const validDomainRegex = new RegExp(
`^.+\\${nameResolutionService.tld}$`,
`^.+(${SOLANA_NAME_SERVICE_TLDS.map((tld) => `\\${tld}`).join('|')})$`,

Check warning on line 17 in packages/solana-wallet-snap/src/core/handlers/onNameLookup/onNameLookup.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this code to not use nested template literals.

See more on https://sonarcloud.io/project/issues?id=MetaMask_internal-snaps&issues=AaBsVhDhRiLD0DKV-bvA&open=AaBsVhDhRiLD0DKV-bvA&pullRequest=271
'u',
);

Expand Down
16 changes: 9 additions & 7 deletions packages/solana-wallet-snap/src/core/sdk-extensions/codecs.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { Infer } from '@metamask/superstruct';
import type {
CompilableTransactionMessage,
TransactionMessage,
TransactionMessageWithFeePayer,
GetMultipleAccountsApi,
Rpc,
Transaction,
Expand Down Expand Up @@ -28,10 +29,11 @@ import type { Base64Struct } from '../validation/structs';
* @returns The base64 encoded string.
*/
export const fromCompilableTransactionMessageToBase64String = async (
compilableTransactionMessage: CompilableTransactionMessage,
compilableTransactionMessage: TransactionMessage,
): Promise<Infer<typeof Base64Struct>> =>
pipe(
compilableTransactionMessage,
compilableTransactionMessage as TransactionMessage &
TransactionMessageWithFeePayer,
// Compile it.
compileTransactionMessage,
// Convert the compiled message into a byte array.
Expand All @@ -58,7 +60,7 @@ export const fromBase64StringToCompilableTransactionMessage = async (
base64String: Infer<typeof Base64Struct>,
rpc: Rpc<GetMultipleAccountsApi>,
config?: DecompileTransactionMessageFetchingLookupTablesConfig,
): Promise<CompilableTransactionMessage> =>
): Promise<TransactionMessage> =>
pipe(
base64String,
getBase64Encoder().encode,
Expand All @@ -85,7 +87,7 @@ export const fromBytesToCompilableTransactionMessage = async (
messageBytes: TransactionMessageBytes,
rpc: Rpc<GetMultipleAccountsApi>,
config?: DecompileTransactionMessageFetchingLookupTablesConfig,
): Promise<CompilableTransactionMessage> =>
): Promise<TransactionMessage> =>
pipe(
messageBytes,
getCompiledTransactionMessageDecoder().decode,
Expand Down Expand Up @@ -165,8 +167,8 @@ export const fromUnknownBase64StringToTransactionOrTransactionMessage = async (
base64String: Infer<typeof Base64Struct>,
rpc: Rpc<GetMultipleAccountsApi>,
config?: DecompileTransactionMessageFetchingLookupTablesConfig,
): Promise<Transaction | CompilableTransactionMessage> =>
PromiseAny<Transaction | CompilableTransactionMessage>([
): Promise<Transaction | TransactionMessage> =>
PromiseAny<Transaction | TransactionMessage>([
fromBase64StringToTransaction(base64String),
fromBase64StringToCompilableTransactionMessage(base64String, rpc, config),
]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { Rpc, SimulateTransactionApi } from '@solana/kit';
import {
address,
blockhash,
getComputeUnitEstimateForTransactionMessageFactory,
estimateResourceLimitsFactory,
SolanaError,
} from '@solana/kit';

Expand All @@ -23,9 +23,9 @@ import {

jest.mock('@solana/kit', () => ({
...jest.requireActual('@solana/kit'),
getComputeUnitEstimateForTransactionMessageFactory: jest
estimateResourceLimitsFactory: jest
.fn()
.mockReturnValue(jest.fn().mockResolvedValue(500)), // 500 compute units
.mockReturnValue(jest.fn().mockResolvedValue({ computeUnitLimit: 500 })), // 500 compute units
}));

describe('transaction-messages', () => {
Expand Down Expand Up @@ -428,17 +428,15 @@ describe('transaction-messages', () => {
});

it('returns the units consumed from the error if the transaction simulation failed', async () => {
jest
.mocked(getComputeUnitEstimateForTransactionMessageFactory)
.mockReturnValue(
jest.fn().mockRejectedValue(
// This code is the specific error code for failed transaction simulation when estimating the compute unit limit.
// It ensures that the error includes the units consumed.
new SolanaError(5663019, {
unitsConsumed: 150,
}),
),
);
jest.mocked(estimateResourceLimitsFactory).mockReturnValue(
jest.fn().mockRejectedValue(
// This code is the specific error code for failed transaction simulation when estimating the compute unit limit.
// It ensures that the error includes the units consumed.
new SolanaError(5663019, {
unitsConsumed: 150n,
} as never),
),
);

const result = await estimateAndOverrideComputeUnitLimit(
transactionMessageWithNoComputeUnitLimit,
Expand All @@ -451,15 +449,30 @@ describe('transaction-messages', () => {
});
});

it('returns the original transaction message if simulation fails without units consumed', async () => {
jest.mocked(estimateResourceLimitsFactory).mockReturnValue(
jest.fn().mockRejectedValue(
new SolanaError(5663019, {
unitsConsumed: null,
} as never),
),
);

const result = await estimateAndOverrideComputeUnitLimit(
transactionMessageWithNoComputeUnitLimit,
rpc,
);

expect(result).toStrictEqual(transactionMessageWithNoComputeUnitLimit);
});

it('returns the original transaction message if the compute unit limit cannot be estimated', async () => {
jest
.mocked(getComputeUnitEstimateForTransactionMessageFactory)
.mockReturnValue(
jest.fn().mockRejectedValue(
// Some other error code not related to compute unit limit estimation. The error doesn't contain the units consumed.
new SolanaError(8190003),
),
);
jest.mocked(estimateResourceLimitsFactory).mockReturnValue(
jest.fn().mockRejectedValue(
// Some other error code not related to compute unit limit estimation. The error doesn't contain the units consumed.
new SolanaError(8190003),
),
);

const result = await estimateAndOverrideComputeUnitLimit(
transactionMessageWithNoComputeUnitLimit,
Expand Down
Loading