@deserialize/multi-vm-wallet 1.2.2 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -610,30 +610,4 @@ async function parseTransferLogs(
610
610
  return { tokens, nfts };
611
611
  }
612
612
 
613
- /**
614
- * Helper function to create a client
615
- */
616
- export function createEVMClient(rpcUrl: string) {
617
- return createPublicClient({
618
- transport: http(rpcUrl),
619
- });
620
- }
621
-
622
- // Example usage:
623
- /*
624
- import { mainnet } from 'viem/chains';
625
-
626
- const client = createPublicClient({
627
- chain: mainnet,
628
- transport: http('https://eth-mainnet.g.alchemy.com/v2/YOUR_API_KEY'),
629
- });
630
-
631
- const history = await getEVMTransactionHistoryWithAPI(
632
- client,
633
- '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb' as Address,
634
- 'https://api.etherscan.io/api',
635
- 'YOUR_ETHERSCAN_API_KEY'
636
- );
637
613
 
638
- console.log(history);
639
- */
@@ -1,7 +1,8 @@
1
1
  import { Balance, ChainWalletConfig, SUPPORTED_VM, UserTokenBalance, TokenInfo } from '../types'
2
- import { JsonRpcProvider, Contract, Wallet, TransactionRequest, TransactionResponse, TransactionReceipt, parseUnits, formatUnits } from 'ethers'
2
+ import { JsonRpcProvider, Contract, Wallet, TransactionRequest, TransactionResponse, TransactionReceipt, parseUnits, formatUnits, ethers } from 'ethers'
3
3
  import BN from 'bn.js'
4
4
  import { HelperAPI } from '../helpers';
5
+ import BigNumber from 'bignumber.js';
5
6
 
6
7
  const KYBER_BASE_URL = 'https://aggregator-api.kyberswap.com';
7
8
 
@@ -149,10 +150,11 @@ const ERC20_ABI = [
149
150
 
150
151
  export const getNativeBalance = async (address: string, provider: JsonRpcProvider): Promise<Balance> => {
151
152
  const balance = await provider.getBalance(address)
153
+ const final = ethers.formatEther(balance)
152
154
 
153
155
  return {
154
156
  balance: new BN(balance),
155
- formatted: Number(balance / 10n ** 18n),
157
+ formatted: Number(final),
156
158
  decimal: 18
157
159
  }
158
160
  }
@@ -654,6 +656,24 @@ export const discoverTokens = async (wallet: string, chain: ChainWalletConfig):
654
656
  return formatBalances
655
657
  }
656
658
 
659
+ export function calcGasTotal(gasLimit = '0', gasPrice = '0') {
660
+ return new BN(gasLimit, 16).mul(new BN(gasPrice, 16)).toString();
661
+ }
662
+ export function toPrecisionWithoutTrailingZeros(n: number, precision: number) {
663
+ return new BigNumber(n)
664
+ .toPrecision(precision)
665
+ .replace(/(\.[0-9]*[1-9])0*|(\.0*)/u, '$1');
666
+ }
667
+
668
+ /**
669
+ * @param {number|string|BigNumber} value
670
+ * @param {number=} decimals
671
+ * @returns {BigNumber}
672
+ */
673
+ export function calcTokenAmount(value: number | string | BigNumber, decimals?: number): BigNumber {
674
+ const divisor = new BigNumber(10).pow(decimals ?? 0);
675
+ return new BigNumber(String(value)).div(divisor);
676
+ }
657
677
  //swaps
658
678
 
659
679
 
package/utils/svm/svm.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Connection, Keypair, PublicKey } from "@solana/web3.js";
1
+ import { Connection, Keypair, PublicKey, Transaction, VersionedTransaction } from "@solana/web3.js";
2
2
  import { SVMDeriveChildPrivateKey } from "../walletBip32";
3
3
  import { VM } from "../vm";
4
4
  import { ChainWallet } from "../IChainWallet";
@@ -16,7 +16,9 @@ import {
16
16
  validateJupiterTokens,
17
17
  JupiterQuoteResponse,
18
18
  getTokenInfo,
19
- discoverTokens
19
+ discoverTokens,
20
+ signTransaction,
21
+ sendTransaction
20
22
  } from "./utils";
21
23
  import BN from "bn.js";
22
24
  import nacl from "tweetnacl";
@@ -26,6 +28,7 @@ import { getSVMTransactionHistory, SVMTransactionHistoryItem } from "./transacti
26
28
 
