Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: depricate provider param from sdk #41

Merged
merged 4 commits into from
Sep 12, 2024
Merged
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
14 changes: 9 additions & 5 deletions docs/docs/03-sdk/01-overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,19 @@ import { Sprinter } from '@chainsafe/sprinter-sdk';

### 2. Initialize the Sprinter SDK

To initialize the SDK, create a new instance of the `Sprinter` class with an Ethereum provider:
To initialize the SDK, create a new instance of the `Sprinter` class:

```typescript
const sprinter = new Sprinter(window.ethereum);
const sprinter = new Sprinter();
```

### 3. Fetch User Balances

Once initialized, you can fetch the user's balances across multiple blockchains:

```typescript
sprinter.getUserBalances().then(console.log);
const ownerAddress = "0x3E101Ec02e7A48D16DADE204C96bFF842E7E2519";
sprinter.getUserBalances(ownerAddress).then(console.log);
```

### 4. Get Solution
Expand All @@ -69,14 +70,17 @@ Here's a more detailed example that combines all the basic operations:
```typescript
import { Sprinter } from '@chainsafe/sprinter-sdk';

const sprinter = new Sprinter(window.ethereum);
const sprinter = new Sprinter();

const ownerAddress = "0x3E101Ec02e7A48D16DADE204C96bFF842E7E2519";

// Fetch user balances
sprinter.getUserBalances().then(balances => {
sprinter.getUserBalances(ownerAddress).then(balances => {
console.log('User balances:', balances);

// Get solution for transactions
return sprinter.getSolution({
account: ownerAddress,
token: "USDC",
destinationChain: 42161, // Destination chain ID
amount: "1000000000" // Amount in the smallest unit (e.g., wei)
Expand Down
10 changes: 7 additions & 3 deletions docs/docs/03-sdk/02-advanced-usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ The dApp is responsible for handling errors that occur during the transaction pr
### Example

```typescript
sprinter.getUserBalances()
const ownerAddress = "0x3E101Ec02e7A48D16DADE204C96bFF842E7E2519";
sprinter.getUserBalances(ownerAddress)
.then(balances => {
console.log('User balances:', balances);
})
Expand All @@ -31,7 +32,9 @@ The Sprinter SDK allows you to customize requests to suit your application's nee
### Example

```typescript
const ownerAddress = "0x3E101Ec02e7A48D16DADE204C96bFF842E7E2519";
sprinter.getSolution({
account: ownerAddress,
token: "USDC",
destinationChain: 42161, // Destination chain ID
amount: "1000000000" // Amount in the smallest unit (e.g., wei)
Expand All @@ -58,12 +61,13 @@ async function integrateWithWeb3() {
const web3 = new Web3(window.ethereum);
const accounts = await web3.eth.requestAccounts();

const sprinter = new Sprinter(window.ethereum);
const sprinter = new Sprinter();

const balances = await sprinter.getUserBalances();
const balances = await sprinter.getUserBalances(accounts[0]);
console.log('User balances:', balances);

const solution = await sprinter.getSolution({
account: accounts[0],
token: "USDC",
destinationChain: 42161,
amount: "1000000000"
Expand Down
28 changes: 16 additions & 12 deletions docs/docs/03-sdk/03-class-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,18 @@ This section details the methods available to the `Sprinter` class in the Sprint

## Methods

### `constructor(provider: EIP1193Provider)`
### `constructor(fetchOptions: Omit<FetchOptions, "signal">)`

Initializes the SDK with the given Ethereum provider.

#### Parameters

- `provider`: An Ethereum provider instance conforming to the EIP-1193 standard (e.g., `window.ethereum`).
- `fetchOptions`: TODO :Sad:

#### Example

```typescript
const sprinter = new Sprinter(window.ethereum);
const sprinter = new Sprinter();
```

### `getAvailableTokens(): Promise<FungibleToken[]>`
Expand Down Expand Up @@ -54,12 +54,13 @@ sprinter.getAvailableChains().then(chains => {
});
```

### `getUserBalances(tokens?: FungibleToken[]): Promise<{ [symbol: TokenSymbol]: { balances: FungibleTokenBalance[]; total: string } }>`
### `getUserBalances(account: Address, tokens?: FungibleToken[]): Promise<{ [symbol: TokenSymbol]: { balances: FungibleTokenBalance[]; total: string } }>`

Fetches the user's balances for specified tokens across multiple blockchains. If no tokens are specified, it fetches balances for all available tokens.

#### Parameters

- `account`: Targeted account address.
- `tokens`: An optional array of fungible token objects.

#### Returns
Expand All @@ -69,24 +70,25 @@ Fetches the user's balances for specified tokens across multiple blockchains. If
#### Example

