# Ethereum JSON-RPC Provider

A typescript SDK for sending EVM transactions through the Fordefi API using a standard Ethereum JSON-RPC Provider interface.

The [FordefiWeb3Provider class](https://web3provider-docs.fordefi.com/classes/FordefiWeb3Provider.html) implements EIP-1193 powered by the Fordefi API. It provides a `request()` function to execute JSON-RPC methods and emits the relevant events.

See [full documentation](https://web3provider-docs.fordefi.com).

# Installation

Use yarn or npm to install the package.

yarn

```yarn
yarn add @fordefi/web3-provider
```

npm

```npm
npm add --save @fordefi/web3-provider
```

# Usage

## Create a provider

Each instance manages a single address (vault) on a specific chain.


```typescript
import { FordefiWeb3Provider, FordefiProviderConfig } from "@fordefi/web3-provider";

const config: FordefiProviderConfig = {
  chainId: 11155111,
  address: "0x1234567890123456789012345678901234567890",
  apiUserToken: process.env.FORDEFI_API_USER_TOKEN,
  apiPayloadSignKey: process.env.FORDEFI_API_PAYLOAD_SIGNING_KEY,
};

const provider = new FordefiWeb3Provider(config)
```

See the [reference](https://web3provider-docs.fordefi.com/index.html#md:api-reference) for a full description of the available configuration options.

## Connect

The spec requires a provider to be [connected](https://eips.ethereum.org/EIPS/eip-1193#connectivity) to submit requests.

This provider automatically connects to Fordefi when a new instance is constructed, and emits a connect event once communication with the Fordefi platform has been established.

To subscribe to the event:


```typescript
// callback to act upon a `connect` event
const onConnect = ({ chainId }: ProviderConnectInfo) => {
  console.log(`Connected to chain ${chainId}`);
}

// option 1: subscribe using a callback
provider.on('connect', onConnect);

// option 2: wait for a promise to be resolved
const result = await provider.waitForEmittedEvent('connect');
onConnect(result);
// or
provider
  .waitForEmittedEvent('connect')
  .then(onConnect);
```

For more information, see [Events](https://web3provider-docs.fordefi.com/index.html#md:events).

## Submit JSON-RPC requests

The `request({ method, params })` method sends JSON-RPC requests to the provider. It returns a promise that resolves to the result of the request.

All methods related to creating and/or signing transactions will resolve once the transaction was successfully signed by an [API Signer](/developers/program-overview).

An example of sending a transaction:


```typescript
const txHash = await provider.request({
  method: 'eth_sendTransaction',
  params: [{
    from: '0x1234567890123456789012345678901234567890',
    to: '0x1234567890123456789012345678901234567890',
    value: 1_500_000_000_000n,
  }],
});

console.log(`Transaction hash: ${txHash}`);
```