27
29
  export class SVMVM extends VM<PublicKey, Keypair, Connection> {
28
30
  getTokenInfo = getTokenInfo
31
+ static getTokenInfo = getTokenInfo
29
32
  static validateAddress(address: PublicKey): boolean {
30
33
  try {
31
34
  new PublicKey(address)
@@ -54,6 +57,10 @@ export class SVMVM extends VM<PublicKey, Keypair, Connection> {
54
57
 
55
58
  static signAndSendTransaction = signAndSendTransaction
56
59
 
60
+ static signTransaction = signTransaction
61
+
62
+ static sendTransaction = sendTransaction
63
+
57
64
 
58
65
  generatePrivateKey(index: number, seed?: string, mnemonic?: string, derivationPath = this.derivationPath) {
59
66
  let _seed: string
@@ -91,6 +98,8 @@ export class SVMChainWallet extends ChainWallet<PublicKey, Keypair, Connection>
91
98
  return await SVMVM.getNativeBalance(this.address, this.connection!)
92
99
  }
93
100
 
101
+
102
+
94
103
  async getTokenBalance(tokenAddress: PublicKey): Promise<Balance> {
95
104
  // Implement token balance retrieval logic here
96
105
  return await SVMVM.getTokenBalance(this.address, (tokenAddress), this.connection!);
@@ -104,22 +113,38 @@ export class SVMChainWallet extends ChainWallet<PublicKey, Keypair, Connection>
104
113
  async transferNative(to: PublicKey, amount: number): Promise<TransactionResult> {
105
114
  // Implement native transfer logic here
106
115
  const transaction = await getTransferNativeTransaction(this.privateKey, to, amount, this.connection!)
107
- const hash = await SVMVM.signAndSendTransaction(transaction, this.connection!, [this.privateKey]);
116
+ const hash = await SVMVM.signAndSendTransaction(transaction, this.connection!, this.privateKey);
108
117
  return { success: true, hash } // Placeholder
109
118
  }
110
119
 
111
120
  async transferToken(token: TokenInfo, to: PublicKey, amount: number): Promise<TransactionResult> {
112
121
  // Implement token transfer logic here
113
122
  const transaction = await getTransferTokenTransaction(this.privateKey, new PublicKey(to), token, (amount), this.connection!);
114
- const hash = await SVMVM.signAndSendTransaction(transaction, this.connection!, [this.privateKey]);
123
+ const hash = await SVMVM.signAndSendTransaction(transaction, this.connection!, this.privateKey);
115
124
  return { success: true, hash }; // Placeholder
116
125
  }
117
126
 
127
+ async signTransaction(transaction: VersionedTransaction | Transaction) {
128
+ return await SVMVM.signTransaction(transaction, this.privateKey)
129
+ }
130
+
131
+ async sendTransaction(transaction: VersionedTransaction | Transaction) {
132
+ return await SVMVM.sendTransaction(transaction, this.connection!)
133
+ }
134
+
135
+ async signAndSendTransaction(transaction: VersionedTransaction | Transaction) {
136
+ return await SVMVM.signAndSendTransaction(transaction, this.connection!, this.privateKey);
137
+ }
138
+
118
139
  async getTransactionHistory(): Promise<SVMTransactionHistoryItem[]> {
119
140
  const history = await getSVMTransactionHistory(this.connection!, this.address);
120
141
  return history;
121
142
  }
122
143
 
144
+ async getTokenInfo(tokenAddress: PublicKey) {
145
+ return await SVMVM.getTokenInfo(tokenAddress, this.connection!)
146
+ }
147
+
123
148
  async swap(fromToken: TokenInfo, toToken: PublicKey, amount: number, slippage: number = 50): Promise<TransactionResult> {
124
149
  try {
125
150
  if (amount <= 0) {
@@ -235,9 +260,8 @@ export class SVMChainWallet extends ChainWallet<PublicKey, Keypair, Connection>
235
260
  };
236
261
  }
237
262
  }
238
- signMessage = (message: string, signer: Keypair) => {
239
- const messageBytes = new TextEncoder().encode(message);
240
- const signature = nacl.sign.detached(messageBytes, signer.secretKey);
263
+ signMessage = (message: Uint8Array<ArrayBuffer>,) => {
264
+ const signature = nacl.sign.detached(message, this.privateKey.secretKey);
241
265
  return base58.encode(signature);
242
266
  };
243
267
  }
@@ -1,11 +1,19 @@
1
1
  //we will write all the svm utils function here
2
2
 
3
3
  import { Account, createAssociatedTokenAccountIdempotentInstruction, createTransferCheckedInstruction, getAccount, getAssociatedTokenAddress, getAssociatedTokenAddressSync, getMint, Mint, NATIVE_MINT, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from "@solana/spl-token";
4
- import { Connection, Keypair, LAMPORTS_PER_SOL, PublicKey, SystemProgram, TransactionInstruction, TransactionMessage, VersionedTransaction } from "@solana/web3.js";
4
+ import { Connection, Keypair, LAMPORTS_PER_SOL, PublicKey, SystemProgram, Transaction, TransactionInstruction, TransactionMessage, VersionedTransaction } from "@solana/web3.js";
5
5
  import { ChainWalletConfig, UserTokenBalance, TokenInfo } from "../types";
6
6
  import { transactionSenderAndConfirmationWaiter } from "./transactionSender";
7
7
  import { BN } from "bn.js";
8
- import { Metaplex } from "@metaplex-foundation/js";
8
+ import { generateSigner, percentAmount } from '@metaplex-foundation/umi'
9
+ import {
10
+ createNft,
11
+ fetchDigitalAsset,
12
+ mplTokenMetadata,
13
+ } from '@metaplex-foundation/mpl-token-metadata'
14
+ import { createUmi } from "@metaplex-foundation/umi-bundle-defaults";
15
+
16
+ import { PublicKey as UmiPublicKey } from "@metaplex-foundation/umi-public-keys"
9
17
 
10
18
  const JUPITER_BASE_URL = 'https://lite-api.jup.ag';
11
19
 
@@ -271,15 +279,16 @@ export const getTransferNativeTransaction = async (from: Keypair, to: PublicKey,
271
279
  console.log('getTransferNativeTransaction: Completed');
272
280
  return transaction;
273
281
  }
274
- const getMetaTokenMetaplexData = (mintAddress: PublicKey, connection: Connection) => {
275
- const metaplex = Metaplex.make(connection);
276
- return metaplex.nfts().findByMint({ mintAddress: mintAddress });
282
+ const getMetaTokenMetaplexData = async (mintAddress: PublicKey, connection: Connection) => {
283
+ const umi = createUmi(connection.rpcEndpoint).use(mplTokenMetadata())
284
+ const ass = await fetchDigitalAsset(umi, mintAddress.toBase58() as unknown as UmiPublicKey)
285
+ return ass.metadata
286
+
277
287
  }
278
288
 
279
289
  export const getTokenInfo = async (tokenAddress: PublicKey, connection: Connection, programId?: PublicKey): Promise<TokenInfo> => {
280
290
  let mint: Mint
281
291
 
282
-
283
292
  const metaplexData = await getMetaTokenMetaplexData(tokenAddress, connection).catch(() => null);
284
293
  if (programId) {
285
294
  const mint = await getMint(connection, tokenAddress, "confirmed", programId)
@@ -347,17 +356,31 @@ export const getTransferTokenTransaction = async (from: Keypair, to: PublicKey,
347
356
  return transaction;
348
357
  }
349
358
 
350
- export const signAndSendTransaction = async (transaction: VersionedTransaction, connection: Connection, signers: Keypair[]) => {
351
- console.log('signAndSendTransaction: Starting');
352
- console.log('Signers count:', signers.length);
359
+ export const signTransaction = async (
360
+ transaction: VersionedTransaction | Transaction,
361
+ signers: Keypair,
362
+ ): Promise<VersionedTransaction | Transaction> => {
363
+
364
+
365
+ if (transaction instanceof Transaction) {
366
+ transaction.partialSign(signers);
367
+
368
+ } else {
369
+ transaction.sign([signers]);
370
+
371
+ }
372
+
373
+ return transaction;
374
+ };
375
+
376
+ export const sendTransaction = async (
377
+ transaction: VersionedTransaction | Transaction,
378
+ connection: Connection
379
+ ): Promise<string> => {
353
380
 
354
- transaction.sign(signers)
355
- console.log('Transaction signed');
356
381
 
357
- const blockhash = await connection.getLatestBlockhash()
358
- console.log('Got latest blockhash:', blockhash.blockhash);
382
+ const blockhash = await connection.getLatestBlockhash();
359
383
 
360
- console.log('Sending transaction...');
361
384
  const res = await transactionSenderAndConfirmationWaiter({
362
385
  connection,
363
386
  serializedTransaction: Buffer.from(transaction.serialize()),
@@ -375,7 +398,21 @@ export const signAndSendTransaction = async (transaction: VersionedTransaction,
375
398
  const signature = res.transaction.signatures[0];
376
399
  console.log('Transaction successful, signature:', signature);
377
400
  return signature;
378
- }
401
+ };
402
+
403
+ export const signAndSendTransaction = async (
404
+ transaction: VersionedTransaction | Transaction,
405
+ connection: Connection,
406
+ signers: Keypair,
407
+ options?: { partialSign?: boolean }
408
+ ): Promise<string> => {
409
+ console.log('signAndSendTransaction: Starting');
410
+
411
+ const signedTx = await signTransaction(transaction, signers);
412
+ const signature = await sendTransaction(signedTx, connection);
413
+
414
+ return signature;
415
+ };
379
416
  export const discoverTokens = async (ownerAddress: PublicKey, connection: Connection): Promise<UserTokenBalance<PublicKey>[]> => {
380
417
 
381
418
  const owner = new PublicKey(ownerAddress);
package/utils/test.ts CHANGED
@@ -13,6 +13,7 @@ import { } from "./svm/transactionParsing";
13
13
  import { getEVMTransactionHistory } from "./evm/transactionParsing";
14
14
  import { createPublicClient, http, PublicClient } from "viem";
15
15
  import { base, baseGoerli } from "viem/chains";
16
+ import { getTokenInfo } from "./svm/utils";
16
17
  // const mnemonic = GenerateNewMnemonic()
17
18
 
18
19
 
@@ -25,6 +26,7 @@ export const testUserKeyPair = Keypair.fromSecretKey(base58.decode(pKey));
25
26
  const x = testUserKeyPair instanceof Keypair;
26
27
  const evePrivateKey = "0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318"
27
28
  const evmPrivateKey2 = "0x0123456789012345678901234567890123456789012345678901234567890123"
29
+ const ogPrivKey = "d2d3f7117aa9a4c6e5d4affedd8a5ea624ffd82b2a1de81509e5913709b1ea72"
28
30
 
29
31
  // const vm = new SVMVM(seed)
30
32
 
@@ -53,11 +55,21 @@ const evmChainConfig: ChainWalletConfig = {
53
55
  confirmationNo: 1,
54
56
  }
55
57
 
58
+ const OgChainConfig: ChainWalletConfig = {
59
+ chainId: 16661,
60
+ name: "",
61
+ rpcUrl: "https://evmrpc.0g.ai",
62
+ explorerUrl: "",
63
+ nativeToken: { name: "Ethereum", symbol: "ETH", decimals: 18 },
64
+
65
+ }
66
+
56
67
 
57
68
  // const wallet = new SVMChainWallet(chainConfig, testUserKeyPair, 0)
58
- const wallet = new EVMChainWallet(evmChainConfig, evmPrivateKey2, 0)
69
+ const wallet = new EVMChainWallet(OgChainConfig, ogPrivKey, 0)
70
+ wallet.getNativeBalance().then(console.log)
59
71
  // console.log('wallet: ', wallet);
60
-
72
+ // getTokenInfo(new PublicKey("9BB6NFEcjBCtnNLFko2FqVQBq8HHM13kCyYcdQbgpump"), wallet.connection!).then(e => console.log('token info: ', e))
61
73
  // wallet.discoverToken().then(e => console.log('discovered tokens: ', e))
62
74
  // wallet.getNativeBalance().then(e => console.log('native balance: ', e))
63
75
  console.log('address: ', wallet.address);
@@ -99,17 +111,18 @@ const connection = new Connection(RPC_URL);
99
111
  // }).catch((error: any) => {
100
112
  // console.error("Error fetching transaction history:", error);
101
113
  // });
102
- const client = createPublicClient({
103
- chain: base,
104
- transport: http(base.rpcUrls.default.http[0]),
105
- })
106
-
107
- getEVMTransactionHistory(client as PublicClient, "0x9C82CE0e125F61AdE50BC0c19638F6Ba93d71D5e", {
108
- startBlock: BigInt(37427020)
109
- // before: "0xabc..."
110
- }).then((history: any) => {
111
- console.log("EVM Transaction History:", history);
112
- }).catch((error: any) => {
113
- console.error("Error fetching EVM transaction history:", error);
114
- });
114
+ // const client = createPublicClient({
115
+ // chain: base,
116
+ // transport: http(base.rpcUrls.default.http[0]),
117
+ // })
118
+
119
+ // getEVMTransactionHistory(client as PublicClient, "0x9C82CE0e125F61AdE50BC0c19638F6Ba93d71D5e", {
120
+ // startBlock: BigInt(37427020)
121
+ // // before: "0xabc..."
122
+ // }).then((history: any) => {
123
+ // console.log("EVM Transaction History:", history);
124
+ // }).catch((error: any) => {
125
+ // console.error("Error fetching EVM transaction history:", error);
126
+ // });
127
+
115
128