```typescript
sprinter.getUserBalances().then(balances => {
const ownerAddress = "0x3E101Ec02e7A48D16DADE204C96bFF842E7E2519";
sprinter.getUserBalances(ownerAddress).then(balances => {
console.log('User balances:', balances);
});
```

### `getSolution(settings: Omit<SolutionOptions, "account">, targetAccount?: Address): Promise<SolutionResponse>`
### `getSolution(settings: SolutionOptions): Promise<SolutionResponse>`

Retrieves the optimal solution for managing cross-chain transactions based on the provided settings.

#### Parameters

- `settings`: An object containing the parameters for the solution request, excluding the account.
- `token`: The token symbol (e.g., "USDC").
- `destinationChain`: The ID of the destination blockchain.
- `amount`: The amount to be transferred.
- `threshold?`: An optional threshold parameter.
- `whitelistedSourceChains?`: An optional array of whitelisted source chain IDs.
- `targetAccount`: An optional account address. If not provided, the current account will be used.
- `account`: Targeted account address.
- `token`: The token symbol (e.g., "USDC").
- `destinationChain`: The ID of the destination blockchain.
- `amount`: The amount to be transferred.
- `threshold?`: An optional threshold parameter.
- `whitelistedSourceChains?`: An optional array of whitelisted source chain IDs.

#### Returns

Expand All @@ -95,7 +97,9 @@ Retrieves the optimal solution for managing cross-chain transactions based on th
#### Example

```typescript
const ownerAddress = "0x3E101Ec02e7A48D16DADE204C96bFF842E7E2519";
sprinter.getSolution({
account: ownerAddress,
token: "USDC",
destinationChain: 42161, // Destination chain ID
amount: 1000000000 // Amount in the smallest unit (e.g., wei)
Expand Down
5 changes: 3 additions & 2 deletions packages/sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,10 @@ The `Sprinter` class provides a convenient interface for interacting with the bl
```typescript
import { Sprinter } from '@chainsafe/sprinter-sdk';

const sprinter = new Sprinter(window.ethereum);
const sprinter = new Sprinter();

