diff --git a/compat-helpers/package.json b/compat-helpers/package.json index 11a116d..c510d94 100644 --- a/compat-helpers/package.json +++ b/compat-helpers/package.json @@ -1,6 +1,6 @@ { "name": "@tensor-foundation/compat-helpers", - "version": "1.0.0-beta.1", + "version": "1.0.0-beta.2", "description": "Helper functions to make old web3.js programs compatible with web3.js-next modules", "sideEffects": false, "module": "./dist/src/index.mjs", diff --git a/compat-helpers/src/accounts.ts b/compat-helpers/src/accounts.ts new file mode 100644 index 0000000..8101411 --- /dev/null +++ b/compat-helpers/src/accounts.ts @@ -0,0 +1,38 @@ +import { AccountInfo, PublicKey } from '@solana/web3.js'; +import { + type EncodedAccount, + type Address, + lamports, + Lamports, +} from '@solana/web3.js-next'; + +export function fromAccountInfoToEncodedAccount< + TAddress extends string = string, +>(address: PublicKey, account: AccountInfo): EncodedAccount { + return { + address: address.toString() as Address, + data: new Uint8Array(account.data), + executable: account.executable, + lamports: lamports(BigInt(account.lamports)), + programAddress: account.owner.toString() as Address, + }; +} + +export function fromEncodedAccountToAccountInfo< + TAddress extends string = string, +>(account: EncodedAccount): AccountInfo { + return { + executable: account.executable, + owner: new PublicKey(account.programAddress), + lamports: lamportsToNumber(account.lamports), + data: Buffer.from(account.data), + }; +} + +function lamportsToNumber(lamportsValue: Lamports): number { + const num = Number(lamportsValue); + if (!Number.isSafeInteger(num)) { + throw new Error('Lamports value too large to convert to number safely'); + } + return num; +}