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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@
"@waves/ts-lib-crypto": "^1.4.4-beta.1",
"@waves/waves-transactions": "^4.2.10",
"axios": "^0.27.2",
"bigint-buffer": "^1.1.5",
"bip32": "^3.0.1",
"bip39": "^3.1.0",
"bitcoinjs-lib": "^6.0.1",
Expand Down
100 changes: 57 additions & 43 deletions src/common/helpers/solanaHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import provider from '../utils/solana';
import * as solanaWeb3 from '@solana/web3.js';
import {
getOrCreateAssociatedTokenAccount,
transfer as transferToken,
getAssociatedTokenAddress,
getMint,
createTransferInstruction
} from '@solana/spl-token';
import {
BalancePayload,
Expand All @@ -18,7 +19,7 @@ import {
TransferPayload,
} from '../utils/types';
import * as bs58 from 'bs58';
import { successResponse } from '../utils';
import { successResponse, parseAmount, formatAmount } from '../utils';
import * as bip39 from 'bip39';
import { derivePath } from 'ed25519-hd-key';
// @ts-ignore
Expand All @@ -39,7 +40,6 @@ export const chainId = {

const getConnection = (rpcUrl?: string) => {
const connection = provider(rpcUrl);

return connection;
};

Expand Down Expand Up @@ -105,30 +105,28 @@ const getBalance = async (args: BalancePayload): Promise<IResponse> => {

try {
let balance;
const publicKey = new solanaWeb3.PublicKey(args.address);
if (args.tokenAddress) {
const account = await connection.getTokenAccountsByOwner(
new solanaWeb3.PublicKey(args.address),
{
mint: new solanaWeb3.PublicKey(args.tokenAddress),
}
);

balance =
account.value.length > 0
? ACCOUNT_LAYOUT.decode(account.value[0].account.data).amount
: 0;

return successResponse({
balance: balance / solanaWeb3.LAMPORTS_PER_SOL,
});
const mintPubkey = new solanaWeb3.PublicKey(args.tokenAddress);
// get token by account
const tokenAccountAddress = await getAssociatedTokenAddress(mintPubkey, publicKey);
const accountInfo = await connection.getAccountInfo(tokenAccountAddress);

// check if account not associated with this return 0 balance
if (!accountInfo) {
return successResponse({
balance: "0",
});
}

const rawBalance = await connection.getTokenAccountBalance(tokenAccountAddress);
balance = rawBalance.value.uiAmount;
} else {
const rawBalance = await connection.getBalance(publicKey);
balance = formatAmount(rawBalance.toString(), 9);
}

const publicKey = new solanaWeb3.PublicKey(args.address);
balance = await connection.getBalance(publicKey);

return successResponse({
balance: balance / solanaWeb3.LAMPORTS_PER_SOL,
});
return successResponse({ balance });
} catch (error) {
throw error;
}
Expand All @@ -139,8 +137,8 @@ const transfer = async (args: TransferPayload): Promise<IResponse> => {

try {
const recipient = new solanaWeb3.PublicKey(args.recipientAddress);
let secretKey;
let signature;
let secretKey: Uint8Array;
let signature: string;

if (args.privateKey.split(',').length > 1) {
secretKey = new Uint8Array(args.privateKey.split(',') as any);
Expand All @@ -152,59 +150,75 @@ const transfer = async (args: TransferPayload): Promise<IResponse> => {
skipValidation: true,
});

const { blockhash } = await connection.getLatestBlockhash();

if (args.tokenAddress) {
// Get token mint
// SPL Token Transfer
const mint = await getMint(
connection,
new solanaWeb3.PublicKey(args.tokenAddress)
);

// Get the token account of the from address, and if it does not exist, create it
const fromTokenAccount = await getOrCreateAssociatedTokenAccount(
connection,
from,
mint.address,
from.publicKey
);

// Get the token account of the recipient address, and if it does not exist, create it
const recipientTokenAccount = await getOrCreateAssociatedTokenAccount(
connection,
from,
mint.address,
recipient
);

signature = await transferToken(
connection,
from,
fromTokenAccount.address,
recipientTokenAccount.address,
from.publicKey,
solanaWeb3.LAMPORTS_PER_SOL * args.amount

const amount = parseAmount(args.amount, mint.decimals);
const tx = new solanaWeb3.Transaction().add(
createTransferInstruction(
fromTokenAccount.address,
recipientTokenAccount.address,
from.publicKey, // owner (signer)
amount,
),
);

tx.recentBlockhash = blockhash;
tx.feePayer = from.publicKey;
tx.sign(from);

// send and confirm
signature = await solanaWeb3.sendAndConfirmTransaction(connection, tx, [from], {
commitment: 'confirmed',
});
} else {
// Native SOL Transfer
const amount = parseAmount(args.amount, 9); // SOL always 9 decimals
const transaction = new solanaWeb3.Transaction().add(
solanaWeb3.SystemProgram.transfer({
fromPubkey: from.publicKey,
toPubkey: recipient,
lamports: solanaWeb3.LAMPORTS_PER_SOL * args.amount,
lamports: amount,
})
);

signature = await solanaWeb3.sendAndConfirmTransaction(
connection,
transaction,
[from]
);
transaction.recentBlockhash = blockhash;
transaction.feePayer = from.publicKey;
transaction.sign(from);

signature = await solanaWeb3.sendAndConfirmTransaction(connection, transaction, [from], {
commitment: 'confirmed',
});
}

const tx = await connection.getTransaction(signature, {
maxSupportedTransactionVersion: 0,
commitment: 'confirmed',
});

return successResponse({
...tx,
...tx
});
} catch (error) {
throw error;
Expand Down
21 changes: 21 additions & 0 deletions src/common/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { IResponse } from './types';
import * as base64 from 'base64-js';
import BigNumber from "bignumber.js";

export const successResponse = (args: IResponse): IResponse => {
return args;
Expand Down Expand Up @@ -111,3 +112,23 @@ export const fromBase64 = (base64String: string): Uint8Array => {
export const toBase64 = (input: Uint8Array): string => {
return base64.fromByteArray(input);
};

/**
* Convert human-readable amount → raw integer (BigInt) by decimals
* ex: 0.1 USDC (decimals 6) => 100000n
*/
export const parseAmount = (amount: string | number, decimals: number): bigint => {
const bn = new BigNumber(amount);
const multiplier = new BigNumber(10).pow(decimals);
return BigInt(bn.times(multiplier).toFixed(0));
};

/**
* Convert raw amount → human-readable string by decimals
* ex: 100000n USDC (decimals 6) => "0.1"
*/
export const formatAmount = (raw: bigint | string, decimals: number): string => {
const bn = new BigNumber(raw.toString());
const divisor = new BigNumber(10).pow(decimals);
return bn.dividedBy(divisor).toString();
};
6 changes: 6 additions & 0 deletions test/wallet.solana.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ describe('MultichainCryptoWallet Solana tests', () => {
});

expect(typeof response).toBe('object');
expect(response.transaction).toHaveProperty('signatures');
expect(Array.isArray(response.transaction.signatures)).toBe(true);
expect(response.transaction.signatures.length).toBeGreaterThan(0);
});

it('transfer Token on Solana', async () => {
Expand All @@ -92,6 +95,9 @@ describe('MultichainCryptoWallet Solana tests', () => {
});

expect(typeof response).toBe('object');
expect(response.transaction).toHaveProperty('signatures');
expect(Array.isArray(response.transaction.signatures)).toBe(true);
expect(response.transaction.signatures.length).toBeGreaterThan(0);
});

it('Get transaction', async () => {
Expand Down