sprinter.getUserBalances().then(console.log);
const ownerAddress = "0x3E101Ec02e7A48D16DADE204C96bFF842E7E2519";
sprinter.getUserBalances(ownerAddress).then(console.log);
```

### Calling API Endpoints Directly
Expand Down
1 change: 0 additions & 1 deletion packages/sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
"devDependencies": {
"@types/eslint": "^8.56.11",
"@types/node": "18.19.42",
"eip1193-types": "^0.2.1",
"eslint": "^8.57.0",
"typescript": "^5.0.3"
}
Expand Down
54 changes: 10 additions & 44 deletions packages/sdk/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { EIP1193Provider } from "eip1193-types";

import {
getFungibleTokens,
getSolution,
Expand Down Expand Up @@ -27,19 +25,13 @@ export * as api from "./api";
export * from "./enums";

class Sprinter {
#provider: EIP1193Provider;

// local "cache"
// in memory "cache"
#tokens?: FungibleToken[];
#chains?: Chain[];

#fetchOptions: Omit<FetchOptions, "signal">;

constructor(
provider: EIP1193Provider,
fetchOptions: Omit<FetchOptions, "signal"> = {},
) {
this.#provider = provider;
constructor(fetchOptions: Omit<FetchOptions, "signal"> = {}) {
this.#fetchOptions = fetchOptions;
}

Expand All @@ -60,13 +52,12 @@ class Sprinter {
}

public async getUserBalances(
account: Address,
tokens?: FungibleToken[],
options: FetchOptions = {},
): Promise<{
[sybol: TokenSymbol]: { balances: FungibleTokenBalance[]; total: string };
}> {
const account = await this.getAccount();

const tokenList = tokens || (await this.getAvailableTokens(options));

const balances = await Promise.all(
Expand Down Expand Up @@ -98,72 +89,47 @@ class Sprinter {
}

public async getSolution(
settings: Omit<ContractSolutionOptions, "account">,
targetAccount?: Address,
settings: ContractSolutionOptions,
options?: FetchOptions,
): Promise<SolutionResponse>;
public async getSolution(
settings: Omit<SolutionOptions, "account">,
targetAccount?: Address,
settings: SolutionOptions,
options?: FetchOptions,
): Promise<SolutionResponse>;
public async getSolution(
settings: unknown,
targetAccount?: Address,
options?: FetchOptions,
): Promise<SolutionResponse> {
const account = targetAccount || (await this.getAccount());

if (typeof settings !== "object" || settings === null)
throw new Error("Missing settings object");

if ("contractCall" in settings)
return await getContractSolution(
<ContractSolutionOptions>{
...settings,
account,
},
<ContractSolutionOptions>settings,
this.makeFetchOptions(options || {}),
);
return await getSolution(
<SolutionOptions>{ ...settings, account },
<SolutionOptions>settings,
this.makeFetchOptions(options || {}),
);
}

public async getCallSolution(
settings: Omit<ContractSolutionOptions, "account">,
targetAccount?: Address,
settings: ContractSolutionOptions,
options?: FetchOptions,
): Promise<SolutionResponse> {
const account = targetAccount || (await this.getAccount());

if (typeof settings !== "object" || settings === null)
throw new Error("Missing settings object");

return await getContractCallSolution(
<ContractSolutionOptions>{
...settings,
account,
},
settings,
this.makeFetchOptions(options || {}),
);
}

private async getAccount(): Promise<Address> {
const [account] = (await this.#provider.request({
method: "eth_requestAccounts",
params: [],
})) as Address[];
if (!account)
throw new Error("No available account! Check your provider or something");

return account;
}

private makeFetchOptions(options: FetchOptions): FetchOptions {
return { ...this.#fetchOptions, ...options };
}
}

export { Sprinter, setBaseUrl, BASE_URL, EIP1193Provider };
export { Sprinter, setBaseUrl, BASE_URL };
27 changes: 10 additions & 17 deletions web/src/lib/components/Account.svelte
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
<script lang="ts">
import { selectedProvider } from '$lib/stores/wallet';
import {
type DrawerSettings,
getDrawerStore,
Expand All @@ -10,10 +9,10 @@
import { sprinterNameServiceAbi } from '$lib/sprinterNameService.abi';
import UpdateNameModal from '$lib/components/UpdateNameModal.svelte';
import { SPRINTER_SEPOLIA_ADDRESS } from '$lib/stores/sprinter';
import { selectedAccount } from '$lib/stores/wallet';
import type { Address } from '@chainsafe/sprinter-sdk';

$: address = $selectedProvider.provider.request({ method: 'eth_requestAccounts', params: [] });

async function getSprinterName(address: string): Promise<string> {
async function getSprinterName(): Promise<string> {
const SEPOLIA_RPC_PROVIDER = 'https://ethereum-sepolia-rpc.publicnode.com';
const web3 = new Web3(SEPOLIA_RPC_PROVIDER);

Expand All @@ -22,7 +21,7 @@
SPRINTER_SEPOLIA_ADDRESS
);

const name = await sprinterNameService.methods.names(address).call();
const name = await sprinterNameService.methods.names($selectedAccount as Address).call();
if (!name) throw new Error('Name not found!');
return name;
}
Expand Down Expand Up @@ -59,18 +58,12 @@
<div class="self-stretch justify-start items-start gap-2.5 inline-flex">
<div class="text-black dark:text-white text-xl font-medium font-['Inter'] leading-7">
Hello
{#await address}
0x....
{:then result}
{#await getSprinterName(result[0])}
{result[0]}
{:then name}
{name}
{:catch}
{result[0]}
{/await}
{:catch error}
- {JSON.stringify(error)}
{#await getSprinterName()}
{$selectedAccount}
{:then name}
{name}
{:catch}
{$selectedAccount}
{/await}
</div>
</div>
Expand Down
4 changes: 3 additions & 1 deletion web/src/lib/components/Portfolio.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@
import { getModalStore, type ModalSettings } from '@skeletonlabs/skeleton';
import TokenModal from '$lib/components/TokenModal.svelte';
import { sprinter } from '$lib/stores/sprinter';
import { selectedAccount } from '$lib/stores/wallet';
import type { Address } from '@chainsafe/sprinter-sdk';

const modalStore = getModalStore();

const tokens = $sprinter.getAvailableTokens();
const balances = $sprinter.getUserBalances();
const balances = $sprinter.getUserBalances($selectedAccount as Address);
const chains = $sprinter.getAvailableChains();

$: total = balances.then((b) =>
Expand Down
5 changes: 4 additions & 1 deletion web/src/lib/components/SendTokensDrawer.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@
import { sprinter } from '$lib/stores/sprinter';
import { getNetworkByChainId, getTokenBySymbol } from '$lib/utils';
import { type FungibleToken, type FungibleTokenBalance } from '@chainsafe/sprinter-sdk';
import { selectedAccount } from '$lib/stores/wallet';
import type { Address } from '@chainsafe/sprinter-sdk';

const tokens = $sprinter.getAvailableTokens();
const allBalances = $sprinter.getUserBalances();
const allBalances = $sprinter.getUserBalances($selectedAccount as Address);
const chains = $sprinter.getAvailableChains();

const drawerStore = getDrawerStore();
Expand Down Expand Up @@ -67,6 +69,7 @@
chains: await chains,
balances,
quota: {
account: $selectedAccount,
token: selectedToken,
destinationChain: selectedNetwork,
whitelisted,
Expand Down
Loading
Loading