Skip to content

Commit

Permalink
feat: docs references + currying (#1204)
Browse files Browse the repository at this point in the history
  • Loading branch information
ice-chillios authored Feb 24, 2025
1 parent be0ee65 commit 3bb7f61
Show file tree
Hide file tree
Showing 33 changed files with 1,149 additions and 1,275 deletions.
59 changes: 16 additions & 43 deletions bun.lock

Large diffs are not rendered by default.

20 changes: 12 additions & 8 deletions docs/astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ function createTypeDoc(docs, nest = "") {
}

function createDocs() {
/**
* I recommend commenting out unnecessary entries in development as re-generating the docs is a bit slow.
*/
if (!process.env.REFERENCES) {
return { plugins: [], items: [] };
}

const base = createTypeDoc([
{ label: "/core", entrypoint: "core/src/index.ts" },
Expand Down Expand Up @@ -119,11 +119,15 @@ export default defineConfig({
sidebar: [
{ label: "Guides", autogenerate: { directory: "guides" } },
{ label: "Others", autogenerate: { directory: "others" } },
{
label: "References",
collapsed: true,
items: [{ label: "@swapkit", items: docsSidebarItems }],
},
...(process.env.REFERENCES
? [
{
label: "References",
collapsed: true,
items: [{ label: "@swapkit", items: docsSidebarItems }],
},
]
: []),
],
}),
],
Expand Down
6 changes: 1 addition & 5 deletions docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@
"version": "0.0.0",
"scripts": {
"dev": "astro dev",
"start": "astro dev",
"build": "astro build",
"preview": "astro preview",
"astro": "astro"
"deploy": "REFERENCES=true astro build"
},
"dependencies": {
"@astrojs/react": "4.2.0",
Expand All @@ -20,7 +17,6 @@
"@swapkit/toolboxes": "workspace:*",
"@swapkit/wallets": "workspace:*",
"astro": "5.3.0",
"expressive-code-twoslash": "0.4.0",
"sharp": "0.33.5",
"starlight-typedoc": "0.19.0",
"typedoc": "0.27.7",
Expand Down
46 changes: 44 additions & 2 deletions docs/src/content/docs/others/migrate_to_v4.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,50 @@ description: A guide to migrate to v4 and update your codebase.
---

```ts twoslash
import { EVMToolbox } from "@swapkit/toolboxes/evm"
import { BTCToolbox } from "@swapkit/toolboxes/utxo"
import { AVAXToolbox, ETHToolbox, getProvider } from "@swapkit/toolboxes/evm"
import { Chain, createSwapKit, DerivationPath } from "@swapkit/sdk"

const btc = BTCToolbox()
const eth = ETHToolbox({ provider: getProvider(Chain.Ethereum) })
const avax = AVAXToolbox({ provider: getProvider(Chain.Avalanche) })

const ethNetwork = eth.getNetworkParams()
const avaxNetwork = avax.getNetworkParams()

const btcKeys = await btc.createKeysForPath({
phrase: "...",
derivationPath: `${DerivationPath.BTC}/0`,
})

const publicKey = btcKeys.getPublicKey?.();

const skClient = createSwapKit()

skClient.swap
// ^|






















const evm = EVMToolbox



Expand All @@ -20,6 +61,7 @@ const evm = EVMToolbox

```

# MIGRATE FROM CORE v3 to v4

> [!IMPORTANT]Read before continue
> We migrated to combined functionality packages to simplify developer experience. You will have to change imports to use the new version of the packages.
Expand Down
16 changes: 9 additions & 7 deletions packages/core/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ export function SwapKit<
const wallet = getWallet(chain);
if (type === "transfer") {
const txObject = await wallet.createTransferTx(params);
return wallet.estimateTransactionFee(txObject, feeOptionKey);
return wallet.estimateTransactionFee({ ...txObject, chain, feeOption: feeOptionKey });
}

if (type === "approve" && !assetValue.isGasAsset) {
Expand All @@ -321,7 +321,7 @@ export function SwapKit<
from: wallet.address,
});

return wallet.estimateTransactionFee(approvalTx, feeOptionKey);
return wallet.estimateTransactionFee({ ...approvalTx, chain, feeOption: feeOptionKey });
}

if (type === "swap") {
Expand All @@ -333,18 +333,20 @@ export function SwapKit<
assetValue,
});

return wallet.estimateTransactionFee(txObject, feeOptionKey);
return wallet.estimateTransactionFee({ ...txObject, chain, feeOption: feeOptionKey });
}

const { tx } = params.route;
if (!tx) {
return undefined;
}

