# UPBOND Developers > UPBOND Transfer API (JPYC transfers from a corporate vault) and the @upbond/sdk reference. This file contains all documentation content in a single document following the llmstxt.org standard. ## AI エージェントと使う このサイトは、コーディングエージェントがそのまま読める形でも提供しています。 | 入口 | URL | 用途 | |---|---|---| | llms.txt | [/llms.txt](pathname:///llms.txt) | ページの一覧。エージェントに「まずこれを読む」と指示します | | llms-full.txt | [/llms-full.txt](pathname:///llms-full.txt) | 全ページを 1 ファイルにまとめたもの | | OpenAPI 定義 | [/transfer-api/openapi.yaml](pathname:///transfer-api/openapi.yaml) | クライアント生成、モック、型の生成 | | SKILL.md | [/transfer-api/skill/SKILL.md](pathname:///transfer-api/skill/SKILL.md) | Agent Skills 形式の導入手順。要点、落とし穴、参照先をまとめたもの | ### Claude Code リポジトリに `.claude/skills/upbond-transfer-api/SKILL.md` として置くと、Transfer API に関する作業のときに自動で読み込まれます。 ```bash mkdir -p .claude/skills/upbond-transfer-api curl -fsSL https://docs.upbond.io/transfer-api/skill/SKILL.md \ -o .claude/skills/upbond-transfer-api/SKILL.md ``` ### Codex、Cursor、その他 Agent Skills に対応したエージェントでは同じ `SKILL.md` をそのまま使えます。対応していない場合は、`AGENTS.md` や `.cursor/rules` から次の 2 行を参照させてください。 ```text UPBOND Transfer API を実装するときは https://docs.upbond.io/llms.txt を読み、 API の形は https://docs.upbond.io/transfer-api/openapi.yaml に従うこと。 ``` ### 注意 - 秘密鍵、シークレット、アクセストークンをプロンプトやチャットに貼らないでください。エージェントには環境変数から読む実装をさせてください。 - エージェントが生成したクライアントは、必ず STG で [疎通確認](./getting-started.md#4-疎通確認) と初回送金を通してから本番に使ってください。 - PHP 8.4 以前では封筒の生成に phpseclib 3 が必要です。エージェントが `openssl_public_encrypt()` を SHA-256 の指定なしで使ったコードを書いた場合は誤りです([シークレットと封筒](./signing-secret.md#封筒を作る))。 --- ## 認証 すべての API 呼び出しに、API キー ID とアクセストークンの 2 つを付けます。アクセストークンは UPBOND の認証基盤から OAuth 2.0 のクライアント資格情報フローで取得します。クライアント認証には貴社の秘密鍵で署名したクライアントアサーション(RFC 7523、`private_key_jwt`)を使います。パスワードやクライアントシークレットはありません。 ### リクエストヘッダー | ヘッダー | 値 | 説明 | |---|---|---| | `X-API-Key` | API キー ID | 接続情報で案内した ID。認証基盤のクライアント ID と同じ値です | | `Authorization` | `Bearer {access_token}` | 認証基盤が発行したアクセストークン。有効期限内は再利用します | | `Content-Type` | `application/json` | 本文を送る API で必須。本文は 64 KB 以内 | | `Idempotency-Key` | 255 文字以内の任意の文字列 | `POST /v1/transactions` の再送対策([送金と取引照会](./transactions.md#重複防止)) | ### アクセストークンの取得 #### 1. クライアントアサーションを作る 登録した秘密鍵で、次のクレームを持つ JWT(RS256)を作ります。 | クレーム | 値 | |---|---| | `iss` / `sub` | API キー ID | | `aud` | 認証基盤の URL(PROD `https://auth.upbond.io`、STG `https://auth.stg.upbond.io`) | | `jti` | 一意な文字列(UUID 推奨)。同じ値の再利用は拒否されます | | `iat` / `exp` | 発行時刻と有効期限(Unix 秒)。`exp` は `iat + 60` 程度の短さにしてください | #### 2. トークンエンドポイントへ POST する ```http POST /oauth/token Host: auth.upbond.io Content-Type: application/x-www-form-urlencoded grant_type=client_credentials &client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer &client_assertion={clientAssertionJwt} ``` ```http HTTP/1.1 200 OK Content-Type: application/json { "access_token": "…", "token_type": "Bearer", "expires_in": 300 } ``` `client_id` パラメーターは付けても構いませんが、その場合はアサーションの `iss` と同じ値でなければなりません。`scope` と `resource` は使いません。 #### 3. トークンを使う アクセストークンは**不透明な文字列**です。JWT として復号したり検証したりはできません。API 側が認証基盤に照会して、有効性とクライアント ID を確認します。 有効期限は 5 分です。期限まで同じトークンを再利用し、期限の 30 秒前に取り直してください。リクエストごとに取得する必要はなく、トークンエンドポイントにもレート制限があります。 API は次の順で検証します。 - トークンが有効で期限内であること。認証基盤への照会に失敗した場合も含めて `401` / `1002` - トークンのクライアント ID が `X-API-Key` と一致し、その API キーが登録済みであること(`401` / `1003`) - API キーが失効していないこと(`403` / `1004`) - 送信元 IP が許可されていること(IP 制限を登録した場合、`403` / `1005`) 有効なトークンの照会結果は最大 60 秒キャッシュされます。認証基盤側でトークンを失効させても、反映に最大 60 秒かかることがあります。API キーの失効は毎回確認されます。 #### トークンエンドポイントのエラー OAuth 2.0 標準の形式で返ります。 | `error` | 主な原因 | |---|---| | `invalid_client` | アサーションの署名が登録済みの公開鍵で検証できない、`aud` が違う、`exp` 切れ、`jti` の再利用 | | `invalid_request` | 必須パラメーターの欠落、`client_id` と `iss` の不一致 | :::tip 時刻同期 クライアントアサーションの有効期限は短いため、貴社サーバーの時刻は NTP で同期してください。`invalid_client` が続く場合、まず時刻のずれを疑ってください。 ::: ### 鍵の更新 認証用の鍵を更新するときは、新しい公開鍵を UPBOND に送って登録してもらってから切り替えます。旧鍵は登録解除の時点で使えなくなります。 ### レート制限 API キーごとに毎秒 10 リクエスト(バースト 20)です。超過すると `429` と `Retry-After` ヘッダー(秒)を返します。一括処理はこの範囲で順次投入してください。必要に応じて引き上げます。 ### 送信元 IP 制限 任意で、送信元グローバル IP を API キーに登録できます(完全一致。CIDR は指定できません)。登録した場合、それ以外の送信元からの呼び出しは `403` / `1005` になります。送信元の判定は、UPBOND の HTTPS 終端の直後で見た接続元アドレスで行います。 --- ## 変更履歴 | 版 | 日付 | 内容 | |---|---|---| | 1.7 | 2026-10-18 | `429` / `1502`(同じ Vault の別の送金を処理中、再送可)を追加(下記) | | 1.6 | 2026-10-18 | 本番のチェーンを Avalanche C-Chain に、STG を Avalanche Fuji に変更(`JPYC_AVALANCHE` / `JPYC_FUJI`、ガス代は AVAX)(下記) | | 1.5 | 2026-10-17 | 署名前のエンジン一時障害の自動再試行(1 回)、受付後に所有者が上限を変えたときの `BLOCKED_BY_POLICY` を明文化、`1310`(下記) | | 1.4 | 2026-10-17 | シークレットを「上限」の一部として所有者が署名(EIP-712 版 2、**既存の上限は署名し直し**)、API キーの表示名、ウォレット設定画面の再編(1 つの API キー = 1 つのシークレット = 1 組の上限)、`1417`(下記) | | 1.3 | 2026-10-17 | 封筒を送金リクエストに束縛(**互換性なし**)、送金の上限は Vault 所有者がウォレットで署名して登録、`1304` の意味と `1305`(下記) | | 1.2 | 2026-10-08 | `DROPPED_BY_BLOCKCHAIN` の判定を変更(下記) | | 1.1 | 2026-09-25 | 実装に合わせた全面改訂(下記) | | 1.0 | 2026-09-07 | 初版(個別に配布した仕様書) | ### 1.7 の変更点 リクエストの形式に変更はありません。 - `429` / `1502`: 同じ Vault の別の送金を UPBOND が処理している間に届いた送金が、待ち時間(20 秒)内に順番を取れなかったときの応答です。取引は作られず、`externalTxId` も `Idempotency-Key` も消費されません。`Retry-After` 秒後に同じリクエストをそのまま再送してください。従来の `429` / `1501`(レート制限)と同じ扱いで済みます。 ### 1.6 の変更点 リクエストの形式に変更はありません。変わるのは接続先のチェーンと `assetId` の値です。 - 本番(PROD)のチェーンを Polygon PoS から **Avalanche C-Chain メインネット**(chainId 43114)に変更しました。`assetId` は `JPYC_POLYGON` ではなく **`JPYC_AVALANCHE`** です。JPYC のコントラクトアドレスは `0xE7C3D8C9a439feDe00D2600032D5dB0Be71C3c29`(decimals 18)です。 - STG のチェーンを Ethereum Sepolia から **Avalanche Fuji**(chainId 43113)に変更しました。`assetId` は `JPYC_SEPOLIA` ではなく **`JPYC_FUJI`** です。従来の値を送ると `422` / `1301` になります。 - ガス代は両環境とも **AVAX** で支払います。本番の Vault にはガス代用の AVAX を入れてください(`feeInfo.networkFee` も AVAX の量です)。 - 取引の確認には Avalanche のエクスプローラー([Snowtrace](https://snowtrace.io/)、STG は [testnet.snowtrace.io](https://testnet.snowtrace.io/))を使えます。 - 封筒の正規化リクエストには `assetId` が含まれるため、封筒は新しい `assetId` で作ってください。仕様書・OpenAPI 定義・サンプルの例を `JPYC_AVALANCHE` に改めました。 ### 1.5 の変更点 リクエストの形式に変更はありません。 - 署名前にエンジン側(MPC ネットワークのメタデータ取得など)で一時的な障害が起きたとき、UPBOND が同じ取引を **1 回だけ自動で再試行**します。従来はその場で `FAILED` / `SIGNING_FAILED` になり、新しい `externalTxId` での作り直しが必要でした。再試行は署名を要求する前の失敗に限られ、署名が 2 回行われることはありません。再試行も失敗したときは従来どおり `FAILED` / `SIGNING_FAILED` です。応答が数秒延びることがあります。 - 取引を受け付けてから署名するまでの間に Vault 所有者が上限を変更・取り消した場合の結果(`BLOCKED` または `FAILED`、`subStatus: BLOCKED_BY_POLICY`、終端)を[ポリシー](./policy.md#受付後に所有者が上限を変えたとき)に明記しました。動作の変更ではありません。 - `422` / `1310`: Vault の登録に不整合があり UPBOND がその Vault の送金を止めているとき、取引を作らずに拒否します。UPBOND 側で解除するまで続きます。 ### 1.4 の変更点 公開 API(`/v1`)に変更はありません。所有者がウォレットで行う作業が変わりました。 - ウォレットの設定に「API キー」画面ができました。UPBOND が登録した API キーが**表示名**(UPBOND が登録時に付け、所有者が変更できます)で並び、キーを開くと名前・シークレット・上限が 1 画面に出ます。1 つの API キーには 1 つのシークレットと 1 組の上限があります。従来の「API アクセス」「送金 API の上限」はこの画面に統合されました。 - **どのシークレットが署名してよいか**が「上限」の項目になりました(`allowedFactorPubs`)。公開鍵を UPBOND に連絡する必要はなくなり、上限を保存するときにその API キーのシークレットが自動で含まれます(確認画面に「シークレット …末尾 6 桁」として表示)。上限に含まれないシークレットは `403` / `1413` で拒否されます。 - 署名対象(EIP-712 `TransferMandate`)のドメイン版が `1` → `2` になりました。**版 1 で署名した上限は、所有者がウォレットで署名し直すまで何も許可しません**(`403` / `1417`)。STG で登録済みの上限が対象です(本番にはまだ上限がありません)。 - 上限の署名では、直前に別の操作で本人確認を済ませていても、必ず本人確認(パスキー)が求められます。 - シークレットの切り替えは「シークレットを再発行」→ エージェント側を新しいシークレットに切り替え → 「上限を保存」(この時点で古いシークレットでは送金できません)→ 古いシークレットを失効、の手順です。UPBOND 側の停止(`1412`)は従来どおりです。 - 用語: ウォレット画面では「API キー」(エージェント・外部システムごとのキー)、「シークレット」(発行してエージェントに渡す秘密値)、「上限」(所有者が署名する上限)、「送金元ウォレット」を使います。API の `source.id`(Vault アカウント ID)など、リクエストの項目名に変更はありません。 ### 1.3 の変更点 **シークレットと封筒**(互換性のない変更。移行期間はありません。1.2 までの 32 バイト形式の封筒は `422` / `1411` で拒否されます) - 封筒の平文が 32 バイトのシークレットから、**73 バイトの束縛付き平文**になりました: `0x01` ‖ シークレット(32)‖ 正規化したリクエストの SHA-256(32)‖ `issuedAt`(8、エポックミリ秒のビッグエンディアン)。詳細は[シークレットと封筒](./signing-secret.md#封筒を作る)。 - 正規化したリクエストは `assetId`・`source.id`・`destination.oneTimeAddress.address`・`amount`・`feeLevel`(省略時は `MEDIUM`)・`externalTxId`・`note`(省略時は空文字列)の **7 項目**を、本文に書いたとおりの文字列で LF 連結したものです。`note` も束縛に含まれるため、封筒を横取りした第三者が `note` だけを差し替えることはできません。 - `externalTxId` に制御文字(改行など)を含めることはできなくなりました(`400` / `1102`)。文字列フィールドに孤立したサロゲート(不正な Unicode)があると `400` / `1102` です。 - 新しいエラー: `422` / `1414`(封筒が別の本文に束縛されている)、`422` / `1415`(`issuedAt` が ±5 分の窓の外)。 - 理由: 1.2 までの封筒は本文に束縛されていなかったため、ログ等から封筒 1 つと API キーが漏れると、シークレットを知らなくても上限内の送金を何度でも署名させられました。1.3 の封筒は作成から数分の間、その 1 件にしか使えず、同じ封筒の 2 回目は `409` / `1201` になります。 - OAEP のパラメーター(SHA-256 / MGF1-SHA-256 / ラベル空)、`GET /v1/upbond/signer`、冪等比較から `signer` を除く規則、`1410` の再送規則に変更はありません。 **ポリシー** - 送金の上限(1 件上限・日次累計上限(日本時間 0:00 区切り)・宛先許可リスト・有効期限)は、**Vault 所有者がウォレット(設定「API アクセス」>「送金 API の上限」)で内容を確認し、法人ウォレットの鍵で署名して登録**するようになりました。UPBOND は署名を検証して保管し、送金のたびに参照します。UPBOND が上限を作ったり引き上げたりすることはできません([ポリシー](./policy.md))。 - 1 件上限も所有者の登録に含まれます。導入時に UPBOND へ 1 件上限を提出する必要はなくなりました。 - 日次累計上限と宛先許可リストの検査が加わりました。超過・リスト外の宛先は `BLOCKED` / `BLOCKED_BY_POLICY` です。日次累計は受付時に加算し、送信前に失敗した取引の額だけ枠に戻します。 - 上限には有効期限があります(最長 365 日)。期限切れの上限での取引は作られずに `422` / `1305` で拒否されます。 - `422` / `1304` は「所有者がこの API キーの上限に署名していない、または取り消した」という意味です。UPBOND 側で解除することはできません。 ### 1.2 の変更点 **送金と照会** - 送信後 30 分レシートが無いだけでは `FAILED` / `DROPPED_BY_BLOCKCHAIN` にしなくなりました。1.1 までの判定では、`FAILED` になった取引の署名済みトランザクションが後から成立することがあり、作り直すと同じ送金が 2 回成立するおそれがありました。 - `DROPPED_BY_BLOCKCHAIN` は、同じ Vault の別の取引がその nonce を使って所定の確認数に達し、送信した取引が成立しないことが確定したときにだけ付きます。それまでは `BROADCASTING` のままです。 - `BROADCASTING` が長く続く取引は作り直さず、UPBOND に連絡する運用を明記しました([`BROADCASTING` が長く続くとき](./transactions.md#broadcasting-が長く続くとき))。 - 列挙値、リクエスト、レスポンスの形式に変更はありません。 ### 1.1 の変更点 **認証** - アクセストークンは不透明な文字列です(1.0 では JWT と記載していました)。API 側が認証基盤に照会して検証します。 - トークン要求の `client_id` は任意(付ける場合は `iss` と一致)、`scope` と `resource` は使いません。 - クライアントアサーションの `aud` は認証基盤の URL(`https://auth.upbond.io` / `https://auth.stg.upbond.io`)です。 **シークレットと封筒** - 封筒のパラメーターを明記しました: RSA-OAEP、SHA-256、MGF1 with SHA-256、ラベル空、平文は base64 を復号した 32 バイト。 - 署名環境の鍵は 30 日を目安に更新し、旧鍵を 7 日間は使える状態に保つ運用を明記しました。API が保証する契約は `expiresAt` と `1410` の扱いです。`attestation` は当面空文字です。 - `1410` / `1411` の再送規則: 同じ `Idempotency-Key` と `externalTxId` のまま再送できます。冪等比較から `signer` を除外し、`4xx` / `5xx` は記録しません。 - 「シークレットは秘密鍵と同等に保管する」という注意を追加しました。API キー漏えい時の被害が上限内に限られるのは API 経路に限った話です。 **Vault** - Vault 所有者の接続(同意)と 90 日の絶対期限、再接続の手順を追加しました。 - 同意切れのエラー `422` / `1303` と、署名中に切れた場合の `subStatus: OWNER_REAUTH_REQUIRED` を追加しました。 - 接続は、ウォレットを作ったときと同じログイン方法で行う必要があります。 **送金と照会** - 自動署名モードでは `POST /v1/transactions` の中で署名と送信まで行うため、応答の `status` は通常 `BROADCASTING`(失敗時は `FAILED`)です。 - 一覧のページ送りに `cursor` パラメーターを追加しました(`next-page` ヘッダーの URL に含まれます)。 - `subStatus` に `SIGNING_FAILED`、`OWNER_REAUTH_REQUIRED`、`CONNECTIVITY_ERROR` を追加しました。`REJECTED` / `CANCELLED` / `REJECTED_BY_USER` / `TIMEOUT` は承認モード向けの予約値で、現在は発生しないことを明記しました。 - 受付後・署名前にチェーンの照会(残高・nonce)に失敗した取引は `FAILED` / `CONNECTIVITY_ERROR` で終端になること(署名も送信もしていないので、新しい `externalTxId` で作り直す)と、UPBOND 内部の障害(`500` / `5000`)の後に同じ `Idempotency-Key` で再送したときの扱いを追記しました。 - `signedBy` は署名完了後にだけ `["api-factor"]` になること、送信の RPC 失敗は `BROADCASTING` のまま追跡されることを追記しました。 **エラー** - エラーコード表を実装に合わせて全面的に書き直しました。1.0 の「番台」の対応は誤りでした。 - 追加: `1203`(冪等処理の進行中)、`1303`、`1401` / `1402`(`signer` の有無)、`1411`、`1412`、`1413`、`5000`。 **ポリシーと運用** - API キー、上限、送信元 IP の設定は UPBOND が代行します。ダッシュボードでの自己設定の記述を削除しました。 - ポリシーは 1 件上限と送信元 IP(完全一致、CIDR 不可)です。日次上限と宛先の許可リストは提供していません。上限超過は既定で `BLOCKED`(承認待ちに回す設定は存在しますが、承認機能は未提供)。 - トークン照会の結果は最大 60 秒キャッシュされることを追記しました。 - 承認モードは準備中です。 - assetId は環境ごとに 1 つです。STG は `JPYC_SEPOLIA`(Ethereum Sepolia)、本番は `JPYC_POLYGON`。 **表現** - 「Fireblocks 互換」を「Fireblocks 形式の API 語彙に準拠」に改めました。 --- ## エラー形式とコード一覧 エラーは HTTP ステータスと、次の形式の本文で返ります。`code` は安定した契約で、番号の付け替えはせず、追加だけを行います。 ```http HTTP/1.1 409 Conflict Content-Type: application/json { "message": "externalTxId already exists", "code": 1201 } ``` `message` は開発者向けの説明で、文言は変わることがあります。分岐には `code` を使ってください。 ### コード一覧 | HTTP | code | 意味 | 貴社側の扱い | |---|---|---|---| | 400 | 1101 | 未知のフィールド、または未対応のクエリパラメーター | 再送しない。リクエストを修正 | | 400 | 1102 | フィールドの形式不正(必須項目の欠落、長さ、列挙値) | 再送しない。リクエストを修正 | | 400 | 1103 | `amount` の形式不正(小数 18 桁超、0 以下、文字列でない) | 再送しない。金額を修正 | | 400 | 1104 | JSON として読めない本文 | 再送しない | | 400 | 1401 | 自動署名モードの API キーに `signer` が無い | `signer` を付ける | | 400 | 1402 | 承認モードの API キーに `signer` がある | `signer` を外す | | 401 | 1001 | `X-API-Key` が無い | ヘッダーを付ける | | 401 | 1002 | アクセストークンが無い、無効、期限切れ | トークンを取り直す | | 401 | 1003 | `X-API-Key` がトークンのクライアント ID と一致しない、または未登録の API キー | 設定を確認 | | 403 | 1003 | `source.id` がこの API キーの Vault ではない | Vault アカウント ID を確認 | | 403 | 1004 | API キーが失効済み | UPBOND に連絡 | | 403 | 1005 | 送信元 IP が許可されていない | 送信元と登録内容を確認 | | 403 | 1412 | シークレットが失効済み | 新しいシークレットに切り替える | | 403 | 1413 | シークレットがこの API キーの上限に含まれていない | 所有者がウォレットの「API キー」でこのシークレットと一緒に上限を保存する(再発行後は保存が必要) | | 403 | 1417 | この API キーの上限がシークレットを 1 つも含んでいない(版 2 より前の上限) | 所有者が上限を署名し直す | | 404 | 1601 | 取引が存在しない | ID を確認 | | 409 | 1201 | `externalTxId` が既に存在する | `GET /v1/transactions/external_tx_id/{externalTxId}` で既存の取引を照会 | | 409 | 1202 | 同じ `Idempotency-Key` で本文が異なる | 新しいキーで送るか、既存の取引を照会 | | 409 | 1203 | 同じ `Idempotency-Key` の処理が進行中 | 数秒待って再送 | | 422 | 1301 | 未対応の `assetId` | 接続情報の assetId を使う | | 422 | 1302 | Vault が未準備、または終了済み | UPBOND に連絡 | | 422 | 1303 | Vault 所有者の同意が切れている | 所有者に再接続を依頼([Vault の接続と維持](./vault.md)) | | 422 | 1304 | Vault 所有者がこの API キーの送金上限に署名していない、または取り消した | 所有者にウォレットの設定「API キー」で上限の保存を依頼。UPBOND では解除できない。登録後、同じリクエストをそのまま再送できる([ポリシー](./policy.md)) | | 422 | 1305 | 所有者が登録した上限の有効期限が切れている(または開始前) | 所有者に登録し直しを依頼。登録後、同じリクエストをそのまま再送できる | | 422 | 1310 | Vault の登録に不整合があり、UPBOND がその Vault の送金を止めている(取引は作られません) | UPBOND に連絡。UPBOND 側で登録を直して解除するまで、同じ Vault の送金はすべてこの応答になる。解除後、同じリクエストをそのまま再送できる | | 422 | 1410 | `signer.keyId` が古い | 公開鍵を取り直して同じリクエストを再送 | | 422 | 1411 | 封筒を復号できない、または平文が 73 バイトのバージョン 1 の形式でない(1.2 までの 32 バイト形式を含む) | OAEP のパラメーターと[平文の形式](./signing-secret.md#平文の形式73-バイト)を確認 | | 422 | 1414 | 封筒が別のリクエスト本文に束縛されている | 送る本文で封筒を作り直す([正規化](./signing-secret.md#正規化したリクエスト)) | | 422 | 1415 | 封筒の `issuedAt` が ±5 分の窓の外 | 送信直前に封筒を作る。サーバーの時計を確認 | | 429 | 1501 | レート制限 | `Retry-After` 秒後に再送 | | 429 | 1502 | 同じ Vault の別の送金を UPBOND が処理中で、待ち時間内に順番が来なかった(取引は作られません) | `Retry-After` 秒後に同じリクエストをそのまま再送 | | 500 | 5000 | UPBOND 側の内部エラー | 同じ `Idempotency-Key` で指数バックオフ再送 | ### 再送してよいもの、いけないもの - `429` と `500` は、同じ `Idempotency-Key` で再送してください。応答を受け取れなかった場合(タイムアウト、接続断)も同じです。 - `4xx` の応答は `Idempotency-Key` に記録されません。原因を直して同じキーで再送できます。 - `409` / `1201` は「その `externalTxId` の取引は既にある」という意味なので、再送ではなく照会に切り替えてください。 - 取引が終端状態(`COMPLETED` / `BLOCKED` / `REJECTED` / `CANCELLED` / `FAILED`)になった後は、同じ `externalTxId` を使い回せません。やり直す場合は新しい `externalTxId` で作り直します。これには、受付後に Vault 所有者が上限を変更・取り消したために `BLOCKED` / `FAILED`(`subStatus: BLOCKED_BY_POLICY`)になった取引も含まれます([ポリシー](./policy.md#受付後に所有者が上限を変えたとき))。受付**前**に拒否された `422` / `1304` / `1305` とは違い、終端になった取引の `externalTxId` は戻りません。 - 終端でない取引(`BROADCASTING` / `CONFIRMING` など)は、長く続いていても作り直さないでください。署名済みのトランザクションが後から成立し、同じ送金が 2 回成立するおそれがあります([`BROADCASTING` が長く続くとき](./transactions.md#broadcasting-が長く続くとき))。 --- ## はじめに STG で最初の送金ができるまでの手順です。貴社側にサーバーやクラウド設備の追加は不要で、必要なのは API を呼ぶサーバーと、Vault 所有者のブラウザだけです。 ### 1. 貴社で用意するもの | 用意するもの | 内容 | |---|---| | RSA 鍵ペア | 認証用。4096 bit を推奨します。秘密鍵は貴社サーバーの外に出しません | | 送信元グローバル IP | 任意。完全一致で登録します(CIDR は不可)。登録すると、それ以外の送信元は 403 になります | | 還付 ID の採番規則 | `externalTxId` に載せます。Vault の中で永続的に一意である必要があります | | シークレットの保管先 | シークレットと秘密鍵を保管する仕組み(Secrets Manager など) | | Vault 所有者 | 法人ウォレットの持ち主。接続とシークレットの発行を行います | 鍵ペアの生成例です。 ```bash openssl genrsa -out upbond-api.key 4096 openssl rsa -in upbond-api.key -pubout -out upbond-api.pub ``` ### 2. UPBOND に提出するもの 次を UPBOND の担当窓口に送ってください。公開鍵は PEM のままで構いません。 - 公開鍵(`upbond-api.pub`) - 送信元グローバル IP(IP 制限を使う場合。完全一致、CIDR 不可) - (上限は UPBOND に提出しません。1 件上限・日次累計上限・宛先・有効期限は Vault 所有者がウォレットで署名して登録します — [ポリシー](./policy.md)) - Vault 所有者の連絡先 UPBOND は認証基盤に貴社の API クライアントを登録し、次の**接続情報**を返します。 | 項目 | 説明 | |---|---| | API キー ID | `X-API-Key` に載せる値。認証基盤のクライアント ID と同じです。秘密ではありませんが、秘密鍵と組で扱ってください | | API ホスト名 | STG / PROD それぞれ | | Vault アカウント ID | `source.id` に載せる値 | | assetId | その環境で送金できるトークン(STG は `JPYC_FUJI`、本番は `JPYC_AVALANCHE`) | | 確認数 | `COMPLETED` になるまでに待つブロック確認数 | ### 3. Vault 所有者の作業 #### 3-a. Vault を接続する UPBOND から Vault 所有者に接続用の URL が届きます。所有者はブラウザでその URL を開き、ログインして同意します。この同意が、API による署名の「所有者の認証」側の要素になります。 :::caution 同じログイン方法でログインしてください ウォレットを作ったときと同じログイン方法(Google なら Google、メールの確認コードならメールの確認コード)を選んでください。認証基盤はログイン方法ごとに別のアカウントとして扱うため、同じメールアドレスでも別のログイン方法では別のウォレットになります。接続先のウォレットアドレスが Vault と一致しない接続は拒否されます。 ::: 同意は **90 日**で切れます。期限前に UPBOND から再接続の案内が届くので、同じ手順で再接続します。詳細は [Vault の接続と維持](./vault.md) を参照してください。 #### 3-b. シークレットを発行する 1. 所有者が UPBOND ウォレット(STG は `https://wallet.stg.upbond.io`)にログインし、設定 →「API キー」を開きます。UPBOND が登録した API キーが表示名で並びます。1 つの API キーには **1 つのシークレット**と **1 組の上限**があります。 2. 対象の API キーを開き、ラベル(例: 本番エージェント)を入力して「シークレットを発行」を押し、本人確認(パスキー)を行います。 3. **シークレット**(base64、44 文字)が 1 回だけ表示されます。委任先(貴社のサーバーや AI エージェント)のシークレット管理に直接保管し、「保管しました(閉じる)」を押します。UPBOND は控えを持たず、再表示もできません。UPBOND に送らないでください。 4. 画面に、この API キーのシークレット(末尾 6 桁)が表示されます。UPBOND への連絡は不要です。 5. 続けて同じ画面の「上限」で送金の上限を保存します([ポリシー](./policy.md))。上限はこのシークレットと一緒に保存されます(確認画面に「シークレット …末尾 6 桁」が表示されます)。**保存が済むまで、そのシークレットでは送金できません**(上限が無いキーも送金できません)。保存のたびに本人確認(パスキー)が求められます。 紛失した・漏えいが疑われる場合は「シークレットを再発行」します。新しいシークレットが 1 回だけ表示されるので、貴社側(エージェント)を新しいシークレットに切り替えてから「上限を保存」してください。保存した時点で古いシークレットでは送金できなくなり、続けて古いシークレットを失効できます。API キーの表示名は「名前を変更」で変えられます(表示だけで、権限には関係しません)。 ### 4. 疎通確認 接続情報を受け取ったら、[認証](./authentication.md) の手順でアクセストークンを取得し、次を呼びます。`200` と空配列(または既存の取引一覧)が返れば疎通は成立です。 ```http GET /v1/transactions?limit=1 X-API-Key: {apiKeyId} Authorization: Bearer {access_token} ``` | 順 | 観点 | 確認内容 | |---|---|---| | 1 | 接続先 | 環境(STG / PROD)のホスト名が正しいか | | 2 | 送信元 IP | IP 制限を登録した場合、登録済みの送信元から呼んでいるか(`403` / `1005`) | | 3 | トークン取得 | トークンエンドポイントが `200` を返すか。`invalid_client` なら公開鍵の登録、アサーションの `aud`・期限、時刻同期を確認 | | 4 | API 呼び出し | トークンが期限内で、`X-API-Key` がトークンのクライアント ID と一致しているか(`401`) | ### 5. 初回送金 1. `GET /v1/upbond/signer` で署名環境の公開鍵を取得します。 2. シークレットをその公開鍵で暗号化して封筒を作ります([シークレットと封筒](./signing-secret.md))。 3. `POST /v1/transactions` を送ります([送金と取引照会](./transactions.md))。自動署名モードでは、このリクエストの中で署名と送信まで行うため、応答に数秒かかります。HTTP クライアントのタイムアウトは 60 秒以上にしてください。 4. `GET /v1/transactions/{txId}` で `txHash` と状態を確認し、`COMPLETED` を業務上の完了として扱います。 STG のテストネットで送金するには、Vault にテスト用のトークンとガス代用のネイティブトークン(Fuji の AVAX)が必要です。入金は UPBOND が行います。 ### 6. 本番へ 本番でも手順は同じです。本番の接続情報(API ホスト名、Vault アカウント ID、`JPYC_AVALANCHE`)と、本番の認証基盤 `https://auth.upbond.io` に切り替えます。本番用のシークレットは、本番ウォレットの所有者が本番の UPBOND ウォレットで発行します。 --- ## Transfer API 概要 ## UPBOND Transfer API UPBOND Transfer API は、法人 Vault(UPBOND の MPC ウォレット)から JPYC を送金し、その状態を照会するための API です。還付や支払いのように「1 件ずつ、宛先と金額を指定して送る」業務を、貴社のサーバーから API 呼び出しだけで行えます。API の語彙(`operation` / `assetId` / `source` / `destination` / `status`)は Fireblocks 形式に準拠しているため、同形式の API を扱った経験があればそのまま読めます。 本書の版は **1.1**([変更履歴](./changelog.md))です。 ### できること | 操作 | API | |---|---| | 送金を 1 件作成する | `POST /v1/transactions` | | 取引を UPBOND の ID で取得する | `GET /v1/transactions/{txId}` | | 取引を貴社の ID(`externalTxId`)で取得する | `GET /v1/transactions/external_tx_id/{externalTxId}` | | 取引一覧を取得する(ポーリング用) | `GET /v1/transactions` | | 署名環境の公開鍵を取得する(自動署名モード) | `GET /v1/upbond/signer` | API はこの 5 本だけです。API キーと Vault の設定は UPBOND が代行し、送金の上限は Vault 所有者がウォレットで署名して登録するため、どちらも公開 API にはありません。 ### 運用モード API キーごとに 2 つのモードがあります。 | 観点 | 自動署名モード | 承認モード | |---|---|---| | 署名するもの | Vault 所有者が発行した**シークレット**を、送金ごとに暗号化して添える | Vault 所有者がウォレットで承認 | | 人手 | 不要(1 件上限・日次累計上限の範囲内) | 承認のたびに必要 | | 提供状況 | **提供中** | 準備中(API は受け付けますが、承認画面はまだ提供していません) | 本書は自動署名モードを前提に説明します。 ### 全体の流れ ```mermaid sequenceDiagram autonumber participant A as 貴社サーバー participant U as UPBOND Transfer API participant C as ブロックチェーン A->>U: GET /v1/upbond/signer(公開鍵を取得、expiresAt までキャッシュ) A->>U: POST /v1/transactions(externalTxId とシークレットの封筒を添える) U->>U: 認証、上限・重複を検査、封筒を復号して署名、シークレットを破棄 U->>C: 送信(BROADCASTING) U-->>A: { id, status } loop 30 秒以上の間隔 A->>U: GET /v1/transactions?after=… U-->>A: 状態・txHash・確認数 end C-->>U: 所定の確認数に到達 → COMPLETED ``` ### 役割 | 役割 | 誰が | すること | |---|---|---| | API ユーザー | 貴社のサーバー | 送金の作成、状態の照会、シークレットの保管と封筒化 | | Vault 所有者 | 法人ウォレットの持ち主 | Vault の接続(90 日ごとに再接続)、API キーごとのシークレットの発行・再発行・失効、**上限(シークレットと一緒に署名)の登録・更新・取り消し**(ウォレットで署名。UPBOND は変更できません) | | UPBOND | — | API の提供、送信と監視、API キー(表示名付き)・送信元 IP の設定代行、所有者が署名した上限の検証と強制 | ### 鍵の所在と非カストディ 法人 Vault は UPBOND の MPC(閾値署名)ウォレットです。署名には「Vault 所有者の認証」と「署名要素」の両方が必要で、UPBOND のサーバーだけでは署名できません。 自動署名モードのシークレットは、この署名要素の 1 つです。Vault 所有者がウォレットの設定画面で発行し、発行時に 1 回だけ表示されます。UPBOND は保存しません。貴社は送金のたびに、UPBOND の署名環境の公開鍵でシークレットを暗号化して送ります。署名環境はそれを復号して 1 回の署名に使い、直後に破棄します。 :::warning シークレットは秘密鍵と同等に扱ってください API キーだけが漏えいした場合、API の経路でできることは Vault 所有者が定めた上限(1 件・日次累計・宛先許可リスト)の範囲に限られます。しかしシークレットと法人アカウントのログインが揃うと、API の外でも署名できます。シークレットは秘密鍵と同じ基準で保管し、漏えいの疑いがあれば直ちに失効してください([シークレットと封筒](./signing-secret.md))。 ::: 現在の署名環境は、鍵管理サービスの中で復号する構成です。`GET /v1/upbond/signer` の `attestation` は空文字で、隔離実行環境によるアテステーションは今後の提供項目です。 ### 接続先 | 環境 | 用途 | チェーン | API ホスト名 | 認証基盤 | |---|---|---|---|---| | STG | 結合試験・受入試験 | Avalanche Fuji(テストネット、chainId 43113、`JPYC_FUJI`) | 接続情報として個別に案内 | `https://auth.stg.upbond.io` | | PROD | 本番 | Avalanche C-Chain メインネット(chainId 43114、`JPYC_AVALANCHE`) | 接続情報として個別に案内 | `https://auth.upbond.io` | すべて HTTPS で、API のパスは `/v1` 配下です。API ホスト名、Vault アカウント ID、対象トークンのコントラクトアドレスは、接続情報として API キーと一緒に案内します。本番の JPYC のコントラクトアドレスは `0xE7C3D8C9a439feDe00D2600032D5dB0Be71C3c29`(decimals 18)です。ガス代は両環境とも AVAX で支払います(STG はテストネットの AVAX)。取引の確認には Avalanche のエクスプローラー([Snowtrace](https://snowtrace.io/)、STG は [testnet.snowtrace.io](https://testnet.snowtrace.io/))を使えます。 ### 読む順番 1. [はじめに](./getting-started.md) — 接続までの手順 2. [認証](./authentication.md) — ヘッダーとアクセストークン 3. [シークレットと封筒](./signing-secret.md) — 自動署名モードの要 4. [Vault の接続と維持](./vault.md) — 所有者の同意と 90 日の期限 5. [送金と取引照会](./transactions.md) — リクエスト、状態遷移、ポーリング 6. [エラーコード](./errors.md)、[ポリシー](./policy.md)、[サンプル](./samples.md)、[API リファレンス](/transfer-api/reference/) --- ## ポリシーと運用モード 送金の上限(1 件上限・日次累計上限・宛先・有効期限)は **Vault 所有者がウォレットで定めます**。所有者は wallet.upbond.io の設定「API キー」で対象のキーを開き、「上限」で値を入力し、内容を確認したうえで、法人ウォレット自身の鍵(生体認証)で署名して登録します。UPBOND はこの署名を検証して保管し、送金のたびに参照するだけです。**UPBOND が所有者に代わって上限を作ったり引き上げたりすることはできません**(UPBOND にできるのは API キーや Vault 接続の停止だけです)。**どのシークレットが署名してよいか**も、この上限の一部として所有者が署名します。送信元 IP は導入時と変更時に UPBOND へ伝えてください。設定は公開 API には出ません。 ### 上限の登録(Vault 所有者) 1. 所有者が wallet.upbond.io にログインし、設定「API キー」で対象の API キーを開きます。 2. 1 件あたりの上限(JPYC)、1 日の上限(JPYC、日本時間 0:00 区切り)、送金先アドレス(任意、1 行に 1 つ)、有効期間(30・90・180・365 日)を入力し、「内容を確認する」を押します。この API キーのシークレットは自動的に含まれます(選ぶ項目はありません)。 3. 確認画面に、署名される内容がそのまま表示されます(表示されている内容だけが署名されます。「シークレット …末尾 6 桁」の行もその一部です)。「生体認証で署名して登録」で署名し、UPBOND に送られます。この署名では、直前に別の操作で本人確認を済ませていても、必ず本人確認が求められます。 4. 登録はその場で有効になります。登録後は、拒否されていた送金を同じ `externalTxId`・`Idempotency-Key` のまま再送できます。 上限には**有効期限**があります(最長 365 日)。期限が切れると送金は `422` / `1305` で拒否されるので、期限前に所有者が登録し直してください。上限を変えるときは新しい内容で登録し直します(古い登録に戻すことはできません)。「上限を取り消す」で、その API キーからの送金をすべて止められます。 ### 設定項目 | 設定 | 誰が定めるか | 内容 | 違反したとき | |---|---|---|---| | 1 件あたり上限 | Vault 所有者(ウォレットで署名して登録) | JPYC 建ての 1 取引の上限額 | 取引は `BLOCKED`(`subStatus: BLOCKED_BY_POLICY`)。署名は行われません | | 日次累計上限 | Vault 所有者(ウォレットで署名して登録) | その API キーが 1 日(日本時間 0:00 区切り)に署名できる合計額。受付時に合計へ加算してから署名するため、同時に送っても、API が複数台で動いていても、合計が上限を超えることはありません。送信前に失敗した取引(残高不足・署名失敗・同意切れ)の額は枠に戻ります。送信後の取引は結果(成立・revert・取り下げ)にかかわらず戻りません | 取引は `BLOCKED`(`subStatus: BLOCKED_BY_POLICY`)。日本時間 0:00 に枠が戻ります | | 宛先許可リスト | Vault 所有者(任意、ウォレットで署名して登録) | 送金先アドレスの一覧(EIP-55 チェックサム形式。照合は大文字小文字を区別しません)。登録すると、それ以外の宛先は拒否されます。未登録なら宛先の制限はありません | 取引は `BLOCKED`(`subStatus: BLOCKED_BY_POLICY`) | | 上限の有効期限 | Vault 所有者(ウォレットで署名して登録、最長 365 日) | 登録した上限が有効な期間。期限切れ・開始前の上限では送金できません | `422` / `1305`。所有者が登録し直すまで送金は作られません | | 送信元 IP | UPBOND(貴社の申告) | 任意。完全一致で登録します(CIDR 不可)。登録すると、それ以外の送信元は拒否されます | `403` / `1005` | | シークレット | Vault 所有者(上限の一部としてウォレットで署名して登録。保存時に自動で含まれる) | 上限に含まれる公開鍵に対応するシークレット(API キーごとに 1 つ)だけが、その API キーで署名できます。それ以外は拒否され、シークレットの無い上限は受け付けません | `403` / `1413`(シークレットを含まない旧い上限は `403` / `1417`) | | 運用モード | UPBOND | 自動署名モードまたは承認モード | — | :::note 上限が未登録・取り消し済みの API キーは送金できません Vault 所有者が上限を登録していない、または取り消した API キーで取引を作ると、取引は作られずに `422` / `1304` で拒否されます。`1304` は「所有者がまだ上限に署名していない(または取り消した)」という意味で、UPBOND 側で解除できるものではありません。所有者に登録を依頼してください。登録後、同じ `externalTxId` と `Idempotency-Key` のまま再送できます。 ::: 自動署名モードで API キーとシークレットの両方が漏えいした場合でも、API の経路で動かせる額は 1 件上限と日次累計上限の範囲に限られ、宛先許可リストを登録していればその宛先に限られます。 ### 受付後に所有者が上限を変えたとき 上限の判定は、取引を受け付けた**後**、その Vault の処理待ち行列の順番が来た時点の上限で行います(同じ Vault の署名は 1 件ずつ直列に処理するため、混み合っていると受付から判定まで時間が空きます)。判定の直後、署名の直前にも、判定に使った上限がそのまま有効かを確認します。 そのため、取引を受け付けてから署名するまでの間に Vault 所有者が上限を**変更・取り消し**した、またはシークレットを上限から**外した**場合、その取引は次のように**終端**になります。署名は行われず、資産は動きません。 | タイミング | 結果 | |---|---| | 判定の時点で、上限が取り消されていた・有効期限が切れていた・別の Vault や資産を指していた、または封筒のシークレットが上限に含まれていなかった | `status: BLOCKED`、`subStatus: BLOCKED_BY_POLICY` | | 判定は通ったが、署名の直前に上限が新しい版に置き換わっていた(金額・宛先・シークレットのどれが変わったかにかかわらず)または取り消されていた | `status: FAILED`、`subStatus: BLOCKED_BY_POLICY` | どちらも終端なので、**同じ `externalTxId` は使えません**。所有者が新しい上限を登録した後、必要なら新しい `externalTxId`(と新しい封筒)で作り直してください。日次累計に加算した額は戻ります。 受付**前**に上限が無い・取り消し済み・期限切れだった場合は、取引を作らずに `422` / `1304` または `1305` で拒否するので、同じ `externalTxId` のまま再送できます(前節)。所有者による上限の変更は、まとめて送金を投入している時間帯を避けて行うことを推奨します。 ### 上限を超えたとき 自動署名モードで 1 件上限または日次累計上限を超えた取引は、既定では `BLOCKED` になります。UPBOND 側の設定で承認待ち(`PENDING_AUTHORIZATION`)に回す構成もありますが、承認して進める機能は未提供のため、現在は `BLOCKED` で運用します。宛先許可リスト外の宛先への取引は、この設定にかかわらず常に `BLOCKED` です。 ### 承認モード 承認モードの API キーで作った取引は `PENDING_AUTHORIZATION` で止まります。承認画面は準備中のため、現在は自動署名モードでの提供です。提供開始時に本書を更新します。 ### 失効 | 対象 | 誰が | 効果 | |---|---|---| | シークレット | Vault 所有者(ウォレットの「API キー」で「シークレットを再発行」→ 上限を保存 → 古いシークレットを失効) | 法人ウォレットの署名要素が更新され、そのシークレットはどこからも使えなくなります | | 上限 | Vault 所有者(ウォレットの「API キー」>「上限を取り消す」) | その API キーからの送金はすべて `422` / `1304` で拒否されます。再開するには所有者が新しい上限を登録します | | シークレットの停止(UPBOND 側) | UPBOND | 上限に含まれていても、その API キーでは署名を試みる前に `403` / `1412` で拒否されます | | API キー | UPBOND | すべての呼び出しが `403` / `1004` になります | | Vault の接続 | UPBOND(所有者の依頼) | 同意が失効し、送金は `422` / `1303`。再接続で再開できます | 漏えいの疑いがあるときは、所有者によるシークレットの失効(と上限の署名し直し)に加え、UPBOND への停止依頼も直ちに行ってください。 ### 監査ログ UPBOND は、取引の作成者(API キー ID)、ポリシーの判定(適用した上限とその版、日次累計、判定理由)、送信、失効、設定変更、所有者による上限の登録・取り消しを追記専用のログに記録します。シークレット、アクセストークン、所有者の認証情報は記録しません。 --- ## サンプル いずれも、秘密鍵とシークレットは環境変数やシークレット管理から読み、コードやリポジトリには置かないでください。 | 環境変数 | 内容 | |---|---| | `UPBOND_API_KEY` | API キー ID | | `UPBOND_AUTH_BASE` | `https://auth.stg.upbond.io`(本番は `https://auth.upbond.io`) | | `UPBOND_API_BASE` | 接続情報の API ホスト名(`https://…`) | | `UPBOND_VAULT_ID` | Vault アカウント ID | | `UPBOND_ASSET_ID` | 接続情報の assetId | | `UPBOND_PRIVATE_KEY_FILE` | 認証用の RSA 秘密鍵(PEM)のパス | | `UPBOND_SIGNING_SECRET` | シークレット(base64、44 文字) | ### Node.js 依存は `jose` だけです(`npm i jose`)。Node.js 20 以降。 ```js // upbond-transfer.mjs import { constants, createHash, createPrivateKey, publicEncrypt, randomUUID } from 'node:crypto'; import { readFileSync } from 'node:fs'; import { SignJWT } from 'jose'; const env = process.env; const apiKey = env.UPBOND_API_KEY; const authBase = env.UPBOND_AUTH_BASE; const apiBase = env.UPBOND_API_BASE; const privateKey = createPrivateKey(readFileSync(env.UPBOND_PRIVATE_KEY_FILE)); // RFC 7523 client assertion: proves possession of the registered key. Short-lived. async function clientAssertion() { return new SignJWT({}) .setProtectedHeader({ alg: 'RS256' }) .setIssuer(apiKey) .setSubject(apiKey) .setAudience(authBase) .setJti(randomUUID()) .setIssuedAt() .setExpirationTime('60s') .sign(privateKey); } // Opaque access token, cached until 30 s before expiry. let cached = { token: null, expiresAt: 0 }; export async function accessToken() { if (cached.token && Date.now() < cached.expiresAt - 30_000) return cached.token; const res = await fetch(`${authBase}/oauth/token`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ grant_type: 'client_credentials', client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer', client_assertion: await clientAssertion(), }), }); if (!res.ok) throw new Error(`token endpoint ${res.status}: ${await res.text()}`); const { access_token, expires_in } = await res.json(); cached = { token: access_token, expiresAt: Date.now() + expires_in * 1000 }; return access_token; } async function headers(extra = {}) { return { 'X-API-Key': apiKey, Authorization: `Bearer ${await accessToken()}`, 'Content-Type': 'application/json', ...extra, }; } // Signing-environment key, cached until expiresAt (re-fetched on a 1410). let signer = null; async function signerKey(force = false) { if (!force && signer && Date.now() < signer.expiresAt) return signer; const res = await fetch(`${apiBase}/v1/upbond/signer`, { headers: await headers() }); if (!res.ok) throw new Error(`signer ${res.status}: ${await res.text()}`); signer = await res.json(); return signer; } // The request a bound envelope names: seven fields exactly as sent, LF-joined // (feeLevel defaults to MEDIUM and note to "" when the body omits them). function canonicalRequest(body) { return [ body.assetId, body.source.id, body.destination.oneTimeAddress.address, body.amount, body.feeLevel ?? 'MEDIUM', body.externalTxId, body.note ?? '', ].join('\n'); } // RSA-OAEP-SHA256 envelope, bound to `body` and stamped now: // 0x01 || secret(32) || sha256(canonicalRequest)(32) || issuedAt(8, BE ms). function envelope(key, body) { const issuedAt = Buffer.alloc(8); issuedAt.writeBigUInt64BE(BigInt(Date.now())); const secret = Buffer.from(env.UPBOND_SIGNING_SECRET, 'base64'); const plaintext = Buffer.concat([ Buffer.from([0x01]), secret, createHash('sha256').update(canonicalRequest(body), 'utf8').digest(), issuedAt, ]); try { const ciphertext = publicEncrypt( { key: key.publicKeyPem, padding: constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' }, plaintext, ); return { keyId: key.keyId, envelope: ciphertext.toString('base64') }; } finally { // Neither the plaintext nor the secret copy outlives the call. plaintext.fill(0); secret.fill(0); } } // One refund = one transaction. externalTxId doubles as the Idempotency-Key. export async function createTransfer({ externalTxId, address, amount, note }) { const body = { operation: 'TRANSFER', assetId: env.UPBOND_ASSET_ID, source: { type: 'VAULT_ACCOUNT', id: env.UPBOND_VAULT_ID }, destination: { type: 'ONE_TIME_ADDRESS', oneTimeAddress: { address } }, amount, externalTxId, ...(note ? { note } : {}), }; for (let attempt = 0; attempt < 2; attempt++) { const key = await signerKey(attempt > 0); const res = await fetch(`${apiBase}/v1/transactions`, { method: 'POST', headers: await headers({ 'Idempotency-Key': externalTxId }), // A fresh envelope per attempt: it is bound to this body and to "now". body: JSON.stringify({ ...body, signer: envelope(key, body) }), signal: AbortSignal.timeout(90_000), }); const result = await res.json(); // 1410: the signer key rotated — fetch it again and re-send the same request. if (res.status === 422 && result.code === 1410 && attempt === 0) continue; if (!res.ok) throw new Error(`create ${res.status}: ${JSON.stringify(result)}`); return result; // { id, status } } } export async function getTransfer(txId) { const res = await fetch(`${apiBase}/v1/transactions/${txId}`, { headers: await headers() }); if (!res.ok) throw new Error(`get ${res.status}: ${await res.text()}`); return res.json(); } export async function getTransferByExternalTxId(externalTxId) { const res = await fetch( `${apiBase}/v1/transactions/external_tx_id/${encodeURIComponent(externalTxId)}`, { headers: await headers() }, ); if (!res.ok) throw new Error(`get ${res.status}: ${await res.text()}`); return res.json(); } // Polling: follow next-page until it disappears. export async function listTransfers(params) { let url = `${apiBase}/v1/transactions?${new URLSearchParams(params)}`; const all = []; while (url) { const res = await fetch(url, { headers: await headers() }); if (!res.ok) throw new Error(`list ${res.status}: ${await res.text()}`); all.push(...(await res.json())); url = res.headers.get('next-page'); } return all; } ``` 使い方の例です。 ```js import { createTransfer, getTransfer } from './upbond-transfer.mjs'; const { id, status } = await createTransfer({ externalTxId: 'refund-2026-000123', address: '0x1111111111111111111111111111111111111111', amount: '12345.00', note: 'Refund #000123', }); console.log(id, status); // BROADCASTING(失敗時は FAILED) const tx = await getTransfer(id); console.log(tx.status, tx.subStatus, tx.txHash); ``` ### curl アクセストークンと封筒は上の Node.js の関数で作ってから、環境変数に入れて呼ぶ例です。 ```bash # 1. アクセストークン($ASSERTION は clientAssertion() の出力) curl -s -X POST "$UPBOND_AUTH_BASE/oauth/token" \ -d grant_type=client_credentials \ -d client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer \ -d "client_assertion=$ASSERTION" # → { "access_token": "…", "token_type": "Bearer", "expires_in": 300 } # 2. 署名環境の公開鍵 curl -s "$UPBOND_API_BASE/v1/upbond/signer" \ -H "X-API-Key: $UPBOND_API_KEY" -H "Authorization: Bearer $TOKEN" # 3. 送金の作成($KEY_ID と $ENVELOPE は、この本文と同じ assetId / source.id / 宛先 / # amount / feeLevel / externalTxId で作った envelope() の出力。封筒は本文に束縛されるので、 # 本文を変えたら封筒も作り直す) curl -s -X POST "$UPBOND_API_BASE/v1/transactions" \ -H "X-API-Key: $UPBOND_API_KEY" -H "Authorization: Bearer $TOKEN" \ -H "Idempotency-Key: refund-2026-000123" -H "Content-Type: application/json" \ -d "{ \"operation\": \"TRANSFER\", \"assetId\": \"$UPBOND_ASSET_ID\", \"source\": { \"type\": \"VAULT_ACCOUNT\", \"id\": \"$UPBOND_VAULT_ID\" }, \"destination\": { \"type\": \"ONE_TIME_ADDRESS\", \"oneTimeAddress\": { \"address\": \"0x1111111111111111111111111111111111111111\" } }, \"amount\": \"12345.00\", \"externalTxId\": \"refund-2026-000123\", \"signer\": { \"keyId\": \"$KEY_ID\", \"envelope\": \"$ENVELOPE\" } }" # 4. 照会 curl -s "$UPBOND_API_BASE/v1/transactions/external_tx_id/refund-2026-000123" \ -H "X-API-Key: $UPBOND_API_KEY" -H "Authorization: Bearer $TOKEN" # 5. 一覧(next-page ヘッダーを見るため -i) curl -si "$UPBOND_API_BASE/v1/transactions?after=1762470000000&limit=200" \ -H "X-API-Key: $UPBOND_API_KEY" -H "Authorization: Bearer $TOKEN" ``` ### PHP Laravel での例です。依存は `firebase/php-jwt`(クライアントアサーション)と `phpseclib/phpseclib:^3`(封筒)です。 :::caution PHP 8.4 以前の `openssl_public_encrypt()` は使えません PHP 8.4 以前の標準 openssl 拡張は OAEP のハッシュが SHA-1 固定で、この API が要求する SHA-256 の封筒を作れません(`422` / `1411` になります。PHP 8.5 で `digest_algo` 引数が追加されました)。封筒には phpseclib 3 を使ってください。封筒の生成だけを Node.js の小さなプロセスに切り出す構成でも構いません。 ::: ```php $this->apiKey, 'sub' => $this->apiKey, 'aud' => $this->authBase, 'jti' => (string) Str::uuid(), 'iat' => $now, 'exp' => $now + 60, ], $this->privateKeyPem, 'RS256'); } /** Opaque access token, cached until 30 seconds before expiry. */ private function accessToken(): string { // Namespaced per auth server and API key so two configurations never share a token. $cacheKey = 'upbond.access_token.'.sha1($this->authBase.'|'.$this->apiKey); return Cache::remember($cacheKey, 270, function () { $res = Http::asForm()->post($this->authBase.'/oauth/token', [ 'grant_type' => 'client_credentials', 'client_assertion_type' => 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer', 'client_assertion' => $this->clientAssertion(), ])->throw(); return $res->json('access_token'); }); } private function headers(array $extra = []): array { return array_merge([ 'X-API-Key' => $this->apiKey, 'Authorization' => 'Bearer '.$this->accessToken(), ], $extra); } /** Signing-environment key, cached for a day and refreshed on a 1410. */ private function signerKey(bool $force = false): array { $cacheKey = 'upbond.signer_key.'.sha1($this->apiBase.'|'.$this->apiKey); if ($force) { Cache::forget($cacheKey); } return Cache::remember($cacheKey, 86400, function () { return Http::withHeaders($this->headers()) ->get($this->apiBase.'/v1/upbond/signer') ->throw() ->json(); }); } /** The request a bound envelope names: seven fields exactly as sent, LF-joined * (feeLevel defaults to MEDIUM and note to "" when the body omits them). */ private function canonicalRequest(array $body): string { return implode("\n", [ $body['assetId'], $body['source']['id'], $body['destination']['oneTimeAddress']['address'], $body['amount'], $body['feeLevel'] ?? 'MEDIUM', $body['externalTxId'], $body['note'] ?? '', ]); } /** * RSA-OAEP with SHA-256 and MGF1-SHA-256, empty label, over the bound plaintext * 0x01 || secret(32) || sha256(canonicalRequest)(32) || issuedAt(8, BE ms). */ private function envelope(array $key, array $body): array { $rsa = PublicKeyLoader::load($key['publicKeyPem']) ->withPadding(RSA::ENCRYPTION_OAEP) ->withHash('sha256') ->withMGFHash('sha256'); $secret = base64_decode($this->signingSecret, true); $plaintext = "\x01" .$secret .hash('sha256', $this->canonicalRequest($body), true) .pack('J', (int) floor(microtime(true) * 1000)); try { return [ 'keyId' => $key['keyId'], 'envelope' => base64_encode($rsa->encrypt($plaintext)), ]; } finally { // Neither the plaintext nor the secret copy outlives the call. sodium_memzero($plaintext); sodium_memzero($secret); } } /** One refund = one transaction. Returns ['id' => ..., 'status' => ...]. */ public function create(string $externalTxId, string $address, string $amount, ?string $note = null): array { $body = [ 'operation' => 'TRANSFER', 'assetId' => $this->assetId, 'source' => ['type' => 'VAULT_ACCOUNT', 'id' => $this->vaultId], 'destination' => ['type' => 'ONE_TIME_ADDRESS', 'oneTimeAddress' => ['address' => $address]], 'amount' => $amount, 'externalTxId' => $externalTxId, ]; if ($note !== null) { $body['note'] = $note; } for ($attempt = 0; $attempt < 2; $attempt++) { // A fresh envelope per attempt: it is bound to this body and to "now". $request = $body + ['signer' => $this->envelope($this->signerKey($attempt > 0), $body)]; $res = Http::withHeaders($this->headers(['Idempotency-Key' => $externalTxId])) ->timeout(90) ->post($this->apiBase.'/v1/transactions', $request); // 1410: the signer key rotated — fetch it again and re-send the same request. if ($res->status() === 422 && $res->json('code') === 1410 && $attempt === 0) { continue; } return $res->throw()->json(); } throw new \RuntimeException('unreachable'); } public function get(string $txId): array { return Http::withHeaders($this->headers()) ->get($this->apiBase.'/v1/transactions/'.$txId) ->throw() ->json(); } public function getByExternalTxId(string $externalTxId): array { return Http::withHeaders($this->headers()) ->get($this->apiBase.'/v1/transactions/external_tx_id/'.rawurlencode($externalTxId)) ->throw() ->json(); } } ``` `Cache::remember` の 270 秒は、5 分のトークン寿命から 30 秒引いた値です。複数プロセスで動かす場合も、キャッシュを共有すればトークンの取得は 5 分に 1 回で済みます。 --- ## シークレットと封筒 自動署名モードでは、送金のたびに**シークレット**を UPBOND の署名環境の公開鍵で暗号化し(これを**封筒**と呼びます)、リクエストの `signer` に添えます。署名環境は封筒を復号して 1 回の署名に使い、直後にメモリから破棄します。UPBOND のデータベースやログにシークレットが残ることはありません。 ### シークレットとは - 法人 Vault の**署名要素の 1 つ**です。Vault 所有者がウォレットの設定「API キー」で、対象の API キーに対して発行します。所有者が**上限を保存**した時点(上限はそのシークレットと一緒に署名されます)ではじめて使えます([はじめに](./getting-started.md#3-b-シークレットを発行する))。 - 発行時に 1 回だけ表示される **base64 文字列(44 文字)**で、復号すると 32 バイトの値になります。封筒の平文に入れるのはこの 32 バイトです(送金本文のハッシュと作成時刻と一緒に。[封筒を作る](#封筒を作る))。 - UPBOND は保存しません。紛失した場合は新しく発行し、古いものを失効します。 - 1 つの API キーには 1 つのシークレットがあります。上限に含まれる公開鍵に対応するシークレットだけが、その API キーで署名できます。どのシークレットが署名できるかは所有者がウォレットの鍵で署名して定めるため、UPBOND にも、所有者のログインだけを奪った者にも変えられません。 :::warning 秘密鍵と同等に扱ってください API キーだけが漏えいした場合、API の経路でできることは Vault 所有者が定めた上限(1 件・日次累計・宛先許可リスト)の範囲に限られます。しかしシークレットと法人アカウントのログインが揃うと、API の外でも署名できます。シークレットは、貴社の秘密鍵と同じ基準で保管してください。 ::: ### 署名環境の公開鍵を取得する ```http GET /v1/upbond/signer X-API-Key: {apiKeyId} Authorization: Bearer {access_token} ``` ```json { "keyId": "3", "publicKeyPem": "-----BEGIN PUBLIC KEY-----\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8A…\n-----END PUBLIC KEY-----", "attestation": "", "expiresAt": 1764547200000 } ``` | 項目 | 説明 | |---|---| | `keyId` | 鍵の識別子。封筒と一緒に送ります | | `publicKeyPem` | RSA 4096 bit の公開鍵(PEM)。対応する秘密鍵は署名環境の鍵管理サービスの中にあり、外に出ません | | `attestation` | 現在は空文字です。隔離実行環境によるアテステーションは今後の提供項目です | | `expiresAt` | この時刻(エポックミリ秒)までキャッシュしてよい目安 | UPBOND は鍵を **30 日を目安**に更新し、更新後も旧鍵を **7 日間**は復号に使える状態に保つ運用です(API が保証する契約は `expiresAt` と、次に述べる `1410` の扱いです)。`expiresAt` までキャッシュしつつ、1 日 1 回程度は取り直してください。古い `keyId` で送ると `422` / `1410` が返るので、そのときは公開鍵を取り直して同じリクエストを再送してください([再送の規則](#再送の規則))。 ### 封筒を作る 封筒は**その送金リクエストに束縛**されています(1.3 以降)。暗号化する平文にはシークレットだけでなく、リクエスト本文の要約(ハッシュ)と作成時刻を含めます。署名環境は復号後にこの 2 つを検査し、別の本文に添えられた封筒や古い封筒を拒否します。 #### 平文の形式(73 バイト) | 位置 | 長さ | 内容 | |---|---|---| | 0 | 1 バイト | バージョン。固定で `0x01` | | 1〜32 | 32 バイト | シークレット(発行時の base64 文字列を復号した 32 バイト) | | 33〜64 | 32 バイト | 正規化したリクエストの SHA-256(下記) | | 65〜72 | 8 バイト | 作成時刻 `issuedAt`。エポックミリ秒の符号なし 64 bit 整数、ビッグエンディアン | #### 正規化したリクエスト 次の 7 つの値を、**リクエスト本文に書いたとおりの文字列で**、この順に LF(`\n`、0x0A)1 文字で連結した UTF-8 文字列です。末尾に LF は付けません。大文字小文字の変換や金額の整形はしません(`"12345.00"` と `"12345"` は別のリクエストです)。`feeLevel` を本文で省略した場合は既定値の `MEDIUM` を入れます(ガス価格を決める値なので束縛に含めます)。`note` を省略した場合は空文字列を入れます(`note` は貴社の記録に残る値なので、封筒を横取りした第三者に差し替えられないよう束縛に含めます。`note` が無い本文では末尾が LF で終わる形になります)。 ``` assetId \n source.id \n destination.oneTimeAddress.address \n amount \n feeLevel \n externalTxId \n note ``` `operation`・`signer` は含めません。`externalTxId` には改行などの制御文字を使えません(`400` / `1102`。`note` は改行を含んでも構いません)。文字列はすべて正しい Unicode(孤立したサロゲートを含まない)である必要があります(違反は `400` / `1102`)。例: ``` JPYC_AVALANCHE vault-1 0x3333333333333333333333333333333333333333 12345.00 MEDIUM refund-000123 Refund #000123 ``` #### 暗号化 | パラメーター | 値 | |---|---| | 方式 | RSA-OAEP | | ハッシュ | SHA-256 | | MGF | MGF1 with SHA-256 | | ラベル | 空 | | 平文 | 上記 73 バイト | | 出力 | 暗号文を標準の base64 にしたもの(4096 文字以内) | Node.js の例です。本文を組み立ててから、その本文で封筒を作ります。 ```js import { constants, createHash, publicEncrypt } from 'node:crypto'; // body = POST /v1/transactions に送る本文(signer を除く) function canonicalRequest(body) { return [ body.assetId, body.source.id, body.destination.oneTimeAddress.address, body.amount, body.feeLevel ?? 'MEDIUM', body.externalTxId, body.note ?? '', ].join('\n'); } // signer = GET /v1/upbond/signer の応答、secret = 発行時に表示された base64 文字列 function makeEnvelope(signer, secret, body) { const issuedAt = Buffer.alloc(8); issuedAt.writeBigUInt64BE(BigInt(Date.now())); const secretBytes = Buffer.from(secret, 'base64'); // 32 bytes const plaintext = Buffer.concat([ Buffer.from([0x01]), secretBytes, createHash('sha256').update(canonicalRequest(body), 'utf8').digest(), // 32 bytes issuedAt, // 8 bytes ]); try { const envelope = publicEncrypt( { key: signer.publicKeyPem, padding: constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' }, plaintext, ).toString('base64'); return { keyId: signer.keyId, envelope }; } finally { // 平文と秘密値のコピーはメモリに残さない plaintext.fill(0); secretBytes.fill(0); } } const body = { operation: 'TRANSFER', assetId: 'JPYC_AVALANCHE', source: { type: 'VAULT_ACCOUNT', id: 'vault-1' }, destination: { type: 'ONE_TIME_ADDRESS', oneTimeAddress: { address: '0x3333…' } }, amount: '12345.00', feeLevel: 'MEDIUM', externalTxId: 'refund-000123', }; const request = { ...body, signer: makeEnvelope(signer, secret, body) }; ``` これを `POST /v1/transactions` の本文に載せます。 ```json "signer": { "keyId": "3", "envelope": "BASE64_RSA_OAEP_CIPHERTEXT" } ``` #### 封筒は 1 リクエストに 1 つ、使い回しは拒否されます - **別の本文には使えません**: 封筒の中のハッシュと本文が一致しなければ `422` / `1414` です。金額・宛先・`externalTxId`・`feeLevel`・`source.id`・`assetId` のどれか 1 文字でも違えば別の本文です。 - **時間が経つと使えません**: `issuedAt` が UPBOND 側の時刻から **±5 分**を超えてずれていると `422` / `1415` です。送信の直前に作ってください。サーバーの時計は NTP で合わせてください。 - **同じ封筒を 2 回は使えません**: 封筒は `externalTxId` に束縛され、`externalTxId` は Vault ごとに永久に一意です。同じ封筒をもう一度送ると、取引が既にあるので `409` / `1201` になり、署名は行われません(同じ `Idempotency-Key` なら元の応答が返るだけです)。 - **なぜこうなっているか**: 貴社のリクエストログや APM、プロキシのログに封筒が残ることがあります。1.2 までの封筒は本文に束縛されていなかったため、封筒 1 つと API キーが漏れると、シークレットそのものを知らなくても、上限内の送金を何度でも署名させることができました。1.3 の封筒は、作成から数分の間、その 1 件の送金にしか使えません。 1.2 までの形式(32 バイトのシークレットだけを暗号化した封筒)は受け付けません(`422` / `1411`)。移行期間はありません。 冪等比較からは引き続き `signer` を除外しているので、同じ本文を同じ `Idempotency-Key` で再送するときに封筒を作り直しても「本文不一致」(`409` / `1202`)にはなりません。 :::caution PHP 8.4 以前の openssl 拡張は使えません PHP 8.4 以前の標準 `openssl_public_encrypt()` は OAEP のハッシュが SHA-1 固定で、SHA-256 の封筒を作れません(送ると `422` / `1411` になります。PHP 8.5 で `digest_algo` 引数が追加されました)。phpseclib 3 の `RSA::loadPublicKey()->withHash('sha256')->withMGFHash('sha256')` を使うか、封筒の生成だけを Node.js の小さなプロセスに切り出してください。例は [サンプル](./samples.md#php) にあります。 ::: ### 封筒に関するエラー | HTTP | code | 意味 | 対処 | |---|---|---|---| | 400 | 1401 | 自動署名モードの API キーなのに `signer` が無い | `signer` を付ける | | 400 | 1402 | 承認モードの API キーに `signer` を付けた | `signer` を外す | | 422 | 1410 | `keyId` が古い(更新済みの鍵) | `GET /v1/upbond/signer` で取り直し、同じリクエストを再送 | | 422 | 1411 | 封筒を復号できない、または復号結果が 73 バイトのバージョン 1 の平文でない(1.2 までの 32 バイト形式を含む) | OAEP のパラメーター(SHA-256 / MGF1-SHA-256 / ラベル空)と、平文が [73 バイトの形式](#平文の形式73-バイト)であることを確認 | | 422 | 1414 | 封筒が別のリクエスト本文に束縛されている | 送る本文そのもので封筒を作り直す。[正規化](#正規化したリクエスト)の 6 項目と連結方法を確認 | | 422 | 1415 | 封筒の `issuedAt` が ±5 分の窓の外 | 送信直前に封筒を作る。サーバーの時計を確認 | | 403 | 1412 | そのシークレットは失効済み | 新しいシークレットに切り替える | | 403 | 1413 | そのシークレットはこの API キーの上限に含まれていない | 所有者がウォレットの「API キー」でこの API キーの上限を保存する(別の API キーのシークレットは使えない) | | 403 | 1417 | この API キーの上限がシークレットを 1 つも含んでいない(版 2 より前に署名した上限) | 所有者が上限を署名し直す | いずれも取引は作られず、`externalTxId` も消費されません。 ### 再送の規則 `1410`・`1411`・`1414`・`1415` は、リクエスト本文が永続化される前に判定されます。したがって、 - 同じ `Idempotency-Key` と同じ `externalTxId` のまま、封筒だけ作り直して再送できます(本文が同じなら封筒のハッシュも同じになり、`issuedAt` だけが新しくなります)。 - 冪等比較は `signer` を除いた本文で行うため、封筒が変わっても「本文不一致」(`409` / `1202`)にはなりません。 - 取引が作られる前の `4xx` / `5xx` は `Idempotency-Key` に記録されないため、再送は新規の処理になります。取引が作られた後に起きた障害の扱いは [送金と取引照会](./transactions.md) を参照してください。 ### 失効 - Vault 所有者は、ウォレットの設定「API キー」で「シークレットを再発行」し、新しいシークレットで上限を保存します(保存した時点で古いシークレットでは送金できません)。続けて古いシークレットを失効できます。失効は法人ウォレットの署名要素そのものを更新するため、その後はどこからでもそのシークレットで署名できなくなります。 - UPBOND 側でも、API キーに対してその公開鍵を失効登録できます。以後は署名を試みる前に `403` / `1412` で拒否されます。 - 漏えいの疑いがあるときは、両方を直ちに行ってください。 --- ## 送金と取引照会 ### 共通仕様 | 項目 | 内容 | |---|---| | 形式 | UTF-8、JSON。`POST` 本文の未知のフィールドと、一覧 API の未対応のクエリパラメーターは無視せず `400` / `1101` を返します | | 日時 | `createdAt` / `lastUpdated`、一覧の `after` / `before` は Unix エポックのミリ秒(整数) | | 金額 | JPYC 単位の小数文字列(例 `"12345.00"`)。内部で最小単位(18 桁)の整数へ厳密変換し、18 桁を超える小数と 0 以下は `400` / `1103` | | アドレス | `0x` から始まる 40 桁の 16 進数。チェックサム表記は任意 | | 識別子 | UPBOND 側の取引 ID は UUID。貴社側の ID は `externalTxId`(1〜255 文字、制御文字不可) | | assetId | 環境ごとに 1 つ(接続情報に記載)。それ以外は `422` / `1301` | ### 送金の作成 — `POST /v1/transactions` ```http POST /v1/transactions X-API-Key: {apiKeyId} Authorization: Bearer {access_token} Idempotency-Key: refund-2026-000123 Content-Type: application/json { "operation": "TRANSFER", "assetId": "JPYC_AVALANCHE", "source": { "type": "VAULT_ACCOUNT", "id": "{vaultAccountId}" }, "destination": { "type": "ONE_TIME_ADDRESS", "oneTimeAddress": { "address": "0x1111111111111111111111111111111111111111" } }, "amount": "12345.00", "externalTxId": "refund-2026-000123", "note": "Refund #000123", "feeLevel": "MEDIUM", "signer": { "keyId": "3", "envelope": "BASE64_RSA_OAEP_CIPHERTEXT" } } ``` | 項目 | 必須 | 説明 | |---|---|---| | `operation` | ○ | 固定値 `TRANSFER` | | `assetId` | ○ | 接続情報の assetId | | `source.type` / `source.id` | ○ | `VAULT_ACCOUNT` と、接続情報の Vault アカウント ID。API キーの Vault と違うと `403` / `1003` | | `destination.type` / `destination.oneTimeAddress.address` | ○ | `ONE_TIME_ADDRESS` と宛先アドレス | | `amount` | ○ | JPYC 単位の小数文字列 | | `externalTxId` | ○ | 貴社の ID。Vault の中で永続的に一意 | | `note` | — | 備考(500 文字以内)。取引の照会に含まれます | | `feeLevel` | — | `LOW` / `MEDIUM`(既定)/ `HIGH` | | `signer.keyId` / `signer.envelope` | 自動署名モードで必須 | [シークレットと封筒](./signing-secret.md) | ```http HTTP/1.1 200 OK { "id": "3f9c2b7e-8d0a-4c1e-9b5d-2a6f7e1c4d80", "status": "BROADCASTING" } ``` 自動署名モードでは、このリクエストの中で認証、ポリシー判定、封筒の復号、署名、送信まで行います。処理は次の順で、途中で失敗した段階によって応答が変わります。 | 段階 | 失敗したときの応答 | |---|---| | 認証・形式検査・封筒の復号 | `4xx`。取引は作られず、`externalTxId` も消費されません | | `externalTxId` の一意性 | `409` / `1201` | | 上限の判定 | `200`、`status: BLOCKED`(UPBOND 側の設定で `PENDING_AUTHORIZATION` に回す構成もあります。[ポリシー](./policy.md))。受付後に所有者が上限を取り消した・変えた場合もここで `BLOCKED` になります([受付後に所有者が上限を変えたとき](./policy.md#受付後に所有者が上限を変えたとき)) | | 署名直前の上限の再確認 | `200`、`status: FAILED`、`subStatus: BLOCKED_BY_POLICY`。判定後に所有者が上限を新しい版に置き換えた・取り消したとき。署名は行われません | | チェーンの照会(残高・nonce)、残高・手数料の検査、署名 | `200`、`status: FAILED`。理由は `GET` の `subStatus` で確認。署名前のエンジン側の一時的な障害は UPBOND が 1 回だけ自動で再試行します(応答が数秒延びることがあります) | | 送信 | `200`、`status: BROADCASTING`。`txHash` は `GET` で取得。送信の RPC が失敗しても結果は不確定なので `BROADCASTING` のまま UPBOND が追跡します。レシートが得られないだけでは `FAILED` にしません([`BROADCASTING` が長く続くとき](#broadcasting-が長く続くとき)) | 応答には `id` と `status` しかありません。`txHash` や `subStatus` は取得 API で読んでください。署名を含むため応答まで数秒かかります。HTTP クライアントのタイムアウトは 60 秒以上にしてください。同じ Vault の署名は 1 件ずつ直列に処理するため、同時に多数投入すると後の要求ほど応答が遅くなります。 :::note 受付後に UPBOND 側の障害が起きたとき 取引が作られた後、署名の前に UPBOND がチェーンを読めなかった(残高や nonce の照会に失敗した)ときは、応答は `200` / `status: FAILED` で、`subStatus` は `CONNECTIVITY_ERROR` です。署名も送信もしていないので資産は動いていません。シークレットの問題ではないので交換は不要です。`FAILED` は終端で同じ `externalTxId` は再利用できないため、時間をおいて新しい `externalTxId` で作り直してください。 取引が作られた後に UPBOND 内部の障害で `500` / `5000` が返ることは、それ以外にごくまれにあります。その場合は同じ `Idempotency-Key` で再送してください。新しい署名は行わず、その取引の `id` と現在の `status` を返します。`SUBMITTED` や `PENDING_SIGNATURE` のまま数分以上変わらない取引は UPBOND に連絡してください。新しい `externalTxId` で作り直さないでください(同じ送金が 2 回成立するおそれがあります)。 ::: #### 重複防止 二重送金を防ぐ仕組みは 2 段階です。 | 仕組み | どこに | 効き方 | 期間 | |---|---|---|---| | `Idempotency-Key` | リクエストヘッダー | 同じキーの再送には最初と同じ応答を返します。同じキーで本文が異なれば `409` / `1202`、最初の処理がまだ進行中なら `409` / `1203` | 24 時間 | | `externalTxId` | リクエスト本文 | 同じ Vault で同じ値の 2 件目は `409` / `1201` | 永続 | 推奨は「貴社の ID を `externalTxId` に載せ、`Idempotency-Key` にも同じ値を使う」です。応答を受け取れなかった場合は同じ内容で再送し、`409` / `1201` なら `GET /v1/transactions/external_tx_id/{externalTxId}` で状態を取得してください。 冪等の比較は `signer` を除いた本文で行います。取引が作られる前の `4xx` / `5xx` はキーに記録されないため、原因を直して同じキーで再送できます。取引が作られた後は、同じキーでの再送に対して作成済みの取引の `id` と現在の `status` を返します(応答が失われた場合も同じです)。 ### 取引の取得 - `GET /v1/transactions/{txId}` — UPBOND の取引 ID で取得 - `GET /v1/transactions/external_tx_id/{externalTxId}` — 貴社の ID で取得 どちらも同じ形式を返します。 ```json { "id": "3f9c2b7e-8d0a-4c1e-9b5d-2a6f7e1c4d80", "externalTxId": "refund-2026-000123", "status": "COMPLETED", "subStatus": "CONFIRMED", "operation": "TRANSFER", "assetId": "JPYC_AVALANCHE", "source": { "type": "VAULT_ACCOUNT", "id": "{vaultAccountId}", "name": "Refund vault" }, "destination": { "type": "ONE_TIME_ADDRESS" }, "destinationAddress": "0x1111111111111111111111111111111111111111", "amountInfo": { "amount": "12345.00", "requestedAmount": "12345.00", "netAmount": "12345.00" }, "feeInfo": { "networkFee": "0.000123" }, "feeLevel": "MEDIUM", "txHash": "0x9d2c…e41a", "numOfConfirmations": 12, "blockInfo": { "blockHeight": "71234567", "blockHash": "0x4b…c9" }, "createdAt": 1762470000000, "lastUpdated": 1762470185000, "createdBy": "{apiKeyId}", "signedBy": ["api-factor"], "note": "Refund #000123" } ``` | 項目 | 説明 | |---|---| | `status` / `subStatus` | [状態遷移](#状態遷移)。`subStatus` は理由があるときだけ付きます | | `txHash` | `BROADCASTING` 以降で付きます | | `feeInfo.networkFee` | 実際に支払ったネイティブトークン(AVAX)の量。レシート取得後に付きます | | `numOfConfirmations` / `blockInfo` | レシート取得後に更新されます | | `createdBy` | 取引を作った API キー ID | | `signedBy` | 署名が完了して `BROADCASTING` 以降になると `["api-factor"]`。それより前(`BLOCKED`、署名前の `FAILED`)は `[]` | | `rejectedBy` | 承認モードで却下されたときだけ付きます | `BROADCASTING` / `CONFIRMING` の取引を個別に取得すると、5 秒に 1 回を上限にチェーンの最新状態を反映します。一覧はその場では更新せず、UPBOND の定期処理が更新した内容を返します。 ### 取引一覧 — `GET /v1/transactions` | クエリ | 説明 | |---|---| | `after` / `before` | 作成時刻の範囲(エポックミリ秒)。`after` は以上、`before` は未満 | | `status` | カンマ区切りの状態フィルター(例 `BROADCASTING,CONFIRMING`) | | `orderBy` / `sort` | `createdAt`(既定)または `lastUpdated`、`ASC`(既定)または `DESC` | | `limit` | 1〜500、既定 200 | | `cursor` | 次ページの位置。`next-page` ヘッダーの URL に含まれる値をそのまま使います | 応答は取引オブジェクトの配列です。続きがある場合は応答ヘッダー `next-page` に次ページの URL を返します。最終ページでは付きません。`next-page` の URL には `cursor` が含まれているので、その URL をそのまま呼んでください。 ### ポーリングの指針 - 間隔は 30 秒以上にしてください。 - 一覧は「前回取得した最古の未完了取引の `createdAt` − 10 分」を `after` にして取得し、重複期間を必ず持たせます。作成時刻だけで前進させないでください。 - 未完了の取引は `GET /v1/transactions/{txId}` で個別に再照会します。一覧の取りこぼしを個別照会で補う二重化を推奨します。 - `txHash` は `BROADCASTING` 以降で確定しますが、完了判定は `COMPLETED` だけで行ってください。 ### 状態遷移 ```mermaid stateDiagram-v2 direction LR [*] --> SUBMITTED SUBMITTED --> PENDING_SIGNATURE : 自動署名モード(上限内) SUBMITTED --> BLOCKED : 上限超過、許可リスト外の宛先、受付後に上限が取り消された SUBMITTED --> PENDING_AUTHORIZATION : 承認モード、または上限超過を承認待ちに回す設定 PENDING_SIGNATURE --> BROADCASTING : 署名完了、送信 PENDING_SIGNATURE --> FAILED : チェーン照会失敗、残高不足、署名失敗、同意切れ、署名直前に上限が変わった BROADCASTING --> CONFIRMING : レシート取得 BROADCASTING --> COMPLETED : レシート取得と同時に所定の確認数 BROADCASTING --> FAILED : revert、別の取引に nonce を使われて成立しなくなった CONFIRMING --> COMPLETED : 所定の確認数 CONFIRMING --> FAILED : revert ``` | status | 意味 | 貴社側の扱い | |---|---|---| | `SUBMITTED` | 受付済み。検査中 | 進行中 | | `PENDING_AUTHORIZATION` | 承認待ち(承認モードの API キー、または上限超過を承認待ちに回す設定のとき)。承認して進める機能は未提供のため、この状態の取引は進みません | 進行中。UPBOND に連絡 | | `PENDING_SIGNATURE` | 署名中 | 進行中 | | `BROADCASTING` | 署名済み。`txHash` が付き、送信中 | 進行中。`txHash` を保存してよいが完了扱いにしない | | `CONFIRMING` | ブロックに取り込まれ、確認数を待っている | 進行中 | | `COMPLETED` | 所定の確認数に達し、転送結果が期待どおり | **業務上の完了** | | `BLOCKED` | 上限(1 件・日次累計)または宛先許可リストの検査で拒否。受付後に所有者が上限を取り消した・変えた場合も含む | 終端。金額や宛先を見直して新しい `externalTxId` で再作成(日次累計上限は日本時間 0:00 に戻ります) | | `REJECTED` | 承認者が却下(承認モード向けの予約値。現在は発生しません) | 終端 | | `CANCELLED` | 取消(承認モード向けの予約値。現在は発生しません) | 終端 | | `FAILED` | 送信前または送信後の失敗。理由は `subStatus` | 終端。`subStatus` を見て再作成を判断 | 終端状態は `COMPLETED` / `BLOCKED` / `REJECTED` / `CANCELLED` / `FAILED` の 5 つで、終端に達した取引は変化しません。列挙値は Fireblocks 形式の 17 種を予約しています。現在発生するのは `SUBMITTED` / `PENDING_AUTHORIZATION` / `PENDING_SIGNATURE` / `BROADCASTING` / `CONFIRMING` / `COMPLETED` / `BLOCKED` / `FAILED` の 8 種で、`REJECTED` と `CANCELLED` は承認モード向けの予約値です。未知の値は「進行中」として扱ってください。 #### `BROADCASTING` が長く続くとき :::caution 作り直さないでください 手数料の高騰などでブロックに取り込まれない間、取引は `BROADCASTING` のままです。署名済みのトランザクションは、時間が経っても nonce が使われるまで有効で、手数料が下がれば後から成立します。そのため UPBOND は、成立しないことをチェーン上で確認できるまで `FAILED` にしません。 `BROADCASTING` の取引を新しい `externalTxId` で作り直さないでください。元の送金と作り直した送金の両方が成立するおそれがあります。同じ Vault の後続の送金も、先の取引が取り込まれるまで待たされることがあります。30 分以上 `BROADCASTING` のまま変わらない場合は、`id` と `txHash` を添えて UPBOND に連絡してください。 ::: #### subStatus | subStatus | 付く status | 意味 | |---|---|---| | `CONFIRMED` | `COMPLETED` | 所定の確認数に到達 | | `BLOCKED_BY_POLICY` | `BLOCKED` / `FAILED` | `BLOCKED`: 1 件上限または日次累計上限の超過、宛先許可リスト外の宛先、または受付後に所有者が上限を取り消した・シークレットを外した。`FAILED`: 判定後・署名直前に所有者が上限を新しい版に置き換えた、または取り消した。いずれも署名は行われず、終端([受付後に所有者が上限を変えたとき](./policy.md#受付後に所有者が上限を変えたとき)) | | `INSUFFICIENT_FUNDS` | `FAILED` | Vault のトークン残高が送金額に足りない | | `INSUFFICIENT_FUNDS_FOR_FEE` | `FAILED` | ガス代用のネイティブトークン(AVAX)が足りない | | `REJECTED_BY_BLOCKCHAIN` | `FAILED` | 署名前のチェーン照会(残高・nonce・ガス見積もり)の失敗、チェーン上で revert、またはレシートは成功でも期待した転送イベントが無い | | `DROPPED_BY_BLOCKCHAIN` | `FAILED` | 送信した取引が成立しないことが確定した。送信から 30 分以上レシートが無く、かつ同じ Vault の別の取引がその nonce を使って所定の確認数に達している。後から着金することはない | | `SIGNING_FAILED` | `FAILED` | 署名の失敗(シークレットの失効など)。署名前のエンジン側の一時的な障害は 1 回だけ自動で再試行したうえで、それでも失敗したときにこの状態になります。時間をおいて新しい `externalTxId` で作り直してください | | `OWNER_REAUTH_REQUIRED` | `FAILED` | 署名中に Vault 所有者の同意が切れた([Vault の接続と維持](./vault.md)) | | `CONNECTIVITY_ERROR` | `FAILED` | 署名の前にチェーンの照会(残高・nonce)に失敗した。署名も送信もしていない。時間をおいて新しい `externalTxId` で作り直す | | `REJECTED_BY_USER` | `REJECTED` | 承認者が却下(承認モード向けの予約値。現在は発生しません) | | `TIMEOUT` | `FAILED` | 承認期限切れ(承認モード向けの予約値。現在は発生しません) | `COMPLETED` になる確認数は環境ごとに決まっており、接続情報に記載します。 --- ## Vault の接続と維持 **Vault** は貴社の法人ウォレットです。API では `source.id` に載せる Vault アカウント ID で指し、1 つの API キーは 1 つの Vault に紐づきます。 署名には、シークレット([シークレットと封筒](./signing-secret.md))に加えて、**Vault 所有者の認証**が必要です。所有者は UPBOND の認証基盤にログインして「この Vault の署名に自分の認証を使ってよい」と同意します。これを**接続**と呼びます。 ### 接続の手順 1. UPBOND が所有者に接続用の URL を送ります。 2. 所有者はブラウザでその URL を開き、ログインして同意します。 3. 認証基盤が UPBOND の署名サービスに戻り、同意が保存されます。所有者の端末やブラウザにトークンは残りません。 :::caution ウォレットを作ったときと同じログイン方法で 認証基盤はログイン方法(Google、メールの確認コードなど)ごとに別のアカウントとして扱います。同じメールアドレスでも、別のログイン方法でログインすると別のウォレットになります。接続先のウォレットアドレスが Vault と一致しない場合、UPBOND は接続を拒否し、その同意をその場で無効にします。 ::: 保存された同意は UPBOND の署名サービス自身のクライアント鍵に束縛されています。保存値だけが漏えいしても、単体では認証に使えません。 ### 期限 | 期限 | 長さ | 意味 | |---|---|---| | 同意の絶対期限 | 接続から **90 日** | ここで必ず切れます。延長はできず、所有者が再接続します | | 利用の期限 | 最終利用から 14 日 | UPBOND が毎日自動で更新するため、貴社が意識する必要はありません | UPBOND は絶対期限の前に、所有者へ再接続を案内します。再接続は初回と同じ手順で、送金を止めずに行えます。 ### 期限切れのときの API の挙動 | 状況 | 応答 | |---|---| | 同意が切れた後に `POST /v1/transactions` を呼んだ | `422` / `1303` `vault reconnect required`。取引は作られず、`externalTxId` も消費されません | | 署名の途中で同意が切れた | 取引は `FAILED`、`subStatus` は `OWNER_REAUTH_REQUIRED` | | Vault が未接続、または UPBOND が終了した | `422` / `1302` `vault is not ready` | `1303` と `OWNER_REAUTH_REQUIRED` は、シークレットの問題(`1412` / `SIGNING_FAILED`)とは別です。シークレットを交換しても直りません。所有者に再接続を依頼してください。 ### 貴社側の実装指針 - `422` / `1303` を受けたら、その送金を再送し続けるのではなく、担当者に通知して所有者の再接続を待ってください。再接続後は同じリクエストをそのまま送れます(`4xx` は `Idempotency-Key` に記録されません)。 - `FAILED` / `OWNER_REAUTH_REQUIRED` の取引は終端です。再接続後に新しい `externalTxId` で作り直してください。同じ `externalTxId` は再利用できません。 --- ## Class: AuthError An [UpbondError](UpbondError.md) specialization for auth-leg failures. Adds the HTTP [AuthError.status](#status) of the failing endpoint (when there was a response), which [isDefinitiveAuthError](../functions/isDefinitiveAuthError.md) uses to tell permanent rejections from transient ones. `code` is narrowed to [AuthErrorCode](../type-aliases/AuthErrorCode.md). ### Remarks Most integrations should use [createUpbond](../functions/createUpbond.md) instead. ### Extends - [`UpbondError`](UpbondError.md) ### Constructors #### Constructor > **new AuthError**(`code`, `message`, `options?`): `AuthError` ##### Parameters ###### code [`AuthErrorCode`](../type-aliases/AuthErrorCode.md) ###### message `string` ###### options? ###### status? `number` ##### Returns `AuthError` ##### Overrides [`UpbondError`](UpbondError.md).[`constructor`](UpbondError.md#constructor) ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from [`UpbondError`](UpbondError.md).[`cause`](UpbondError.md#cause) *** #### code > `readonly` **code**: [`AuthErrorCode`](../type-aliases/AuthErrorCode.md) Stable machine-readable classification of the failure. ##### Overrides [`UpbondError`](UpbondError.md).[`code`](UpbondError.md#code) *** #### message > **message**: `string` ##### Inherited from [`UpbondError`](UpbondError.md).[`message`](UpbondError.md#message) *** #### name > **name**: `string` ##### Inherited from [`UpbondError`](UpbondError.md).[`name`](UpbondError.md#name) *** #### stack? > `optional` **stack?**: `string` ##### Inherited from [`UpbondError`](UpbondError.md).[`stack`](UpbondError.md#stack) *** #### status > `readonly` **status**: `number` \| `undefined` HTTP status of the failing endpoint response, when one was received. *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from [`UpbondError`](UpbondError.md).[`stackTraceLimit`](UpbondError.md#stacktracelimit) ### Methods #### captureStackTrace() ##### Call Signature > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ###### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ###### Returns `void` ###### Inherited from [`UpbondError`](UpbondError.md).[`captureStackTrace`](UpbondError.md#capturestacktrace) ##### Call Signature > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Create .stack property on a target object ###### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ###### Returns `void` ###### Inherited from [`UpbondError`](UpbondError.md).[`captureStackTrace`](UpbondError.md#capturestacktrace) *** #### prepareStackTrace()? > `static` `optional` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from [`UpbondError`](UpbondError.md).[`prepareStackTrace`](UpbondError.md#preparestacktrace) --- ## Class: Eip1193Error An EIP-1193 provider error carrying the standard numeric `code` (e.g. 4001 user-rejected, 4100 unauthorized, -32602 invalid params, 4900 disconnected). Thrown by [WidgetProvider.request](WidgetProvider.md#request) when the widget returns an `rpc:error`, times out, or is destroyed. ### Extends - `Error` ### Constructors #### Constructor > **new Eip1193Error**(`code`, `message`, `data?`): `Eip1193Error` ##### Parameters ###### code `number` Standard EIP-1193 / JSON-RPC error code. ###### message `string` ###### data? `unknown` Optional provider-supplied error data. ##### Returns `Eip1193Error` ##### Overrides `Error.constructor` ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from `Error.cause` *** #### code > `readonly` **code**: `number` Standard EIP-1193 / JSON-RPC error code. *** #### data? > `readonly` `optional` **data?**: `unknown` Optional provider-supplied error data. *** #### message > **message**: `string` ##### Inherited from `Error.message` *** #### name > **name**: `string` ##### Inherited from `Error.name` *** #### stack? > `optional` **stack?**: `string` ##### Inherited from `Error.stack` *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from `Error.stackTraceLimit` ### Methods #### captureStackTrace() ##### Call Signature > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ###### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ###### Returns `void` ###### Inherited from `Error.captureStackTrace` ##### Call Signature > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Create .stack property on a target object ###### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ###### Returns `void` ###### Inherited from `Error.captureStackTrace` *** #### prepareStackTrace()? > `static` `optional` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from `Error.prepareStackTrace` --- ## Class: UpbondError The single error type thrown across the `@upbond/sdk` public surface. Implementation errors from the OIDC and wallet-core layers are translated into this taxonomy at the adapter boundary, so consumers never import or catch internal classes. ### Remarks Branch on [UpbondError.code](#code) (a [UpbondErrorCode](../type-aliases/UpbondErrorCode.md)); the originating error, when there is one, is preserved on the standard `cause`. ### Extends - `Error` ### Extended by - [`AuthError`](AuthError.md) ### Constructors #### Constructor > **new UpbondError**(`code`, `message`, `options?`): `UpbondError` ##### Parameters ###### code [`UpbondErrorCode`](../type-aliases/UpbondErrorCode.md) Stable machine-readable classification of the failure. ###### message `string` ###### options? ###### cause? `unknown` ##### Returns `UpbondError` ##### Overrides `Error.constructor` ### Properties #### cause? > `optional` **cause?**: `unknown` ##### Inherited from `Error.cause` *** #### code > `readonly` **code**: [`UpbondErrorCode`](../type-aliases/UpbondErrorCode.md) Stable machine-readable classification of the failure. *** #### message > **message**: `string` ##### Inherited from `Error.message` *** #### name > **name**: `string` ##### Inherited from `Error.name` *** #### stack? > `optional` **stack?**: `string` ##### Inherited from `Error.stack` *** #### stackTraceLimit > `static` **stackTraceLimit**: `number` The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. ##### Inherited from `Error.stackTraceLimit` ### Methods #### captureStackTrace() ##### Call Signature > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()` was called. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` The first line of the trace will be prefixed with `${myObject.name}: ${myObject.message}`. The optional `constructorOpt` argument accepts a function. If given, all frames above `constructorOpt`, including `constructorOpt`, will be omitted from the generated stack trace. The `constructorOpt` argument is useful for hiding implementation details of error generation from the user. For instance: ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` ###### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ###### Returns `void` ###### Inherited from `Error.captureStackTrace` ##### Call Signature > `static` **captureStackTrace**(`targetObject`, `constructorOpt?`): `void` Create .stack property on a target object ###### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ###### Returns `void` ###### Inherited from `Error.captureStackTrace` *** #### prepareStackTrace()? > `static` `optional` **prepareStackTrace**(`err`, `stackTraces`): `any` ##### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ##### Returns `any` ##### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ##### Inherited from `Error.prepareStackTrace` --- ## Class: WidgetProvider The EIP-1193 provider the RP receives from `UpbondClient.getEthereumProvider()` (embedded mode). It bridges standard `request()` calls to the wallet-origin widget over a `MessagePort` and emits the standard `connect`/`disconnect`/`accountsChanged`/`chainChanged` events; ethers/viem plug into it directly. Keys, tokens, and the signing ceremony stay inside the widget — this object only ever sees addresses, chain id, and signatures. Obtain instances via the SDK facade rather than constructing one. ### Constructors #### Constructor > **new WidgetProvider**(`frame`, `opts?`): `WidgetProvider` ##### Parameters ###### frame `WidgetFrame` ###### opts? ###### requestTimeoutMs? `number` ##### Returns `WidgetProvider` ### Accessors #### accounts ##### Get Signature > **get** **accounts**(): `string`[] The currently connected accounts, from the last widget state snapshot. ###### Returns `string`[] *** #### chainId ##### Get Signature > **get** **chainId**(): `` `0x${string}` `` The active chain id as a `0x`-prefixed hex string. Moved by `wallet_switchEthereumChain` and by the in-widget network picker; both emit `chainChanged` (docs/24 D22). ###### Returns `` `0x${string}` `` *** #### connected ##### Get Signature > **get** **connected**(): `boolean` Whether the widget currently reports a connected wallet. ###### Returns `boolean` ### Methods #### closeWallet() > **closeWallet**(): `void` Hide the wallet overlay. ##### Returns `void` *** #### destroy() > **destroy**(): `void` Rejects every in-flight request and detaches from the port. Called by EmbeddedWallet.destroy() — a torn-down widget must not leave callers awaiting forever. ##### Returns `void` *** #### on() > **on**(`event`, `listener`): `this` Subscribe to a provider event (EIP-1193 `on`); returns `this` for chaining. ##### Parameters ###### event [`ProviderEvent`](../type-aliases/ProviderEvent.md) ###### listener (`payload`) => `void` ##### Returns `this` *** #### openWallet() > **openWallet**(`view?`, `options?`): `void` RP-initiated overlay open (e.g. a "wallet" button): shows the frame and tells the widget which view to render. ##### Parameters ###### view? [`WalletView`](../type-aliases/WalletView.md) = `'home'` ###### options? [`WalletViewOptions`](../interfaces/WalletViewOptions.md) ##### Returns `void` *** #### removeListener() > **removeListener**(`event`, `listener`): `this` Unsubscribe a listener previously added with [WidgetProvider.on](#on). ##### Parameters ###### event [`ProviderEvent`](../type-aliases/ProviderEvent.md) ###### listener (`payload`) => `void` ##### Returns `this` *** #### request() > **request**\<`T`\>(`args`, `opts?`): `Promise`\<`T`\> Issue an EIP-1193 JSON-RPC request to the wallet. Signing methods surface a confirm + fresh-biometric ceremony inside the widget before resolving. ##### Type Parameters ###### T `T` = `unknown` ##### Parameters ###### args [`Eip1193RequestArguments`](../interfaces/Eip1193RequestArguments.md) The method and optional params. ###### opts? `timeoutMs` overrides the provider-wide request timeout for this one call (e.g. the SDK's logout uses a short bound so an unresponsive widget cannot stall the issuer sign-out). ###### timeoutMs? `number` ##### Returns `Promise`\<`T`\> The RPC result. ##### Throws [Eip1193Error](Eip1193Error.md) on an RPC error, a request timeout (widget unresponsive), or a destroyed provider. --- ## Function: addressesFromPublicKey() > **addressesFromPublicKey**(`pub`): [`DerivedAddresses`](../interfaces/DerivedAddresses.md) Both wallet addresses from one public key — offline, no signing, no network. Pure helper: given any secp256k1 public key (e.g. a `wallet_public_key` claim, if a flow supplies one) it returns the corresponding receive addresses. The issuer does NOT pre-derive the key before the first ceremony — issuer-side derivation was rejected (docs/34, 2026-08-20). ### Parameters #### pub [`PublicKeyInput`](../type-aliases/PublicKeyInput.md) ### Returns [`DerivedAddresses`](../interfaces/DerivedAddresses.md) --- ## Function: beginAuthorization() > **beginAuthorization**(`config`, `hints?`, `opts?`): `Promise`\<[`PendingAuthorization`](../interfaces/PendingAuthorization.md)\> Build the issuer authorization URL for an authorization-code + PKCE login and the [PendingAuthorization](../interfaces/PendingAuthorization.md) state that must be persisted across the redirect. Generates fresh `state`, `nonce`, and PKCE verifier; only the S256 challenge leaves the client. ### Parameters #### config [`AuthConfig`](../interfaces/AuthConfig.md) Issuer, client, redirect URI, and optional scope. #### hints? [`AuthorizationHints`](../interfaces/AuthorizationHints.md) Optional connection / login-hint to skip the issuer's provider chooser. #### opts? ##### statePrefix? `string` Prepended to the generated `state` (see `POPUP_LOGIN_STATE_PREFIX`). ### Returns `Promise`\<[`PendingAuthorization`](../interfaces/PendingAuthorization.md)\> The pending authorization to store before navigating to `authorizeUrl`. ### Remarks Most integrations should use [createUpbond](createUpbond.md) instead. --- ## Function: buildLogoutUrl() > **buildLogoutUrl**(`config`, `idTokenHint?`, `postLogoutRedirectUri?`): `string` RP-initiated logout URL at the issuer's frozen end_session route. The id_token_hint is optional (RP-initiated logout §2): the issuer session cookie can outlive the RP's local tokens (expired, or a widget-only connection), and logout must still end it. client_id is always sent, so the issuer can validate post_logout_redirect_uri without the hint. ### Parameters #### config [`AuthConfig`](../interfaces/AuthConfig.md) #### idTokenHint? `string` #### postLogoutRedirectUri? `string` ### Returns `string` ### Remarks Most integrations should use [createUpbond](createUpbond.md) instead. --- ## Function: completeAuthorization() > **completeAuthorization**(`config`, `pending`, `callbackUrl`, `fetchFn?`, `nowEpochSeconds?`): `Promise`\<[`TokenSet`](../interfaces/TokenSet.md)\> Complete a login: validate the callback against the stored [PendingAuthorization](../interfaces/PendingAuthorization.md), exchange the code at the token endpoint, and validate the returned id_token's binding claims (issuer, audience, expiry, nonce, subject). ### Parameters #### config [`AuthConfig`](../interfaces/AuthConfig.md) The same config used for [beginAuthorization](beginAuthorization.md). #### pending `Pick`\<[`PendingAuthorization`](../interfaces/PendingAuthorization.md), `"state"` \| `"nonce"` \| `"codeVerifier"`\> The `state`/`nonce`/`codeVerifier` persisted at login start. #### callbackUrl `string` The full redirect URL the issuer returned to. #### fetchFn? \{(`input`, `init?`): `Promise`\<`Response`\>; (`input`, `init?`): `Promise`\<`Response`\>; (`input`, `init?`): `Promise`\<`Response`\>; \} Injectable fetch (defaults to the global). #### nowEpochSeconds? () => `number` Injectable clock in epoch seconds (for tests). ### Returns `Promise`\<[`TokenSet`](../interfaces/TokenSet.md)\> The validated [TokenSet](../interfaces/TokenSet.md). ### Remarks The caller must delete the pending state from storage *before* calling this so a replayed callback can never reuse the verifier (PKCE single-use, docs/24-sdk-design.md D3). Most integrations should use [createUpbond](createUpbond.md) instead. ### Throws [AuthError](../classes/AuthError.md) on issuer error, missing/invalid callback, state mismatch, a failed token request, or id_token validation failure. --- ## Function: createUpbond() > **createUpbond**(`config`): [`UpbondClient`](../interfaces/UpbondClient.md) Create the browser [UpbondClient](../interfaces/UpbondClient.md) — the main entry point of `@upbond/sdk`. Validates `config` once at the boundary and wires the platform-agnostic core to the browser (sessionStorage/localStorage, `window` navigation, and the lazily code-split MPC wallet core). Call it once and reuse the returned client. ### Parameters #### config [`UpbondConfig`](../interfaces/UpbondConfig.md) The RP's `clientId`, plus an optional `environment` (default `'production'`) and field-level overrides. ### Returns [`UpbondClient`](../interfaces/UpbondClient.md) A ready-to-use [UpbondClient](../interfaces/UpbondClient.md). ### Remarks - `init()` must run on every page load to consume a redirect callback or restore a persisted session. - `environment` defaults to `'production'`, so `createUpbond({ clientId })` is a complete integration. The auth leg is always the RP's own OIDC redirect: `login()` sends the user to the issuer under YOUR client and the callback leaves the id_token on your page (docs/24 D20). The default wallet is the embedded widget on the UPBOND wallet origin (D18) — keys, passkeys, ceremonies and recovery stay there; the RP talks EIP-1193. `connect()` REQUIRES that prior `login()` (throws `not_signed_in` otherwise) and consumes the issuer session as silent SSO — the wallet leg never authenticates (D20 A-3). An auth-only RP needs nothing special: it simply never calls a wallet method. - Redirect mode (`wallet.mode: 'redirect'`) runs the MPC ceremony on the RP page instead — the wallet's own origin and internal demos: `connectWallet()` gives a view-only Layer 1 session, `unlockWallet()` establishes the single per-session Layer 2 ceremony (A2), and every signature is re-gated by a fresh biometric. The MPC stack is a lazy code-split chunk (docs/24 D5). - The two mode's wallet methods are mutually exclusive: embedded exposes `connect()` / `getEthereumProvider()` / `openWallet()`; calling the other mode's methods throws `wallet_not_configured`. ### Throws [UpbondError](../classes/UpbondError.md) `config_invalid` if `config` fails boundary validation. ### Example ```ts const upbond = createUpbond({ clientId: 'YOUR_CLIENT_ID', // environment: 'staging', // omit for production }); await upbond.init(); // consume callback / restore session loginBtn.onclick = () => upbond.login(); // OIDC redirect under YOUR client connectBtn.onclick = async () => { // after login: user gesture! await upbond.connect(); // wallet-origin popup, silent SSO const provider = await upbond.getEthereumProvider(); // EIP-1193 (ethers/viem OK) const [address] = await provider.request({ method: 'eth_accounts' }); }; ``` --- ## Function: detectPasskeyCapability() > **detectPasskeyCapability**(): `Promise`\<[`PasskeyCapability`](../type-aliases/PasskeyCapability.md)\> Checks whether this browser can use a passkey on this device, without any prompt or user gesture. It needs no sign-in and no `createUpbond()`, so it can run before `login()`, even on page load. Call it in the browser only: on a server there is no WebAuthn and the answer is `'unavailable'`. - `'unavailable'`: WebAuthn is missing, or the device reports no usable platform authenticator. It cannot tell which: typically no screen lock (passcode, PIN or biometrics) is set up, or an in-app browser blocks it. - `'capable'`: nothing ruled a passkey out. **Creating a wallet can still fail** (the user cancels, no PRF support, the passkey provider refuses). Inconclusive checks, including no answer within 1500 ms, also read `'capable'`. Before sign-in you do not know whether the visitor already owns a wallet, so show guidance rather than disabling your sign-in or wallet buttons. ### Returns `Promise`\<[`PasskeyCapability`](../type-aliases/PasskeyCapability.md)\> ### Example ```ts if ((await detectPasskeyCapability()) === 'unavailable') { showNotice('Set up a screen lock on this device, or open this page in your browser.'); } ``` --- ## Function: evmAddressFromPublicKey() > **evmAddressFromPublicKey**(`pub`): `` `0x${string}` `` EVM address of a secp256k1 key: `keccak256(X ‖ Y)[12:]`, EIP-55 checksummed. ### Parameters #### pub [`PublicKeyInput`](../type-aliases/PublicKeyInput.md) ### Returns `` `0x${string}` `` --- ## Function: isDefinitiveAuthError() > **isDefinitiveAuthError**(`error`): `boolean` A token-endpoint rejection that will not heal by retrying (4xx: revoked or expired grant, bad client). Network failures and 5xx are transient — the session should survive them and retry later. ### Parameters #### error `unknown` ### Returns `boolean` ### Remarks Most integrations should use [createUpbond](createUpbond.md) instead. --- ## Function: refreshGrant() > **refreshGrant**(`config`, `refreshToken`, `fetchFn?`, `nowEpochSeconds?`): `Promise`\<[`TokenSet`](../interfaces/TokenSet.md)\> Exchange a refresh token for a fresh TokenSet (widget host steady state). Public clients send no secret; the rotated refresh_token (when the issuer rotates) replaces the old one in the returned set. ### Parameters #### config [`AuthConfig`](../interfaces/AuthConfig.md) #### refreshToken `string` #### fetchFn? \{(`input`, `init?`): `Promise`\<`Response`\>; (`input`, `init?`): `Promise`\<`Response`\>; (`input`, `init?`): `Promise`\<`Response`\>; \} #### nowEpochSeconds? () => `number` ### Returns `Promise`\<[`TokenSet`](../interfaces/TokenSet.md)\> ### Remarks Most integrations should use [createUpbond](createUpbond.md) instead. --- ## Function: suiAddressFromPublicKey() > **suiAddressFromPublicKey**(`pub`): `` `0x${string}` `` Sui address of a secp256k1 key: `blake2b256(0x01 ‖ compressed pubkey)`. ### Parameters #### pub [`PublicKeyInput`](../type-aliases/PublicKeyInput.md) ### Returns `` `0x${string}` `` --- ## @upbond/sdk ### Getting Started - [createUpbond](functions/createUpbond.md) ### Client - [ApiFactorIssue](interfaces/ApiFactorIssue.md) - [DerivedAddresses](interfaces/DerivedAddresses.md) - [IdTokenClaims](interfaces/IdTokenClaims.md) - [RecoveryStatus](interfaces/RecoveryStatus.md) - [SignRequest](interfaces/SignRequest.md) - [SuiAccount](interfaces/SuiAccount.md) - [TypedDataDomain](interfaces/TypedDataDomain.md) - [TypedDataField](interfaces/TypedDataField.md) - [TypedDataRequest](interfaces/TypedDataRequest.md) - [UpbondClient](interfaces/UpbondClient.md) - [UpbondState](interfaces/UpbondState.md) - [WalletAccountClaim](interfaces/WalletAccountClaim.md) - [WalletFactor](interfaces/WalletFactor.md) - [WalletRef](interfaces/WalletRef.md) - [AuthStatus](type-aliases/AuthStatus.md) - [PasskeyCapability](type-aliases/PasskeyCapability.md) - [ProgressPhase](type-aliases/ProgressPhase.md) - [PublicKeyInput](type-aliases/PublicKeyInput.md) - [RecoveryEnrollment](type-aliases/RecoveryEnrollment.md) - [WalletKind](type-aliases/WalletKind.md) - [WalletStatus](type-aliases/WalletStatus.md) - [addressesFromPublicKey](functions/addressesFromPublicKey.md) - [detectPasskeyCapability](functions/detectPasskeyCapability.md) ### Configuration - [UpbondConfig](interfaces/UpbondConfig.md) - [UpbondWalletConfig](interfaces/UpbondWalletConfig.md) - [UpbondWalletRecoveryConfig](interfaces/UpbondWalletRecoveryConfig.md) - [UpbondEnvironment](type-aliases/UpbondEnvironment.md) - [~~WalletEnvironment~~](type-aliases/WalletEnvironment.md) ### Errors - [UpbondError](classes/UpbondError.md) - [UpbondErrorCode](type-aliases/UpbondErrorCode.md) ### Embedded Wallet (EIP-1193) - [Eip1193Error](classes/Eip1193Error.md) - [WidgetProvider](classes/WidgetProvider.md) - [Eip1193RequestArguments](interfaces/Eip1193RequestArguments.md) - [WalletViewOptions](interfaces/WalletViewOptions.md) - [ProviderEvent](type-aliases/ProviderEvent.md) - [WalletView](type-aliases/WalletView.md) ### Advanced: Low-level OIDC - [AuthError](classes/AuthError.md) - [AuthConfig](interfaces/AuthConfig.md) - [AuthorizationHints](interfaces/AuthorizationHints.md) - [PendingAuthorization](interfaces/PendingAuthorization.md) - [TokenSet](interfaces/TokenSet.md) - [AuthErrorCode](type-aliases/AuthErrorCode.md) - [beginAuthorization](functions/beginAuthorization.md) - [buildLogoutUrl](functions/buildLogoutUrl.md) - [completeAuthorization](functions/completeAuthorization.md) - [isDefinitiveAuthError](functions/isDefinitiveAuthError.md) - [refreshGrant](functions/refreshGrant.md) ### External Wallets - [ConnectExternalOptions](interfaces/ConnectExternalOptions.md) - [Eip1193Provider](interfaces/Eip1193Provider.md) - [ExternalWalletInfo](interfaces/ExternalWalletInfo.md) - [ExternalWalletSession](interfaces/ExternalWalletSession.md) - [ExternalConnector](type-aliases/ExternalConnector.md) - [DEFAULT\_WALLETCONNECT\_CHAINS](variables/DEFAULT_WALLETCONNECT_CHAINS.md) ### Other - [SignatureVerificationOptions](interfaces/SignatureVerificationOptions.md) - [evmAddressFromPublicKey](functions/evmAddressFromPublicKey.md) - [suiAddressFromPublicKey](functions/suiAddressFromPublicKey.md) --- ## Interface: ApiFactorIssue The result of `issueApiFactor`: the new factor's public key (its revoke handle) and, EXACTLY ONCE, the factor key itself. The secret is the raw 32-byte secp256k1 scalar in standard base64 (44 chars). No UPBOND component persists it — the caller shows it to the owner, who stores it in their own secret manager; a lost secret is replaced by issuing a new factor and revoking this one. ### Properties #### factorPubHex > **factorPubHex**: `string` *** #### label > **label**: `string` *** #### secret > **secret**: `string` --- ## Interface: AuthConfig Minimal OIDC client configuration for the low-level auth primitives. ### Remarks Most integrations should use [createUpbond](../functions/createUpbond.md) instead. ### Properties #### clientId > **clientId**: `string` OIDC `client_id` registered at the issuer. *** #### issuer > **issuer**: `string` Issuer origin, e.g. `https://id.upbond.io`. *** #### redirectUri > **redirectUri**: `string` Registered redirect URI back into the RP. *** #### scope? > `optional` **scope?**: `string` Defaults to `openid profile email`. --- ## Interface: AuthorizationHints Hints forwarded to the issuer so it can skip its provider chooser. ### Remarks Most integrations should use [createUpbond](../functions/createUpbond.md) instead. ### Properties #### connection? > `optional` **connection?**: `string` Connection name (Auth0 semantics): 'google', 'line', 'email', 'sms', ... *** #### loginHint? > `optional` **loginHint?**: `string` Pre-filled identifier (email address, phone number). --- ## Interface: ConnectExternalOptions Options for `UpbondClient.connectExternal()`. ### Properties #### chains? > `optional` **chains?**: `number`[] WalletConnect only: extra numeric chain ids to offer the wallet, on top of [DEFAULT\_WALLETCONNECT\_CHAINS](../variables/DEFAULT_WALLETCONNECT_CHAINS.md) (always offered). All chains are optional: the wallet approves the ones it supports, and the session starts on the wallet's current chain — move it with `wallet_switchEthereumChain` on the session's provider. *** #### connector > **connector**: [`ExternalConnector`](../type-aliases/ExternalConnector.md) `'injected'` for an EIP-6963 browser-extension wallet; `'walletconnect'` for WalletConnect v2 (QR / deep link). *** #### rdns? > `optional` **rdns?**: `string` Injected only: the EIP-6963 rdns of the wallet to use. Defaults to `'io.metamask'`. *** #### rpcMap? > `optional` **rpcMap?**: `Record`\<`number`, `string`\> WalletConnect only: JSON-RPC URL per chain id for read calls; chains left out use WalletConnect's public RPC. URLs stay for the client's lifetime — a later connect can replace a chain's URL but not remove it. --- ## Interface: DerivedAddresses Both addresses derived from one secp256k1 public key. ### Properties #### evm > **evm**: `` `0x${string}` `` EIP-55 checksummed 20-byte EVM address. *** #### sui > **sui**: `` `0x${string}` `` 32-byte Sui address (secp256k1 scheme) as 0x-prefixed hex. --- ## Interface: Eip1193Provider The minimal EIP-1193 provider surface `@upbond/sdk` guarantees on an external-wallet session: `request()` plus the standard event methods (`accountsChanged` / `chainChanged` / `disconnect`). The embedded `WidgetProvider` satisfies it too, so an RP can type a "current provider" slot with this one interface. ethers/viem plug in directly. ### Methods #### on() > **on**(`event`, `listener`): `unknown` ##### Parameters ###### event `string` ###### listener (`payload`) => `void` ##### Returns `unknown` *** #### removeListener() > **removeListener**(`event`, `listener`): `unknown` ##### Parameters ###### event `string` ###### listener (`payload`) => `void` ##### Returns `unknown` *** #### request() > **request**\<`T`\>(`args`): `Promise`\<`T`\> ##### Type Parameters ###### T `T` = `unknown` ##### Parameters ###### args ###### method `string` ###### params? `Record`\<`string`, `unknown`\> \| `unknown`[] ##### Returns `Promise`\<`T`\> --- ## Interface: Eip1193RequestArguments Arguments for an EIP-1193 `request()` call. ### Properties #### method > **method**: `string` JSON-RPC method name, e.g. `eth_accounts`, `eth_sendTransaction`. *** #### params? > `optional` **params?**: `unknown`[] Positional JSON-RPC parameters; defaults to an empty array. --- ## Interface: ExternalWalletInfo An injected wallet's EIP-6963 announcement metadata. Announced means installed and responding — there is no separate "installed" flag. ### Properties #### icon > **icon**: `string` The wallet's icon, always a `data:image/…` URI: EIP-6963 requires a data URI, and the store drops announcements with any other icon shape — so consumers can bind it to an `img.src` without re-validating. *** #### name > **name**: `string` Human-readable wallet name, e.g. `'MetaMask'`. *** #### rdns > **rdns**: `string` Reverse-DNS wallet id from the announcement, e.g. `'io.metamask'`. --- ## Interface: ExternalWalletSession A connected external-wallet session. Self-contained: the UPBOND auth session and embedded/redirect wallet are unaffected, and dropping every reference (after `disconnect()`) is a complete teardown. ### Properties #### accounts > **accounts**: `string`[] Accounts the user approved at connect time. *** #### chainId > **chainId**: `` `0x${string}` `` \| `null` The wallet's active chain as `0x`-hex, or `null` if it could not be read. *** #### connector > **connector**: [`ExternalConnector`](../type-aliases/ExternalConnector.md) *** #### provider > **provider**: [`Eip1193Provider`](Eip1193Provider.md) The wallet's live EIP-1193 provider — emits the standard `accountsChanged` / `chainChanged` / `disconnect` events. *** #### wallet > **wallet**: [`ExternalWalletInfo`](ExternalWalletInfo.md) \| `null` EIP-6963 metadata of the connected wallet; `null` for WalletConnect. ### Methods #### disconnect() > **disconnect**(): `Promise`\<`void`\> End the session: WalletConnect disconnects the relay pairing; injected wallets get a best-effort EIP-2255 permission revocation. A client holds one WalletConnect session at a time — a new walletconnect connect ends the previous one, after which its `disconnect()` does nothing. ##### Returns `Promise`\<`void`\> --- ## Interface: IdTokenClaims Decoded id_token claims. `sub` is the stable user identifier (and the Web3Auth `verifierId`); the optional profile claims depend on the granted scope. `wallet_address` is present once the address has been bound to the account. Unlisted claims are exposed via the index signature. ### Indexable > \[`claim`: `string`\]: `unknown` ### Properties #### email? > `optional` **email?**: `string` *** #### name? > `optional` **name?**: `string` *** #### picture? > `optional` **picture?**: `string` *** #### sub > **sub**: `string` OIDC subject — the stable per-user identifier. *** #### wallet\_accounts? > `optional` **wallet\_accounts?**: [`WalletAccountClaim`](WalletAccountClaim.md)[] All wallets of the user, default entry included (multi-wallet foundation, docs/28; requires the `wallet` scope). *** #### wallet\_address? > `optional` **wallet\_address?**: `string` The user's bound wallet address, once set (requires the `wallet` scope). *** #### wallet\_public\_key? > `optional` **wallet\_public\_key?**: `string` Reserved: the wallet's secp256k1 public key (compressed SEC1 hex; requires the `wallet` scope). No issuer flow populates this claim today — issuer-side pre-derivation was rejected (docs/34, 2026-08-20): the final TSS key includes ceremony-time client randomness, so it cannot be known before the first ceremony. If a future flow supplies it, both chain addresses derive from it offline: see `addressesFromPublicKey` / `UpbondState.derivedAddresses`. --- ## Interface: PendingAuthorization PKCE authorization state that must survive the redirect round-trip. The caller persists it before navigating to the issuer and reloads it when the callback returns. It is single-use: delete it from storage *before* the code exchange so a replayed callback can never reuse the `codeVerifier` (docs/24-sdk-design.md D3). ### Remarks Most integrations should use [createUpbond](../functions/createUpbond.md) instead. ### Properties #### authorizeUrl > **authorizeUrl**: `string` Fully-formed issuer authorization URL to navigate to. *** #### codeVerifier > **codeVerifier**: `string` PKCE verifier; its S256 challenge went to the issuer, the verifier stays local. *** #### nonce > **nonce**: `string` Replay-defense nonce bound into and verified on the id_token. *** #### state > **state**: `string` Opaque CSRF value echoed back and checked against the callback. --- ## Interface: RecoveryStatus Read-only view of the account's recovery setup (WO 2026/003995). `enrollment` is decided ONLY by querying the recovery-service blob store and the recoverian binding — never by local/optimistic client state (issue #165). `contact` is the recoverian's OTP delivery binding. The contact is pre-masked by the recoverian — this surface never carries the plain address, so Layer 1 may read it. ### Properties #### contact > **contact**: \{ `channel`: `"email"` \| `"sms"`; `current`: `boolean`; `masked`: `string`; \} \| `null` Where the recoverian sends its OTP, masked server-side; null when no contact is bound (or recovery is not configured at all). `current` is true when the bound contact matches the current token's claims; false means a stale binding the user should update while they still control the old contact (rebinding requires an OTP sent there). *** #### enrolled > **enrolled**: `boolean` `enrollment === 'enrolled'` — kept for consumers of the boolean shape. False for `'partial'`/`'unknown'` (fail-closed: never claim a recovery path that is unverified or incomplete). *** #### enrollment > **enrollment**: [`RecoveryEnrollment`](../type-aliases/RecoveryEnrollment.md) Server-verified enrollment state. --- ## Interface: SignRequest A chain-agnostic signing request handed to the wallet's transaction signer. ### Properties #### chainId > **chainId**: `number` *** #### payload > **payload**: `` `0x${string}` `` RLP/typed-data payload as an opaque hex string. --- ## Interface: SignatureVerificationOptions How a signature's user verification is gated (docs/23 決定2). `'session'` (default): the cadence decides — a live L1 window covers it. `'fresh'`: a NEW user verification for this very signature, whatever the cadence and whatever window is live — the only hold it may consume is an establishment unlock armed for this exact intent (#241). For statements that change who may sign (the transfer mandate, docs/37): the Layer 2 requirement of constitution §4 注記, not merely its frequency. ### Properties #### verification? > `optional` **verification?**: `"session"` \| `"fresh"` --- ## Interface: SuiAccount The wallet's Sui-on-secp256k1 account, derived from the SAME MPC key as the EVM address: `address = blake2b256(0x01 ‖ compressed pubkey)`. Known only after a Layer 2 ceremony (like `walletAddress` on first setup) and NOT bound to the issuer — the `wallet_address` claim stays Ethereum-shaped and RPs persist the Sui address on their side (issue #205 判断3). ### Properties #### address > **address**: `` `0x${string}` `` 32-byte Sui address as 0x-prefixed hex (66 chars). *** #### publicKey > **publicKey**: `string` Base64 of the 33-byte compressed secp256k1 public key. --- ## Interface: TokenSet The tokens and decoded claims produced by a successful auth exchange. ### Remarks Most integrations should use [createUpbond](../functions/createUpbond.md) instead. ### Properties #### accessToken > **accessToken**: `string` OAuth access token for the issuer's userinfo/management surfaces. *** #### claims > **claims**: [`IdTokenClaims`](IdTokenClaims.md) Decoded (and boundary-validated) id_token claims. *** #### expiresAt > **expiresAt**: `number` Epoch seconds; the id_token exp when the token endpoint omits expires_in. *** #### idToken > **idToken**: `string` OIDC id_token. Single-use at the Web3Auth network — never resubmit a spent one. *** #### refreshToken? > `optional` **refreshToken?**: `string` Present when the client requested `offline_access` (widget host). --- ## Interface: TypedDataDomain The EIP-712 domain separator fields. All optional — a domain claims only what it states, and `chainId` in particular is what binds a signature to one chain (the widget refuses a request whose `chainId` disagrees with the connected chain; an absent `chainId` makes no cross-chain claim to check). ### Properties #### chainId? > `optional` **chainId?**: `number` *** #### name? > `optional` **name?**: `string` *** #### salt? > `optional` **salt?**: `string` *** #### verifyingContract? > `optional` **verifyingContract?**: `string` *** #### version? > `optional` **version?**: `string` --- ## Interface: TypedDataField A single EIP-712 struct member: `{ name: 'amount', type: 'uint256' }`. ### Properties #### name > **name**: `string` *** #### type > **type**: `string` --- ## Interface: TypedDataRequest An EIP-712 typed-data signing request (`eth_signTypedData_v4`). The struct is carried in full — NOT as a precomputed digest — so the wallet layer derives the digest itself and no caller can turn this into blind hash signing (`eth_sign`, deliberately unsupported everywhere in this codebase). `types` may still carry the redundant `EIP712Domain` entry that dApps send; the implementation drops it before hashing. ### Properties #### domain > **domain**: [`TypedDataDomain`](TypedDataDomain.md) *** #### message > **message**: `Record`\<`string`, `unknown`\> *** #### primaryType > **primaryType**: `string` *** #### types > **types**: `Record`\<`string`, [`TypedDataField`](TypedDataField.md)[]\> --- ## Interface: UpbondClient The browser client returned by [createUpbond](../functions/createUpbond.md) — the entire supported `@upbond/sdk` runtime surface. It combines the OIDC auth leg (login, session, claims) with the wallet leg (connect, unlock, sign, recovery) in either redirect or embedded mode. Read [UpbondClient.state](#state) synchronously or observe it via [UpbondClient.subscribe](#subscribe). ### Properties #### state > `readonly` **state**: [`UpbondState`](UpbondState.md) The current client state (auth + wallet status, claims, address, phase). Always up to date. ### Methods #### addPasscodeSealer() > **addPasscodeSealer**(): `Promise`\<`void`\> Add a passcode sealer to this device's factor vault (docs/23): the same wallet afterwards unlocks via passkey OR passcode. Requires an unlocked wallet (`wallet_locked` otherwise); the core re-gates with a fresh user verification and collects the passcode via `wallet.promptPasscode`. Refused with `passcode_not_allowed` under a `'passkey-strict'` policy. ##### Returns `Promise`\<`void`\> *** #### closeWallet() > **closeWallet**(): `void` Hide the wallet overlay. ##### Returns `void` *** #### connect() > **connect**(): `Promise`\<`string`[]\> Connect the embedded wallet. Requires a signed-in session — call `login()` first (D20 A-3): the RP authenticates under its own client and the wallet-origin popup only consumes that issuer session as silent SSO (+ passkey onboarding on first use); throws `not_signed_in` otherwise, before opening anything. MUST be called synchronously from a user gesture (it opens the popup). Returns the connected accounts. ##### Returns `Promise`\<`string`[]\> *** #### connectExternal() > **connectExternal**(`options`): `Promise`\<[`ExternalWalletSession`](ExternalWalletSession.md)\> Connect an external wallet: an EIP-6963 injected wallet (MetaMask by default) or WalletConnect v2. Returns a self-contained session exposing the wallet's own EIP-1193 provider — the UPBOND auth session and embedded/redirect wallet are unaffected. The WalletConnect connector needs `wallet.walletConnectProjectId` and lazy-loads its relay stack (plus QR modal) on first use. ##### Parameters ###### options [`ConnectExternalOptions`](ConnectExternalOptions.md) ##### Returns `Promise`\<[`ExternalWalletSession`](ExternalWalletSession.md)\> *** #### connectWallet() > **connectWallet**(): `Promise`\<\{ `status`: [`WalletStatus`](../type-aliases/WalletStatus.md); `walletAddress`: `string` \| `null`; \}\> Layer 1 wallet session; also resolves needs-setup vs needs-recovery for new devices. ##### Returns `Promise`\<\{ `status`: [`WalletStatus`](../type-aliases/WalletStatus.md); `walletAddress`: `string` \| `null`; \}\> *** #### getAccessToken() > **getAccessToken**(): `string` \| `null` The OAuth access token for the issuer's userinfo/management APIs, or `null` when unavailable. ##### Returns `string` \| `null` *** #### getEthereumProvider() > **getEthereumProvider**(): `Promise`\<[`WidgetProvider`](../classes/WidgetProvider.md)\> EIP-1193 provider over the widget (ethers/viem plug in directly). Mounts the widget on first call. ##### Returns `Promise`\<[`WidgetProvider`](../classes/WidgetProvider.md)\> *** #### getIdToken() > **getIdToken**(): `string` \| `null` The raw id_token for downstream verification, or `null` when there is no valid session. ##### Returns `string` \| `null` *** #### getRecoveryStatus() > **getRecoveryStatus**(): `Promise`\<[`RecoveryStatus`](RecoveryStatus.md)\> Recovery status (enrollment + masked OTP contact). Layer 1 — works right after connectWallet, no unlock. ##### Returns `Promise`\<[`RecoveryStatus`](RecoveryStatus.md)\> *** #### getSuiAccount() > **getSuiAccount**(): `Promise`\<[`SuiAccount`](SuiAccount.md)\> The wallet's Sui-on-secp256k1 account (docs/00-BUILD-SPEC.md §3, issue #205 Option C) — same MPC key as the EVM address, Sui address derivation. Served from `state.suiAccount` when the session already captured it (zero prompts); otherwise establishes the Layer 2 ceremony, which for a locked wallet means one biometric — call from a user gesture. Throws `wallet_not_set_up` for a brand-new wallet. ##### Returns `Promise`\<[`SuiAccount`](SuiAccount.md)\> *** #### getUser() > **getUser**(): [`IdTokenClaims`](IdTokenClaims.md) \| `null` The signed-in user's id_token claims, or `null` when signed out or the token has expired. ##### Returns [`IdTokenClaims`](IdTokenClaims.md) \| `null` *** #### init() > **init**(): `Promise`\<`void`\> Call once on page load: consumes the redirect callback (and cleans the URL) or restores a persisted session. ##### Returns `Promise`\<`void`\> *** #### issueApiFactor() > **issueApiFactor**(`label`): `Promise`\<[`ApiFactorIssue`](ApiFactorIssue.md)\> Issue an API factor (docs/37): a new signing factor whose 32-byte key is returned ONCE (`secret`, base64) for the owner to store outside UPBOND. It signs through an authorised signing service; it is a full MPC factor, so treat it like a private key. Requires an unlocked wallet (`wallet_locked` otherwise); the core re-gates with a fresh user verification. `invalid_api_factor_label` for a blank/over-long label, `factor_limit_reached` at the network cap. Disabled for clients created by the public `createUpbond` entry (`api_factors_disabled` after unlock); only the workspace wallet host can enable it. ##### Parameters ###### label `string` ##### Returns `Promise`\<[`ApiFactorIssue`](ApiFactorIssue.md)\> *** #### listExternalWallets() > **listExternalWallets**(): [`ExternalWalletInfo`](ExternalWalletInfo.md)[] The EIP-6963-announced injected wallets currently available in this browser (for install badges / wallet pickers). Announced means installed and responding. Works in every mode; never prompts the user. ##### Returns [`ExternalWalletInfo`](ExternalWalletInfo.md)[] *** #### listFactors() > **listFactors**(): `Promise`\<[`WalletFactor`](WalletFactor.md)[]\> List the account's registered key factors (Layer 2 required — the listing runs behind a biometric). ##### Returns `Promise`\<[`WalletFactor`](WalletFactor.md)[]\> *** #### login() > **login**(`hints?`): `Promise`\<`void`\> Persists PKCE state, then navigates to the issuer. Optional hints (connection, loginHint) skip the issuer's provider chooser. Does not resolve into app code. ##### Parameters ###### hints? [`AuthorizationHints`](AuthorizationHints.md) ##### Returns `Promise`\<`void`\> *** #### loginAndConnect() > **loginAndConnect**(`hints?`): `Promise`\<`string`[]\> One user click → sign-in AND wallet connect (docs/24 1.0.0). Opens a popup synchronously, runs the OIDC login under the RP's own client inside it (the registered `redirectUri` page loads there briefly — its `init()` relays the callback automatically), exchanges the code on THIS page, then the SAME popup continues into the wallet leg. Resolves with the connected accounts. Already signed in? Behaves exactly like [connect](#connect). MUST be called synchronously from a user gesture. Concurrent calls (and concurrent `connect()`) share one flow. Error contract: `unsupported_browser` (in-app browser — guide the user to an external browser), `popup_blocked` (fall back to `login()`), `popup_closed` (the user cancelled), the auth-leg codes (`authorization_error`, `state_mismatch`, ...) if the login fails, and `connect()`'s codes for the wallet leg. If the login succeeded but the wallet leg failed, the session REMAINS signed in — retry with `connect()`. Requires the RP pages (this one and the callback) to not sever `window.opener` (`Cross-Origin-Opener-Policy: same-origin` breaks the relay — use `same-origin-allow-popups` or none). ##### Parameters ###### hints? [`AuthorizationHints`](AuthorizationHints.md) ##### Returns `Promise`\<`string`[]\> *** #### logout() > **logout**(`options?`): `Promise`\<`void`\> Wallet session first (embedded mode: the widget's wallet-origin session too, via `wallet_disconnect`), then RP-initiated issuer logout redirect. Clears storage; keeps the device factor (B1). ##### Parameters ###### options? ###### postLogoutRedirectUri? `string` ##### Returns `Promise`\<`void`\> *** #### openWallet() > **openWallet**(`view?`, `options?`): `Promise`\<`void`\> Open the wallet overlay on a view (RP-initiated, e.g. a "wallet" button). `options` suggests starting values for that view's form — see [WalletViewOptions](WalletViewOptions.md). ##### Parameters ###### view? [`WalletView`](../type-aliases/WalletView.md) ###### options? [`WalletViewOptions`](WalletViewOptions.md) ##### Returns `Promise`\<`void`\> *** #### recoverWallet() > **recoverWallet**(): `Promise`\<`string`\> New-device recovery: synced-passkey restore first, recoverian ceremony fallback. ##### Returns `Promise`\<`string`\> *** #### removeFactor() > **removeFactor**(`factorPubHex`): `Promise`\<`void`\> Remove a stale device factor by its public key (Layer 2 required). Recovery factors and this device's own factor are refused (`factor_not_deletable`). ##### Parameters ###### factorPubHex `string` ##### Returns `Promise`\<`void`\> *** #### removePasscodeSealer() > **removePasscodeSealer**(): `Promise`\<`void`\> Remove the passcode sealer (never the last sealer). Same unlocked-wallet contract as addPasscodeSealer. ##### Returns `Promise`\<`void`\> *** #### revokeApiFactor() > **revokeApiFactor**(`factorPubHex`): `Promise`\<`void`\> Revoke an API factor by its public key (the key is re-shared, the secret stops working). Disabled on the public createUpbond entry, with the same unlocked-wallet contract as issueApiFactor; other factor kinds are refused (`factor_not_deletable`). ##### Parameters ###### factorPubHex `string` ##### Returns `Promise`\<`void`\> *** #### rotateRecoveryFactor() > **rotateRecoveryFactor**(): `Promise`\<`void`\> Rotate the recovery factor (Layer 2 required). ##### Returns `Promise`\<`void`\> *** #### setupWallet() > **setupWallet**(): `Promise`\<`string`\> First-time onboarding — the first unlock creates the wallet. ##### Returns `Promise`\<`string`\> *** #### signMessage() > **signMessage**(`message`): `Promise`\<`` `0x${string}` ``\> EIP-191 personal message signature. Same ceremony semantics as signTransaction. ##### Parameters ###### message `Uint8Array` ##### Returns `Promise`\<`` `0x${string}` ``\> *** #### signTransaction() > **signTransaction**(`request`): `Promise`\<`` `0x${string}` ``\> Signs with the session ceremony; every signature re-gates with a fresh biometric. Call from a user gesture. ##### Parameters ###### request [`SignRequest`](SignRequest.md) ##### Returns `Promise`\<`` `0x${string}` ``\> *** #### signTypedData() > **signTypedData**(`request`, `opts?`): `Promise`\<`` `0x${string}` ``\> EIP-712 typed-data signature (`eth_signTypedData_v4`). Same ceremony semantics as signTransaction. Pass the struct, not a digest — the wallet derives the hash itself, and `types` may keep the redundant `EIP712Domain` entry that dApps include. `opts.verification: 'fresh'` (1.2.0) demands a new user verification for this signature even inside a live L1 window — for statements that change who may sign. ##### Parameters ###### request [`TypedDataRequest`](TypedDataRequest.md) ###### opts? [`SignatureVerificationOptions`](SignatureVerificationOptions.md) ##### Returns `Promise`\<`` `0x${string}` ``\> *** #### subscribe() > **subscribe**(`listener`): () => `void` Observe [state](#state) changes; returns an unsubscribe function. ##### Parameters ###### listener (`state`) => `void` ##### Returns () => `void` *** #### unlockWallet() > **unlockWallet**(): `Promise`\<`string`\> Establishes the session's Layer 2 ceremony (device factor + passkey biometric) and returns the wallet address. Call from a user gesture. One ceremony per session (A2): signatures reuse it, each behind a fresh biometric; logout disposes it. ##### Returns `Promise`\<`string`\> *** #### updateRecoveryContact() > **updateRecoveryContact**(`opts?`): `Promise`\<`void`\> Re-register the recovery contact from the current session's claims (recovery change → Layer 2). Requires an unlocked wallet (`wallet_locked` otherwise); rebinding an already-bound contact runs an OTP ceremony against the OLD contact via wallet.recovery.promptOtp. ##### Parameters ###### opts? ###### channel? `"email"` \| `"sms"` ##### Returns `Promise`\<`void`\> --- ## Interface: UpbondConfig The single configuration object an RP hands to [createUpbond](../functions/createUpbond.md). Validated once at the boundary by `validateConfig`; everything downstream trusts the resolved shape. ### Remarks `validateConfig` throws [UpbondError](../classes/UpbondError.md) with code `config_invalid` when `issuer`/`redirectUri` are not absolute http(s) URLs, `clientId` is empty, `postLoginPath` is not absolute, or (when `wallet` is present) the resolved wallet fields are inconsistent. ### Properties #### clientId > **clientId**: `string` OIDC `client_id` registered at the issuer. *** #### environment? > `optional` **environment?**: [`UpbondEnvironment`](../type-aliases/UpbondEnvironment.md) UPBOND deployment to target; fills `issuer` and the whole wallet leg (Web3Auth project, verifier, network, wallet origin, recovery wiring). Defaults to `'production'` — the minimal integration is `createUpbond({ clientId })`. *** #### issuer? > `optional` **issuer?**: `string` Issuer origin override; defaults from `environment`. Must equal the id_token `iss`. *** #### persistence? > `optional` **persistence?**: `"session"` \| `"local"` Where the session persists (docs/24 D13). 'session' (default) uses sessionStorage — the session ends with the tab. 'local' uses localStorage so a revisit restores the session; paired with an `offline_access` scope, an expired session is silently refreshed on boot (the "open the wallet and you're in" UX). Use 'local' only on the wallet's own origin, never on an untrusted shared device. *** #### postLoginPath? > `optional` **postLoginPath?**: `string` Path shown (history.replaceState) after the callback is consumed; defaults to '/'. Set it to the page's own path for multi-page apps. *** #### redirectUri? > `optional` **redirectUri?**: `string` Redirect URI back into the RP; defaults to `window.location.origin`. Either way it must be registered at the issuer for this client. *** #### scope? > `optional` **scope?**: `string` Defaults to `openid profile email` (add `wallet` to receive wallet_address). *** #### storageKeyPrefix? > `optional` **storageKeyPrefix?**: `string` Storage namespace; defaults to 'upbond'. *** #### wallet? > `optional` **wallet?**: [`UpbondWalletConfig`](UpbondWalletConfig.md) Wallet-leg overrides. Omitting it does NOT disable the wallet: the `environment` preset supplies the embedded (widget) wallet by default, and an auth-only RP simply never calls a wallet method. Pass fields here only to switch to `mode: 'redirect'` (local MPC on the RP page — the wallet's own origin / internal demos), wire the recovery OTP UI, or point at a custom deployment. --- ## Interface: UpbondState The full observable client state, delivered synchronously via `UpbondClient.state` and to `subscribe` listeners on every change. ### Properties #### auth > **auth**: [`AuthStatus`](../type-aliases/AuthStatus.md) OIDC session status. *** #### derivedAddresses > **derivedAddresses**: [`DerivedAddresses`](DerivedAddresses.md) \| `null` EVM + Sui addresses computed offline from `walletPublicKey` (see `addressesFromPublicKey`), or `null` when the claim is absent or malformed — or when the client is in redirect mode (see `walletPublicKey`). Like `walletPublicKey`, expect `null` today — no issuer flow supplies the claim (docs/34 rejected). Prefer `walletAddress` when it is set — it is the bound value and wins over the derived one. *** #### phase > **phase**: [`ProgressPhase`](../type-aliases/ProgressPhase.md) The operation currently in progress. *** #### suiAccount > **suiAccount**: [`SuiAccount`](SuiAccount.md) \| `null` The Sui-on-secp256k1 account (docs/00-BUILD-SPEC.md §3, issue #205 Option C), derived from the SAME MPC key as `walletAddress`. Unlike the EVM address there is no issuer claim for it, so it is `null` until the session's first Layer 2 ceremony (unlock/setup/recovery/signing) — the capture piggybacks on that ceremony and never consumes an extra biometric. Hosts that want it earlier call `getSuiAccount()`. *** #### user > **user**: [`IdTokenClaims`](IdTokenClaims.md) \| `null` Decoded id_token claims while signed in, otherwise `null`. *** #### wallet > **wallet**: [`WalletStatus`](../type-aliases/WalletStatus.md) Wallet-leg status. *** #### walletAddress > **walletAddress**: `string` \| `null` The wallet address once known (after connect/unlock), otherwise `null`. *** #### walletPublicKey > **walletPublicKey**: `string` \| `null` The wallet's secp256k1 public key from the `wallet_public_key` claim (compressed SEC1 hex), or `null` when the claim is absent. No issuer flow populates the claim today: issuer-side pre-derivation was rejected (docs/34, 2026-08-20) because the final TSS key includes ceremony-time client randomness — expect `null` until a ceremony-side flow supplies it. The claim would describe the key under the ISSUER's default verifier (the embedded widget's wallet). A redirect-mode client runs its own verifier / network, whose ceremony key may differ, so this is `null` whenever `wallet` (redirect-mode MPC config) is set — a wrong deposit address is a permanent loss. Such a host reads the raw claim from `user.wallet_public_key` only if it knows its verifier is the default. *** #### wallets > **wallets**: [`WalletRef`](WalletRef.md)[] The user's wallet list (multi-wallet foundation, docs/28). Derived from the `wallet_accounts` claim — present as soon as the user is signed in, before any wallet connect — with the ceremony-learned address as the fallback for a brand-new wallet whose token predates the binding. Today at most one entry (`kind: 'mpc'`), the default entry, whose address `walletAddress` reports once the wallet leg is connected. --- ## Interface: UpbondWalletConfig The wallet leg of [UpbondConfig](UpbondConfig.md). Omit it to take the preset's default wiring. Two shapes share this type: `mode: 'embedded'` (default) delegates to a wallet-origin widget and needs only `walletOrigin` (docs/25-widget.md, docs/24-sdk-design.md D12/D18); `mode: 'redirect'` runs the MPC ceremony on the RP page and needs the Web3Auth fields (all supplied by the `environment` preset). Setting `environment` supplies UPBOND infra defaults for either mode. In either mode the auth leg is the RP's own OIDC redirect (`login()`, docs/24 D20). ### Properties #### environment? > `optional` **environment?**: [`UpbondEnvironment`](../type-aliases/UpbondEnvironment.md) Wallet-leg environment override. Defaults to the top-level [UpbondConfig.environment](UpbondConfig.md#environment) (itself defaulting to 'production'); set it only to point the wallet leg at a different deployment than the issuer. Explicit fields below override the preset field-by-field. *** #### mode? > `optional` **mode?**: `"redirect"` \| `"embedded"` 'embedded' (default, docs/24 D18/D20): the wallet lives in a wallet-origin iframe/popup and the RP talks EIP-1193 (docs/25-widget.md) — keys, passkeys, ceremonies and recovery traffic never leave the wallet origin; only `walletOrigin` applies. The RP authenticates under its own client with `login()` first; `connect()` then consumes that issuer session as silent SSO. 'redirect': the RP page itself runs the MPC ceremony via the wallet-core layer (`connectWallet()` / `setupWallet()` / `signMessage()` …) — for the wallet's own origin and internal demos; every RP origin then needs Web3Auth / recovery-service registration. When `mode` is omitted but any local-MPC field below (`web3authClientId`/`network`/`verifier`/`rpId`/ `recovery`/`promptPasscode`/`sealerPolicy`) is set, the config is treated as 'redirect' (pre-D18 configs keep working unchanged). *** #### network? > `optional` **network?**: `"sapphire_mainnet"` \| `"sapphire_devnet"` Required unless `environment` supplies it (redirect mode). *** #### promptPasscode? > `optional` **promptPasscode?**: (`purpose`) => `Promise`\<`string`\> Passcode UI callback for the second sealer (docs/23, redirect mode): asks the user to choose (`'enroll'`, via `addPasscodeSealer`) or enter (`'unlock'`) their passcode. The value is used for one on-device key derivation and never sent anywhere. Wallet creation is passkey-only and never consults this callback — environments without WebAuthn PRF fail creation with `passkey_unsupported` (guide the user to an external browser). Omit if the app offers no passcode UI. ##### Parameters ###### purpose `"enroll"` \| `"unlock"` ##### Returns `Promise`\<`string`\> *** #### recovery? > `optional` **recovery?**: `Partial`\<[`UpbondWalletRecoveryConfig`](UpbondWalletRecoveryConfig.md)\> \| `null` Recovery-service wiring (WO 2026/003995, redirect mode). Omit to inherit the preset's wiring (or none without a preset); pass `null` to disable recovery even when the preset provides it. An explicit object merges over the preset field-by-field — e.g. `recovery: { promptOtp }` just adds the OTP UI on top of the preset URLs. *** #### rpId? > `optional` **rpId?**: `string` WebAuthn RP ID for the passkey factor; defaults to the page's domain. *** #### sealerPolicy? > `optional` **sealerPolicy?**: `SealerPolicy` Sealer policy (docs/23, redirect mode). Governs the post-hoc passcode sealer only — wallet creation is always passkey-only. Default `'passkey-or-passcode'` allows `addPasscodeSealer` on an unlocked wallet; `'passkey-strict'` disables passcode sealers entirely. *** #### verifier? > `optional` **verifier?**: `string` Custom verifier trusting the issuer JWKS (verifierId = OIDC sub). Required unless `environment` supplies it (redirect mode). *** #### walletConnectProjectId? > `optional` **walletConnectProjectId?**: `string` Reown Cloud (WalletConnect) project id used by `connectExternal({ connector: 'walletconnect' })` (issue #302). Applies in both wallet modes and never participates in the redirect-mode inference below. Omit if the app never offers WalletConnect. *** #### walletOrigin? > `optional` **walletOrigin?**: `string` Origin serving the widget (embedded mode). Required unless `environment` supplies it. *** #### web3authClientId? > `optional` **web3authClientId?**: `string` Web3Auth dashboard project ID (redirect mode). Defaults to UPBOND's project via `environment`; set it only to run against your own Web3Auth project. Required when no `environment` is set. --- ## Interface: UpbondWalletRecoveryConfig Wiring for the two-service non-custodial recovery split (WO 2026/003995, redirect mode). Usually supplied by a [WalletEnvironment](../type-aliases/WalletEnvironment.md) preset; an RP only sets these to point at a custom deployment. See `.claude/rules/wallet.md` for the ciphertext-store / recoverian separation. ### Properties #### promptOtp? > `optional` **promptOtp?**: () => `Promise`\<`string`\> Asks the user for the OTP the recoverian sent to their bound contact; called mid-recovery (between recoverStart and recoverVerify). Optional so recovery-service registration can be wired before the OTP input UI exists; recoverWallet throws clearly if invoked without it. ##### Returns `Promise`\<`string`\> *** #### recoverianServiceName > **recoverianServiceName**: `string` Cloud Run service name of the recoverian (used to scope its requests). *** #### recoverianUrl > **recoverianUrl**: `string` `recoverian-service` base URL — the independent identify + KMS-decrypt side. *** #### serviceUrl > **serviceUrl**: `string` `recovery-service` base URL — the encrypted-blob store (ciphertext only). --- ## Interface: WalletAccountClaim JSON entry of the `wallet_accounts` token claim (snake_case like the other wallet claims). ### Properties #### address > **address**: `string` *** #### default > **default**: `boolean` *** #### kind > **kind**: [`WalletKind`](../type-aliases/WalletKind.md) *** #### public\_key? > `optional` **public\_key?**: `string` --- ## Interface: WalletFactor One registered MPC key factor of the account (Web3Auth caps an account at 10). `kind` comes from the tssShareIndex recorded at creation (DEVICE=2, RECOVERY=3); a factor with no share description reads as `'unknown'`. Public keys only — factor key material never crosses this surface. ### Properties #### addedAt > **addedAt**: `number` \| `null` Epoch milliseconds recorded at creation; null when no description exists. *** #### factorPubHex > **factorPubHex**: `string` Compressed-SEC1 hex of the factor's public key. *** #### isCurrentDevice > **isCurrentDevice**: `boolean` True when this is THIS device's sealed device factor. *** #### kind > **kind**: `"device"` \| `"unknown"` \| `"recovery"` \| `"api"` `'api'` is an API factor (docs/37): a DEVICE-share factor whose key the account owner exported once for out-of-band signing. Classified by the `role` the description records, ahead of the share index. *** #### label > **label**: `string` \| `null` The owner-chosen label of an API factor; null for every other kind. --- ## Interface: WalletRef One wallet attribute on a user — public data only, never key material (docs/constitution.md §2). Exactly one entry per user is `default`; its address is what single-wallet consumers see as `walletAddress` / `wallet_address`. ### Properties #### address > **address**: `string` *** #### default > **default**: `boolean` *** #### kind > **kind**: [`WalletKind`](../type-aliases/WalletKind.md) *** #### publicKey? > `optional` **publicKey?**: `string` --- ## Interface: WalletViewOptions Values for the view [UpbondClient.openWallet](UpbondClient.md#openwallet) opens. Honoured by `'jpyc-issue'` only, and only for RP origins UPBOND has enabled for it — on any other origin, and on every other view, they are ignored and the view opens as it would without them. With both honoured, the view opens on its confirmation step with these values instead of on the empty form. Nothing is submitted until the user confirms there, and they can step back to the form and change either value. Values that cannot be used as they stand (an amount outside the current limits, a network the exchange does not issue on) land on the form instead; malformed ones are dropped without an error. Nothing is reported back — the RP never learns what the user ended up applying for, or whether they did. ### Properties #### amount? > `optional` **amount?**: `string` Amount in token units as a plain decimal string, e.g. `'10000'`. No thousands separator, no exponent. *** #### chainId? > `optional` **chainId?**: `number` EVM chain id of the network to select, e.g. `137`. --- ## Type Alias: AuthErrorCode > **AuthErrorCode** = `Extract`\<[`UpbondErrorCode`](UpbondErrorCode.md), `"authorization_error"` \| `"invalid_callback"` \| `"state_mismatch"` \| `"token_request_failed"` \| `"invalid_id_token"`\> The subset of [UpbondErrorCode](UpbondErrorCode.md) the auth leg can raise as an [AuthError](../classes/AuthError.md). ### Remarks Most integrations should use [createUpbond](../functions/createUpbond.md) instead. --- ## Type Alias: AuthStatus > **AuthStatus** = `"signed-out"` \| `"authenticating"` \| `"signed-in"` OIDC session status. ### Remarks - `signed-out` — no session. - `authenticating` — a login redirect or code exchange is in progress. - `signed-in` — a session is established (an id_token was adopted from the callback or restored/refreshed at init). It stays `signed-in` until `logout()`; the id_token itself may age out meanwhile — `getUser()` / `getIdToken()` / `getAccessToken()` return `null` once it has expired, and (with `offline_access`) the wallet leg refreshes on demand. --- ## Type Alias: ExternalConnector > **ExternalConnector** = `"injected"` \| `"walletconnect"` Which kind of external wallet [ConnectExternalOptions](../interfaces/ConnectExternalOptions.md) targets. --- ## Type Alias: PasskeyCapability > **PasskeyCapability** = `"capable"` \| `"unavailable"` Verdict of [detectPasskeyCapability](../functions/detectPasskeyCapability.md). --- ## Type Alias: ProgressPhase > **ProgressPhase** = `"idle"` \| `"exchanging-code"` \| `"connecting-wallet"` \| `"unlocking"` \| `"signing"` \| `"recovering"` The current long-running operation, for progress UI. `idle` when nothing is in flight; the other phases correspond to code exchange, `connectWallet()`, `unlockWallet()`/`setupWallet()`, signing, and recovery respectively. --- ## Type Alias: ProviderEvent > **ProviderEvent** = `"connect"` \| `"disconnect"` \| `"accountsChanged"` \| `"chainChanged"` The standard EIP-1193 provider events emitted by [WidgetProvider](../classes/WidgetProvider.md). --- ## Type Alias: PublicKeyInput > **PublicKeyInput** = `Uint8Array` \| `string` A secp256k1 public key as bytes or text: 33-byte compressed SEC1, 65-byte uncompressed SEC1, or 64-byte raw `X ‖ Y`; text is hex (0x optional) or base64 (the `SuiAccount.publicKey` shape). --- ## Type Alias: RecoveryEnrollment > **RecoveryEnrollment** = `"enrolled"` \| `"partial"` \| `"none"` \| `"unknown"` Server-verified enrollment state (issue #165 — never optimistic): - `'enrolled'`: BOTH the ciphertext blob (recovery-service) and the OTP contact binding (recoverian) exist server-side — recovery can complete. - `'partial'`: exactly one of the two exists (an interrupted registration). Retrying the rotation repairs it. - `'none'`: neither exists (or recovery is not configured at all). - `'unknown'`: a status query failed (401/network) — the state could not be verified and MUST NOT be shown as enrolled. --- ## Type Alias: UpbondEnvironment > **UpbondEnvironment** = `"production"` \| `"staging"` Named UPBOND deployments an RP can target without knowing the infra. `'production'` is the default everywhere `environment` can be set. --- ## Type Alias: UpbondErrorCode > **UpbondErrorCode** = `"authorization_error"` \| `"invalid_callback"` \| `"state_mismatch"` \| `"token_request_failed"` \| `"invalid_id_token"` \| `"config_invalid"` \| `"not_signed_in"` \| `"session_expired"` \| `"wallet_not_configured"` \| `"popup_blocked"` \| `"popup_closed"` \| `"unsupported_browser"` \| `"wallet_not_set_up"` \| `"recovery_required"` \| `"recovery_unavailable"` \| `"recovery_incomplete"` \| `"passkey_unsupported"` \| `"wallet_locked"` \| `"invalid_otp"` \| `"resend_too_soon"` \| `"factor_limit_reached"` \| `"factor_not_deletable"` \| `"invalid_api_factor_label"` \| `"api_factors_disabled"` \| `"passcode_not_allowed"` \| `"invalid_passcode"` \| `"wallet_error"` \| `"external_wallet_unavailable"` The frozen set of error codes carried by every [UpbondError](../classes/UpbondError.md). Narrow on `error.code` rather than parsing messages — the code union is the customer contract; messages are advisory and may change. ### Remarks Auth leg (raised by the OIDC client in `core/auth.ts`): - `authorization_error` — the issuer returned an `error` parameter in the authorization callback (e.g. the user denied consent). - `invalid_callback` — the callback was malformed or arrived without a matching pending login attempt (missing `code`, or no persisted PKCE state). - `state_mismatch` — the callback `state` did not match the value stored for this login attempt (CSRF / stale-tab defense). - `token_request_failed` — the token endpoint rejected the exchange or the response was missing `id_token`/`access_token`. - `invalid_id_token` — the returned id_token failed binding-claim validation (issuer, audience, expiry, nonce, or subject). Client / session lifecycle: - `config_invalid` — [UpbondConfig](../interfaces/UpbondConfig.md) failed boundary validation in `validateConfig` (missing/relative URL, unknown environment, ...). - `not_signed_in` — an operation needing a session was called before sign-in (embedded `connect()` included: the RP must `login()` first — D20 A-3), or the session was ended while a refresh was in flight. - `session_expired` — the id_token has expired and no refresh token was available, or the refresh grant was definitively rejected — sign in again. - `wallet_not_configured` — a wallet method was called without a matching `wallet` config, or a redirect-mode method was called in embedded mode (or vice versa). Wallet leg (translated from wallet-core implementation errors at the adapter boundary, original error preserved on `cause`): - `popup_blocked` — the browser blocked the popup (`connect()` / `loginAndConnect()` must be called synchronously from a user gesture). Recoverable: fall back to the redirect `login()`. - `popup_closed` — the user closed the popup before the flow completed (login leg or wallet leg). Treat as cancellation, not failure. - `unsupported_browser` — an in-app browser (LINE, Instagram, Facebook, ...) where popup windows and usually WebAuthn are unavailable, so neither the popup login nor the wallet ceremony can run. Terminal in this browser: guide the user to open the page in an external browser. - `wallet_not_set_up` — a signature was requested before the wallet was onboarded (run `setupWallet()` or `recoverWallet()` first). - `recovery_required` — this device holds no usable factor; new-device recovery (`recoverWallet()`) is needed. - `recovery_unavailable` — recovery cannot proceed: no stored binding, or the recoverian/OTP prompt is not configured. - `passkey_unsupported` — the platform authenticator lacks the required WebAuthn PRF capability (or WebAuthn is absent). Terminal for wallet creation — there is no passcode fallback; guide the user to an external browser. Unlock can still succeed via a previously added passcode sealer. - `wallet_locked` — a Layer-2 operation was attempted on a locked wallet (call `unlockWallet()` first). - `invalid_otp` — the recoverian rejected the presented one-time code. - `resend_too_soon` — an OTP was requested again before the resend cooldown elapsed (recoverian rate limit). - `factor_limit_reached` — the MPC network refused to register another key factor (per-account cap); no new device can be enrolled and the recovery factor cannot be rotated until unused factors are removed. - `factor_not_deletable` — `removeFactor` / `revokeApiFactor` refused the requested factor: it is not of the kind that path deletes (recovery factors and unclassified factors are never deletable; API factors only through `revokeApiFactor`, device factors only through `removeFactor`), it is this device's own factor, or the MPC engine refused (last remaining factor / the ceremony's active factor). - `invalid_api_factor_label` — `issueApiFactor` was given a blank or over-long (>64 chars) label; nothing was issued and no verification ran. - `api_factors_disabled` — `issueApiFactor` / `revokeApiFactor` are not enabled on this host (docs/37: issuance is a wallet-origin settings operation, off by default and off in production until its approval record exists). Refused before any ceremony lookup or user verification; nothing was issued or revoked. No `UpbondConfig` field turns it on. - `passcode_not_allowed` — the client's sealer policy is `'passkey-strict'`: passcode sealers are disabled, so `addPasscodeSealer` is refused. - `invalid_passcode` — the entered passcode failed to unseal the device factor vault (authenticated decryption failed). The vault stays locked. - `wallet_error` — catch-all for any other wallet-layer failure (handshake timeout, unexpected internal error). External wallets (`connectExternal`, issue #302): - `external_wallet_unavailable` — no EIP-6963 provider announced for the requested rdns: the wallet extension is not installed (or not responding). Provider-level rejections (e.g. the user declining the connect prompt) surface as `Eip1193Error` with the standard numeric code instead. --- ## ~~Type Alias: WalletEnvironment~~ > **WalletEnvironment** = [`UpbondEnvironment`](UpbondEnvironment.md) ### Deprecated Alias kept for 0.0.x consumers that imported the wallet-scoped name; use [UpbondEnvironment](UpbondEnvironment.md). --- ## Type Alias: WalletKind > **WalletKind** = `"mpc"` \| `"tee-spending"` \| `"smart"` \| `"linked"` \| `"agent"` Wallet classes the multi-wallet foundation can carry. Only `mpc` exists today; the other names are reserved so a future wallet class is a data change, not a schema change (docs/28-multi-wallet-foundation.md). --- ## Type Alias: WalletStatus > **WalletStatus** = `"unavailable"` \| `"disconnected"` \| `"connecting"` \| `"needs-setup"` \| `"needs-recovery"` \| `"ready"` Wallet-leg status, orthogonal to [AuthStatus](AuthStatus.md). ### Remarks - `unavailable` — no redirect-mode wallet wiring on this client (embedded mode — use `connect()`/`getEthereumProvider()` instead — or auth-only). - `disconnected` — signed in, but `connectWallet()` has not run yet. - `connecting` — a `connectWallet()` call is in flight. - `needs-setup` — connected, but this device holds no wallet credential and no stored recovery exists: a brand-new wallet to onboard via `setupWallet()`. - `needs-recovery` — connected, no credential on this device but stored recovery exists: an existing wallet on a fresh device, restore via `recoverWallet()`. - `ready` — this device holds a wallet credential (signing still gates on an unlock + fresh biometric). Since 0.1.0 the decision is the DEVICE CREDENTIAL, not the address: a `wallet_address` claim is written by a binding that may have run on ANOTHER device, so an address never proves this device can sign — only a credential (a sealed device-factor vault record, local or synced) does. --- ## Type Alias: WalletView > **WalletView** = `"home"` \| `"activity"` \| `"send"` \| `"receive"` \| `"jpyc-issue"` \| `"jpyc-redeem"` Wallet screens an RP may deep-link to via [UpbondClient.openWallet](../interfaces/UpbondClient.md#openwallet). `jpyc-issue` / `jpyc-redeem` are a REQUEST, not a guarantee: the widget resolves its own preconditions first (account link, terms of service, per-chain availability), so the user may land on a connect or terms screen instead. Design your flow to tolerate that. There is deliberately no JPYC method on UpbondClient: in direct mode the facade runs on the RP's own page, and a JPYC method there would put the user's JPYC accessToken in RP memory. --- ## Variable: DEFAULT\_WALLETCONNECT\_CHAINS > `const` **DEFAULT\_WALLETCONNECT\_CHAINS**: readonly `number`[] Chains every WalletConnect session offers: every chain in UPBOND's shared chain registry (the networks the wallet knows, mainnets and testnets). All are optional: the wallet approves the ones it supports, so a wallet on any of them can usually stay there without a re-pair (issue #593).