# ウォレット - 外部ウォレットインターフェース

> Privyを利用すると、ユーザーはMetaMask、Coinbase Wallet、Rainbow Walletなどの外部ウォレットをアプリに接続し、メッセージの署名、トランザクションの送信、スマートコントラクトとのやり取りを行うことができ

- URL: https://cardene.dev/books/privy/f719ec
- 本: Privy大全 (https://cardene.dev/books/privy.md)
- 章: 15 / 42
- 前の章: https://cardene.dev/books/privy/99294d.md
- 次の章: https://cardene.dev/books/privy/042781.md
- 公開日: 2023-12-22
- 更新日: 2023-12-22
- トピック: Blockchain
- タグ: solidity, ethereum, smartcontract, wallet

# 概要

Privyを利用すると、ユーザーは**MetaMask**、**Coinbase Wallet**、**Rainbow Wallet**などの外部ウォレットをアプリに接続し、メッセージの署名、トランザクションの送信、スマートコントラクトとのやり取りを行うことができます。
また、`ethers.js`、`web3.js`、`wagmi`などの人気のあるweb3ライブラリを使用して、Privyを通じて接続された外部ウォレットから署名やトランザクションをリクエストすることが可能です。

# ウォレットの接続
`usePrivy`フックから`connectWallet`メソッドを呼び出すことで、アプリは複数のウォレットを接続できます。
接続されたウォレットは`useWallets`フックから返される`wallets`配列でアクセス可能です。

```tsx
import { usePrivy } from '@privy-io/react-auth';

export default function ConnectWalletButton() {
  const { connectWallet } = usePrivy();

  return <button onClick={connectWallet}>Connect Wallet</button>;
}
```

:::message
`useConnectWallet`インターフェースを使用して`connectWallet`に簡単にコールバックをアタッチできます。
詳細は以下に書かれています。
:::

https://docs.privy.io/guide/frontend/callbacks


# `useWallets`フックを使用してウォレットを処理
`connectWallet`、`linkWallet`、`login`を使用してユーザーがウォレットを接続すると、Privyは`useWallets`フックから返される`wallets`配列に新しい`ConnectedWallet`オブジェクトを追加します。
このリストには外部ウォレットと組み込みウォレットが含まれます。

`wallets`配列は、より複雑なフローにも使用できます。
例えば、標準的な使用例には組み込みのログインを推奨しますが、接続とログインの呼び出しを分割し、フローをよりカスタマイズすることも可能です。

# 接続されたウォレットでログインする
```tsx
import { usePrivy, useWallets } from '@privy-io/react-auth';

export default function ConnectAndLogin() {
  const { connectWallet, ready, authenticated } = usePrivy();
  const { wallets } = useWallets();

  return <div>
    <button onClick={() => connectWallet()}>Connect Wallet</button>
    <p>Most recent wallet: {wallets[0] ? wallets[0].address : "none"}</p>
    <button onClick={() => wallets[0]?.loginOrLink()} disabled={!ready || !wallets[0] || !authenticated}>Login</button>
  </div>;
}
```

`wallets`配列は常に最近接続された順に並べられます。
したがって、`wallets[0]`は常に最も最近接続されたウォレットになります。

`ConnectedWallet`オブジェクトには、ユーザーのウォレットと対話するために使用できるいくつかのプロパティとメソッドがあります。

## プロパティ
`ConnectedWallet`オブジェクトには次のプロパティがあります。

- `address`
	- チェックサム形式のイーサリアムアドレス。
- `chainId`
	- CAIP-2形式のチェーンID。
- `linked`
	- ユーザーが認証されていない場合は`false`に設定され、認証されていてもこのウォレットが現在のユーザーにまだリンクされていない場合も`false`に設定されます。
- `walletClientType`
	- ウォレットプロバイダーのタイプ（metamask、trust、rainbowなど）。
- `connectorType`
	- ウォレットが接続された方法（injected、wallet_connect、coinbase_walletなど）。
- `connectedAt`
	- このウォレットが最後に接続された時刻。

## メソッド
`Wallet`オブジェクトには以下のメソッドがあります。

- `loginOrLink()`
	- 現在接続されているウォレットを使用してログインまたはリンクするためにユーザーに署名を求めます。
- `unlink()`
	- 認証されたユーザーから現在接続されているウォレットのリンクを解除します。
- `sign(message: string)`
	- 現在接続されているウォレットを使用してメッセージに`personal_sign`で署名します。
- `getEthersProvider()`
	- ethersプロバイダーを取得します。
- `getWeb3jsProvider()`
	- Web3JSプロバイダーを取得します。
- `getEthereumProvider()`
	- EIP1193プロバイダーを取得します。

## 署名のリクエスト
署名は、サードパーティの統合または直接ウォレットオブジェクトを使用してリクエストできます。

```tsx
import { useWallets } from '@privy-io/react-auth';

export default function SignMessageButton() {
  const { wallets } = useWallets();

  // Prompt user to sign a message
  return <button onClick={() => wallets[0]?.sign("Hello World.")} disabled={!wallets[0]}>Sign Message</button>;
}
```

## トランザクションの送信
**ethers.js**を使用して、署名をリクエストする方法を紹介します。

```tsx
import { useWallets } from '@privy-io/react-auth';

export default function SendTransactionButton() {
  const { wallets } = useWallets();

  async function sendTransaction() {
    // Get an ethers provider and signer from the most recently connected wallet
    const provider = await wallets[0]?.getEthersProvider();
    const signer = await provider?.getSigner();

    const txn = {
        from: ...,
        to: ...,
        value: ...,
        nonce: ...,
        gasLimit: ...,
        gasPrice: ...,
    }

    // Send transaction
    signer.sendTransaction(txn).then((completedTxn) => {
        console.log(completedTxn);
    });
  }

  // Prompt user to sign a message
  return <button onClick={() => sendTransaction()} disabled={!wallets[0]}>Sign Message</button>;
}
```

# 統合
Privyでは、開発者がお気に入りのWeb3ライブラリを引き続き使用できるように、さまざまな統合が提供されています。

## ethers.js
特定のネットワークでユーザーのウォレットにアクションを取らせる必要がある場合は、ウォレットのEthersプロバイダーを初期化する前に、ユーザーのウォレットを目的のネットワークに切り替えるべきです。
そうしないと、プロバイダーが古いネットワークに対応している可能性があります。

`wallets`配列のウォレットから`getEthersProvider`メソッドを呼び出すことで、ユーザーのウォレットからEthers互換のプロバイダーを取得できます。これをEthersプロバイダーとして使用して、ブロックチェーンデータを読み取ったり、ユーザーのウォレットにリクエストを送ったりできます。

```tsx
import { useWallets } from '@privy-io/react-auth';

export default function MyComponent() {
    const { wallets } = useWallets();

    const getEthersSigner = async () => {
    // Switch the wallet to your target chain before getting the ethers provider
    await wallets[0]?.switchChain('your-target-chain-id');
        // Get an ethers provider and signer from the user's recently connected wallet
        const provider = await wallets[0]?.getEthersProvider();
        return await provider?.getSigner();
    }

    return <>{/* your code here */}</>
}
```

## Ethereum JavaScript APIの使用
EIP-1193（Ethereum JavaScript API）互換のプロバイダーを取得できます。
これは、JSON-RPC経由でユーザーのウォレットと通信するために使用できます。
このプロバイダーは、`wallets`配列のウォレットから`getEthereumProvider`メソッドを使用してアクセスできます。

```tsx
import { useWallets } from '@privy-io/react-auth';

export default function MyComponent() {
    const { wallets } = useWallets();

    // You can now use the ethereum.request({method: ...})
    // syntax as documented in the EIP.
    const getEthereumProvider = async () => {
        // Initialize your Web3.js client with the provider
        return await wallets[0]?.getEthereumProvider();
    }

    return <>{/* your code here */}</>
}
```

## Wagmiの統合
Privyでは、アプリ内でPrivyと共にWagmiを統合するためのWagmiコネクタパッケージが提供されています。
詳細については以下のガイドを参照してください。

https://docs.privy.io/guide/guides/wagmi

## Viemの統合
特定のネットワークでユーザーのウォレットにアクションを取らせる必要がある場合は、ウォレットのViem WalletClientを初期化する前に、目的のネットワークに切り替える必要があります。
Privyの`getEthereumProvider`メソッドからEIP1193プロバイダーを取得し、これをViemの`createWalletClient`メソッドに渡すことで、Viem互換のウォレットクライアントをユーザーのウォレット用に取得できます。

```tsx
import { useWallets } from '@privy-io/react-auth';
import { createWalletClient, custom } from 'viem';
// Replace 'mainnet' below with the chain your application needs
// See https://viem.sh/docs/clients/chains.html
import { mainnet } from 'viem/chains';

export default function MyComponent() {
    const { wallets } = useWallets();

    const getViemWalletClient = async () => {
        // Switch your wallet to your target chain before getting the viem WalletClient
        await wallets[0]?.switchChain('your-target-chain-id');
        // Get an EIP1193 provider from the user's wallet
        const ethereumProvider = await wallets[0]?.getEthereumProvider();
        // Create a Viem wallet client from the EIP1193 provider
        const walletClient = await createWalletClient({
            account: embeddedWallet?.address,
            chain: mainnet,
            transport: custom(ethereumProvider)
        });
        return walletClient;
    }

    return <>{/* your code here */}</>
}
```

## Web3.jsの統合
特定のネットワークでユーザーのウォレットにアクションを取らせる必要がある場合は、ウォレットのWeb3.jsプロバイダーを初期化する前に、目的のネットワークに切り替える必要があります。
`wallets`配列のウォレットから`getWeb3jsProvider`メソッドを呼び出すことで、ユーザーのウォレットからWeb3.js互換のプロバイダーを取得できます。
その後、このプロバイダーでWeb3クライアントを初期化できます。

wallets配列内のウォレットから`getWeb3jsProvider`メソッドを呼び出すことで、ユーザーのウォレットからweb3.js互換プロバイダを取得できます。
その後、このプロバイダでweb3クライアントを初期化できます。

```tsx
import { useWallets } from '@privy-io/react-auth';
import Web3 from 'web3';

export default function MyComponent() {
    const { wallets } = useWallets();

    const getWeb3Provider = async () => {
        // Initialize your Web3.js client with the provider
        const provider = await wallets[0]?.getWeb3jsProvider();
        return new Web3(provider);
    }

    return <>{/* your code here */}</>
}
```

# 参考

https://docs.privy.io/guide/frontend/wallets/external