return wallet.estimateTransactionFee(
{ ...(tx as EVMTransaction), value: BigInt((tx as EVMTransaction).value) },
feeOptionKey,
);
return wallet.estimateTransactionFee({
...(tx as EVMTransaction),
value: BigInt((tx as EVMTransaction).value),
feeOption: feeOptionKey,
chain,
});
}

return AssetValue.from({ chain });
Expand Down
2 changes: 1 addition & 1 deletion packages/helpers/src/types/chains.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ export const MAYASupportedChains = [

export const RPC_URLS: Record<Chain | StagenetChain, string> = {
[Chain.Arbitrum]: "https://arb1.arbitrum.io/rpc",
[Chain.Avalanche]: "https://avalanche-c-chain-rpc.publicnode.com",
[Chain.Avalanche]: "https://api.avax.network/ext/bc/C/rpc",
[Chain.Base]: "https://base-rpc.publicnode.com",
[Chain.BinanceSmartChain]: "https://bsc-dataseed.binance.org",
[Chain.BitcoinCash]: "https://node-router.thorswap.net/bitcoin-cash",
Expand Down
24 changes: 15 additions & 9 deletions packages/helpers/src/utils/wallets.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { BrowserProvider } from "ethers";
import type { getToolboxByChain } from "@swapkit/toolboxes/evm";
import type { BrowserProvider, JsonRpcPayload, Provider } from "ethers";
import { SwapKitError } from "../modules/swapKitError";
import {
type AddChainType,
Expand Down Expand Up @@ -116,12 +117,16 @@ export function wrapMethodWithNetworkSwitch<T extends (...args: any[]) => any>(
}) as unknown as T;
}

export function prepareNetworkSwitch<T extends { [key: string]: (...args: any[]) => any }>({
export function prepareNetworkSwitch<
T extends ReturnType<ReturnType<typeof getToolboxByChain>>,
P extends BrowserProvider | Provider | JsonRpcPayload | undefined,
M extends keyof T,
>({
toolbox,
chain,
provider = window.ethereum,
methodNames = [],
}: { toolbox: T; chain: Chain; provider?: BrowserProvider; methodNames?: string[] }) {
}: { toolbox: T; chain: Chain; provider?: P; methodNames?: M[] }) {
const methodsToWrap = [
...methodNames,
"approve",
Expand All @@ -138,18 +143,19 @@ export function prepareNetworkSwitch<T extends { [key: string]: (...args: any[])
"estimateGasLimit",
"estimateGasPrices",
"createContractTxObject",
];
] as M[];
const wrappedMethods = methodsToWrap.reduce((object, methodName) => {
if (!toolbox[methodName]) return object;

const method = toolbox[methodName];

if (typeof method !== "function") return object;

return {
// biome-ignore lint/performance/noAccumulatingSpread: This is a valid use case
...object,
[methodName]: wrapMethodWithNetworkSwitch<typeof method>(method, provider, chain),
};
// @ts-expect-error
const wrappedMethod = wrapMethodWithNetworkSwitch(method, provider, chain);

// biome-ignore lint/performance/noAccumulatingSpread: valid use case
return { ...object, [methodName]: wrappedMethod };
}, {});

return { ...toolbox, ...wrappedMethods };
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/src/evm/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export const EVMPlugin = createPlugin({
}

const { from, to, data, value } = tx as EVMTransaction;
return wallet.sendTransaction({ from, to, data, value: BigInt(value) }, feeOptionKey);
return wallet.sendTransaction({ from, to, data, value: BigInt(value), feeOptionKey });
},
}),
});
8 changes: 4 additions & 4 deletions packages/toolboxes/src/evm/__tests__/ethereum.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test";
import type ethers from "@nomicfoundation/hardhat-ethers";
import { AssetValue, Chain, FeeOption } from "@swapkit/helpers";
import { AssetValue, Chain } from "@swapkit/helpers";
import { erc20ABI } from "@swapkit/helpers/contracts";
import type { JsonRpcProvider } from "ethers";
// import hre from "hardhat";
Expand Down Expand Up @@ -74,7 +74,7 @@ describe("Ethereum toolkit", () => {
test.todo(
"Send Token",
async () => {
const USDC = await context.toolbox.createContract(USDCAddress, erc20ABI, context.provider);
const USDC = await context.toolbox.createContract(USDCAddress, erc20ABI);
const balance = await USDC.balanceOf?.(emptyRecipient);
expect(balance.toString()).toBe("0");
await context.toolbox.transfer({
Expand Down Expand Up @@ -124,7 +124,7 @@ describe("Ethereum toolkit", () => {
test.todo(
"Create contract tx object and sendTransaction",
async () => {
const USDC = context.toolbox.createContract(USDCAddress, erc20ABI, context.provider);
const USDC = context.toolbox.createContract(USDCAddress, erc20ABI);
const balance = await USDC.balanceOf?.(emptyRecipient);
expect(balance.toString()).toBe("0");

Expand All @@ -138,7 +138,7 @@ describe("Ethereum toolkit", () => {
},
});

await context.toolbox.sendTransaction(txObject, FeeOption.Average);
await context.toolbox.sendTransaction(txObject);
// biome-ignore lint/correctness/noUnsafeOptionalChaining: <explanation>
expect((await USDC?.balanceOf?.(emptyRecipient)).toString()).toBe("2222222");
},
Expand Down
63 changes: 33 additions & 30 deletions packages/toolboxes/src/evm/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import {
import type { BrowserProvider, JsonRpcProvider, Provider } from "ethers";

import { getEvmApi } from "./api";
import { type EIP1559TxParams, type EVMMaxSendableAmountsParams, estimateGasPrices } from "./index";
import { getEstimateGasPrices } from "./toolbox/baseEVMToolbox";
import type { EIP1559TxParams, EVMMaxSendableAmountsParams } from "./types";

export const estimateMaxSendableAmount = async ({
toolbox,
Expand Down Expand Up @@ -72,7 +73,9 @@ export const estimateMaxSendableAmount = async ({
return AssetValue.from({ chain: balance.chain, value: maxSendableAmount.getValue("string") });
};

export const toHexString = (value: bigint) => (value > 0n ? `0x${value.toString(16)}` : "0x0");
export function toHexString(value: bigint) {
return value > 0n ? `0x${value.toString(16)}` : "0x0";
}

export const getBalance = async ({
provider,
Expand Down Expand Up @@ -114,32 +117,32 @@ export const getBalance = async ({
);
};

export const estimateTransactionFee = async (
txObject: EIP1559TxParams,
// biome-ignore lint/style/useDefaultParameterLast: Should only be used through wrapped toolboxes
feeOption: FeeOption = FeeOption.Fast,
chain: EVMChain,
provider: Provider | BrowserProvider,
export function getEstimateTransactionFee({
provider,
isEIP1559Compatible = true,
) => {
const gasPrices = (await estimateGasPrices(provider, isEIP1559Compatible))[feeOption];
const gasLimit = await provider.estimateGas(txObject);
const assetValue = AssetValue.from({ chain });

if (!isEIP1559Compatible && gasPrices.gasPrice) {
return assetValue.set(
SwapKitNumber.fromBigInt(gasPrices.gasPrice * gasLimit, assetValue.decimal),
);
}

if (gasPrices.maxFeePerGas && gasPrices.maxPriorityFeePerGas) {
return assetValue.set(
SwapKitNumber.fromBigInt(
(gasPrices.maxFeePerGas + gasPrices.maxPriorityFeePerGas) * gasLimit,
assetValue.decimal,
),
);
}

throw new Error("No gas price found");
};
}: { provider: Provider | BrowserProvider; isEIP1559Compatible?: boolean }) {
return async function estimateTransactionFee({
feeOption = FeeOption.Fast,
chain,
...txObject
}: EIP1559TxParams & { feeOption: FeeOption; chain: EVMChain }) {
const estimateGasPrices = getEstimateGasPrices({ provider, isEIP1559Compatible });
const gasPrices = await estimateGasPrices();
const gasLimit = await provider.estimateGas(txObject);

const assetValue = AssetValue.from({ chain });
const { gasPrice, maxFeePerGas, maxPriorityFeePerGas } = gasPrices[feeOption];

if (!isEIP1559Compatible && gasPrice) {
return assetValue.set(SwapKitNumber.fromBigInt(gasPrice * gasLimit, assetValue.decimal));
}

if (maxFeePerGas && maxPriorityFeePerGas) {
const fee = (maxFeePerGas + maxPriorityFeePerGas) * gasLimit;

return assetValue.set(SwapKitNumber.fromBigInt(fee, assetValue.decimal));
}

throw new Error("No gas price found");
};
}
10 changes: 3 additions & 7 deletions packages/toolboxes/src/evm/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,13 @@
export * from "./api";
export * from "./helpers";
export * from "./provider";
export * from "./toolbox/EVMToolbox";
export * from "./toolbox/baseEVMToolbox";
export * from "./types";

/**
* Toolboxes
*/
export * from "./toolbox/arb";
export * from "./toolbox/avax";
export * from "./toolbox/bsc";
export * from "./toolbox/eth";
export * from "./toolbox/baseEVMToolbox";
export * from "./toolbox/getToolboxByChain";
export * from "./toolbox/matic";
export * from "./toolbox/op";
export * from "./toolbox/base";
export * from "./toolbox/evm";
Loading

0 comments on commit 3bb7f61

Please sign in to comment.