@agether/sdk 1.5.4 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -318,26 +318,48 @@ var init_MorphoClient = __esm({
318
318
  tx: txHash
319
319
  };
320
320
  }
321
- /** Get ETH / USDC balances for EOA and AgentAccount. */
321
+ /** Get ETH / USDC / collateral balances for EOA and AgentAccount. */
322
322
  async getBalances() {
323
323
  const eoaAddr = this.wallet.address;
324
324
  const usdc = new import_ethers.Contract(this.config.contracts.usdc, ERC20_ABI, this.provider);
325
325
  const ethBal = await this.provider.getBalance(eoaAddr);
326
326
  const usdcBal = await usdc.balanceOf(eoaAddr);
327
+ const eoaCollateral = {};
328
+ for (const [symbol, info] of Object.entries(BASE_COLLATERALS)) {
329
+ try {
330
+ const token = new import_ethers.Contract(info.address, ERC20_ABI, this.provider);
331
+ const bal = await token.balanceOf(eoaAddr);
332
+ eoaCollateral[symbol] = import_ethers.ethers.formatUnits(bal, info.decimals);
333
+ } catch {
334
+ eoaCollateral[symbol] = "0";
335
+ }
336
+ }
327
337
  const result = {
328
338
  agentId: this.agentId || "?",
329
339
  address: eoaAddr,
330
340
  eth: import_ethers.ethers.formatEther(ethBal),
331
- usdc: import_ethers.ethers.formatUnits(usdcBal, 6)
341
+ usdc: import_ethers.ethers.formatUnits(usdcBal, 6),
342
+ collateral: eoaCollateral
332
343
  };
333
344
  try {
334
345
  const acctAddr = await this.getAccountAddress();
335
346
  const acctEth = await this.provider.getBalance(acctAddr);
336
347
  const acctUsdc = await usdc.balanceOf(acctAddr);
348
+ const acctCollateral = {};
349
+ for (const [symbol, info] of Object.entries(BASE_COLLATERALS)) {
350
+ try {
351
+ const token = new import_ethers.Contract(info.address, ERC20_ABI, this.provider);
352
+ const bal = await token.balanceOf(acctAddr);
353
+ acctCollateral[symbol] = import_ethers.ethers.formatUnits(bal, info.decimals);
354
+ } catch {
355
+ acctCollateral[symbol] = "0";
356
+ }
357
+ }
337
358
  result.agentAccount = {
338
359
  address: acctAddr,
339
360
  eth: import_ethers.ethers.formatEther(acctEth),
340
- usdc: import_ethers.ethers.formatUnits(acctUsdc, 6)
361
+ usdc: import_ethers.ethers.formatUnits(acctUsdc, 6),
362
+ collateral: acctCollateral
341
363
  };
342
364
  } catch {
343
365
  }
@@ -840,27 +862,23 @@ var X402Client_exports = {};
840
862
  __export(X402Client_exports, {
841
863
  X402Client: () => X402Client
842
864
  });
843
- function chainIdFromNetwork(network) {
844
- const m = network.match(/^eip155:(\d+)$/);
845
- return m ? Number(m[1]) : 1;
846
- }
847
- var import_ethers2, USDC_DOMAINS, X402Client;
865
+ var import_fetch, import_client, import_client2, import_accounts, X402Client;
848
866
  var init_X402Client = __esm({
849
867
  "src/clients/X402Client.ts"() {
850
868
  "use strict";
851
- import_ethers2 = require("ethers");
852
- USDC_DOMAINS = {
853
- "eip155:1": { name: "USD Coin", version: "2", address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" },
854
- "eip155:8453": { name: "USD Coin", version: "2", address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" },
855
- "eip155:84532": { name: "USD Coin", version: "2", address: "0x036CbD53842c5426634e7929541eC2318f3dCF7e" },
856
- "eip155:42161": { name: "USD Coin", version: "2", address: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831" },
857
- "eip155:10": { name: "USD Coin", version: "2", address: "0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85" }
858
- };
869
+ import_fetch = require("@x402/fetch");
870
+ import_client = require("@x402/core/client");
871
+ import_client2 = require("@x402/evm/exact/client");
872
+ import_accounts = require("viem/accounts");
859
873
  X402Client = class {
860
874
  constructor(config) {
861
875
  this.config = config;
862
- const provider = new import_ethers2.ethers.JsonRpcProvider(config.rpcUrl);
863
- this.wallet = new import_ethers2.ethers.Wallet(config.privateKey, provider);
876
+ const privateKey = config.privateKey.startsWith("0x") ? config.privateKey : `0x${config.privateKey}`;
877
+ const signer = (0, import_accounts.privateKeyToAccount)(privateKey);
878
+ this.address = signer.address;
879
+ const client = new import_client.x402Client();
880
+ (0, import_client2.registerExactEvmScheme)(client, { signer });
881
+ this.paidFetch = (0, import_fetch.wrapFetchWithPayment)(fetch, client);
864
882
  }
865
883
  async get(url, opts) {
866
884
  return this.request(url, { ...opts, method: "GET" });
@@ -874,13 +892,13 @@ var init_X402Client = __esm({
874
892
  });
875
893
  }
876
894
  getAddress() {
877
- return this.wallet.address;
895
+ return this.address;
878
896
  }
879
- // ──────────── Core request / 402-retry loop ────────────
897
+ // ──────────── Core request — @x402/fetch handles 402 automatically ────────────
880
898
  async request(url, options) {
881
899
  try {
882
- console.log(" [1/4] Calling resource server\u2026");
883
- const response = await fetch(url, {
900
+ console.log(` [x402] ${options?.method || "GET"} ${url}`);
901
+ const response = await this.paidFetch(url, {
884
902
  ...options,
885
903
  headers: {
886
904
  ...options?.headers,
@@ -889,45 +907,13 @@ var init_X402Client = __esm({
889
907
  });
890
908
  if (response.ok) {
891
909
  const data = await response.json();
892
- return { success: true, data };
893
- }
894
- if (response.status !== 402) {
895
- return { success: false, error: `HTTP ${response.status}: ${await response.text()}` };
896
- }
897
- console.log(" [2/4] 402 received \u2014 parsing payment requirements\u2026");
898
- const parsed = await this.parsePaymentRequired(response);
899
- if (!parsed) {
900
- return { success: false, error: "Could not parse payment requirements from 402 response" };
901
- }
902
- const { requirements, resource } = parsed;
903
- console.log(` scheme : ${requirements.scheme}`);
904
- console.log(` network : ${requirements.network}`);
905
- console.log(` amount : ${requirements.amount} (atomic)`);
906
- console.log(` asset : ${requirements.asset}`);
907
- console.log(` payTo : ${requirements.payTo}`);
908
- console.log(" [3/4] Signing EIP-3009 transferWithAuthorization\u2026");
909
- const paymentPayload = await this.buildPaymentPayload(requirements, resource, url);
910
- const paymentB64 = Buffer.from(JSON.stringify(paymentPayload)).toString("base64");
911
- await this.riskCheck(paymentPayload, requirements);
912
- console.log(" [4/4] Retrying with PAYMENT-SIGNATURE header\u2026");
913
- const paidResponse = await fetch(url, {
914
- ...options,
915
- headers: {
916
- ...options?.headers,
917
- "X-Agent-Id": this.config.agentId || "",
918
- // v2 header
919
- "PAYMENT-SIGNATURE": paymentB64,
920
- // v1 compat header (some servers still use this)
921
- "X-PAYMENT": paymentB64
922
- }
923
- });
924
- if (paidResponse.ok) {
925
- const data = await paidResponse.json();
926
- const settlementHeader = paidResponse.headers.get("PAYMENT-RESPONSE") || paidResponse.headers.get("X-PAYMENT-RESPONSE");
910
+ const paymentResponse = response.headers.get("PAYMENT-RESPONSE");
927
911
  let txHash;
928
- if (settlementHeader) {
912
+ if (paymentResponse) {
929
913
  try {
930
- const settlement = JSON.parse(Buffer.from(settlementHeader, "base64").toString("utf-8"));
914
+ const settlement = JSON.parse(
915
+ Buffer.from(paymentResponse, "base64").toString("utf-8")
916
+ );
931
917
  txHash = settlement.transaction;
932
918
  } catch {
933
919
  }
@@ -935,164 +921,26 @@ var init_X402Client = __esm({
935
921
  return {
936
922
  success: true,
937
923
  data,
938
- paymentInfo: {
939
- amount: requirements.amount,
940
- asset: requirements.extra?.name || "USDC",
941
- network: requirements.network,
942
- txHash
943
- }
924
+ ...txHash ? {
925
+ paymentInfo: {
926
+ amount: "",
927
+ asset: "USDC",
928
+ network: "eip155:8453",
929
+ txHash
930
+ }
931
+ } : {}
944
932
  };
945
933
  }
946
- const errBody = await paidResponse.text();
947
- return { success: false, error: `Payment rejected (HTTP ${paidResponse.status}): ${errBody}` };
934
+ const errBody = await response.text();
935
+ return {
936
+ success: false,
937
+ error: `HTTP ${response.status}: ${errBody}`
938
+ };
948
939
  } catch (error) {
949
- return { success: false, error: `Request failed: ${error instanceof Error ? error.message : String(error)}` };
950
- }
951
- }
952
- // ──────────── Parse 402 response ────────────
953
- async parsePaymentRequired(response) {
954
- const prHeader = response.headers.get("PAYMENT-REQUIRED") || response.headers.get("x-payment-required");
955
- if (prHeader) {
956
- try {
957
- const decoded = JSON.parse(Buffer.from(prHeader, "base64").toString("utf-8"));
958
- if (decoded.accepts?.length) {
959
- return { requirements: decoded.accepts[0], resource: decoded.resource };
960
- }
961
- } catch {
962
- }
963
- }
964
- try {
965
- const body = await response.json();
966
- if (body.accepts && Array.isArray(body.accepts) && body.accepts.length > 0) {
967
- return { requirements: body.accepts[0], resource: body.resource };
968
- }
969
- if (body.paymentRequirements) {
970
- const pr = Array.isArray(body.paymentRequirements) ? body.paymentRequirements[0] : body.paymentRequirements;
971
- return { requirements: pr, resource: body.resource };
972
- }
973
- if (body.scheme && body.network) {
974
- return { requirements: body, resource: body.resource };
975
- }
976
- } catch {
977
- }
978
- const wwwAuth = response.headers.get("WWW-Authenticate");
979
- if (wwwAuth) {
980
- const m = wwwAuth.match(/x402[^"]*"([^"]+)"/);
981
- if (m) {
982
- try {
983
- const decoded = JSON.parse(Buffer.from(m[1], "base64").toString("utf-8"));
984
- const reqs = Array.isArray(decoded) ? decoded[0] : decoded;
985
- return { requirements: reqs };
986
- } catch {
987
- }
988
- }
989
- }
990
- return null;
991
- }
992
- // ──────────── Build x402 v2 PaymentPayload with EIP-3009 ────────────
993
- //
994
- // If an AgentAccount is configured, we use it as the `from` address
995
- // (smart wallet pays directly). The AgentAccount implements EIP-1271
996
- // so USDC's transferWithAuthorization will call isValidSignature()
997
- // to verify the owner's ECDSA signature. The facilitator detects
998
- // the >65-byte or smart-wallet case and uses the bytes overload.
999
- async buildPaymentPayload(reqs, resource, url) {
1000
- const now = Math.floor(Date.now() / 1e3);
1001
- const validAfter = String(now - 60);
1002
- const validBefore = String(now + (reqs.maxTimeoutSeconds || 300));
1003
- const nonce = import_ethers2.ethers.hexlify(import_ethers2.ethers.randomBytes(32));
1004
- const chainId = chainIdFromNetwork(reqs.network);
1005
- const usdcDomain = USDC_DOMAINS[reqs.network] || USDC_DOMAINS["eip155:1"];
1006
- const payerAddress = this.config.accountAddress || this.wallet.address;
1007
- const isSmartWallet = !!this.config.accountAddress;
1008
- const domain = {
1009
- name: usdcDomain.name,
1010
- version: usdcDomain.version,
1011
- chainId,
1012
- verifyingContract: reqs.asset || usdcDomain.address
1013
- };
1014
- const types = {
1015
- TransferWithAuthorization: [
1016
- { name: "from", type: "address" },
1017
- { name: "to", type: "address" },
1018
- { name: "value", type: "uint256" },
1019
- { name: "validAfter", type: "uint256" },
1020
- { name: "validBefore", type: "uint256" },
1021
- { name: "nonce", type: "bytes32" }
1022
- ]
1023
- };
1024
- const value = {
1025
- from: payerAddress,
1026
- // AgentAccount or EOA
1027
- to: reqs.payTo,
1028
- value: reqs.amount,
1029
- validAfter,
1030
- validBefore,
1031
- nonce
1032
- };
1033
- let signature = await this.wallet.signTypedData(domain, types, value);
1034
- if (isSmartWallet) {
1035
- signature = signature + "00";
1036
- }
1037
- if (isSmartWallet) {
1038
- console.log(` \u2713 Signed for AgentAccount ${payerAddress.slice(0, 10)}\u2026 (EIP-1271, chain=${chainId})`);
1039
- } else {
1040
- console.log(` \u2713 Signed (from=${payerAddress.slice(0, 10)}\u2026, chain=${chainId})`);
1041
- }
1042
- return {
1043
- x402Version: 2,
1044
- resource: resource || { url, description: "", mimeType: "application/json" },
1045
- accepted: {
1046
- scheme: reqs.scheme,
1047
- network: reqs.network,
1048
- amount: reqs.amount,
1049
- asset: reqs.asset,
1050
- payTo: reqs.payTo,
1051
- maxTimeoutSeconds: reqs.maxTimeoutSeconds,
1052
- extra: reqs.extra || {}
1053
- },
1054
- payload: {
1055
- signature,
1056
- authorization: {
1057
- from: payerAddress,
1058
- // AgentAccount address — facilitator checks balance here
1059
- to: reqs.payTo,
1060
- value: reqs.amount,
1061
- validAfter,
1062
- validBefore,
1063
- nonce
1064
- }
1065
- }
1066
- };
1067
- }
1068
- // ──────────── Risk check via our backend ────────────
1069
- async riskCheck(paymentPayload, reqs) {
1070
- try {
1071
- const verifyUrl = `${this.config.backendUrl}/x402/verify`;
1072
- const resp = await fetch(verifyUrl, {
1073
- method: "POST",
1074
- headers: {
1075
- "Content-Type": "application/json",
1076
- "X-Agent-Id": this.config.agentId || "",
1077
- ...this.config.accountAddress ? { "X-Agent-Account": this.config.accountAddress } : {}
1078
- },
1079
- body: JSON.stringify({
1080
- x402Version: 2,
1081
- paymentPayload,
1082
- paymentRequirements: reqs
1083
- }),
1084
- signal: AbortSignal.timeout(5e3)
1085
- });
1086
- if (resp.ok) {
1087
- const result = await resp.json();
1088
- const decision = resp.headers.get("X-Risk-Decision") || (result.isValid ? "allow" : "unknown");
1089
- const score = resp.headers.get("X-Risk-Score") || "?";
1090
- console.log(` \u2713 Risk check: ${decision} (score=${score})`);
1091
- } else {
1092
- console.log(` \u26A0 Risk check failed (HTTP ${resp.status}) \u2014 continuing anyway`);
1093
- }
1094
- } catch {
1095
- console.log(" \u26A0 Risk check unavailable \u2014 continuing");
940
+ return {
941
+ success: false,
942
+ error: `Request failed: ${error instanceof Error ? error.message : String(error)}`
943
+ };
1096
944
  }
1097
945
  }
1098
946
  };
@@ -1100,7 +948,7 @@ var init_X402Client = __esm({
1100
948
  });
1101
949
 
1102
950
  // src/cli.ts
1103
- var import_ethers3 = require("ethers");
951
+ var import_ethers2 = require("ethers");
1104
952
  var fs = __toESM(require("fs"));
1105
953
  var path = __toESM(require("path"));
1106
954
  var os = __toESM(require("os"));
@@ -1206,7 +1054,7 @@ async function cmdInit(privateKey, agentId) {
1206
1054
  const backendUrl = process.env.AGETHER_BACKEND_URL || DEFAULT_BACKEND;
1207
1055
  let wallet;
1208
1056
  try {
1209
- wallet = new import_ethers3.ethers.Wallet(privateKey);
1057
+ wallet = new import_ethers2.ethers.Wallet(privateKey);
1210
1058
  } catch {
1211
1059
  console.error("\u274C Invalid private key");
1212
1060
  process.exit(1);
@@ -1221,8 +1069,8 @@ async function cmdInit(privateKey, agentId) {
1221
1069
  }
1222
1070
  async function cmdRegister(name) {
1223
1071
  const config = requireConfig();
1224
- const provider = new import_ethers3.ethers.JsonRpcProvider(config.rpcUrl);
1225
- const signer = new import_ethers3.ethers.Wallet(config.privateKey, provider);
1072
+ const provider = new import_ethers2.ethers.JsonRpcProvider(config.rpcUrl);
1073
+ const signer = new import_ethers2.ethers.Wallet(config.privateKey, provider);
1226
1074
  const agentName = name || `Agent-${signer.address.slice(0, 8)}`;
1227
1075
  console.log(`\u{1F916} Registering agent: ${agentName}
1228
1076
  `);
@@ -1245,7 +1093,7 @@ async function cmdRegister(name) {
1245
1093
  process.exit(1);
1246
1094
  }
1247
1095
  console.log(" [2/4] Registering on ERC-8004 IdentityRegistry...");
1248
- const agentRegistry = new import_ethers3.ethers.Contract(registryAddr, ERC8004_ABI, signer);
1096
+ const agentRegistry = new import_ethers2.ethers.Contract(registryAddr, ERC8004_ABI, signer);
1249
1097
  let agentId;
1250
1098
  if (config.agentId && config.agentId !== "0") {
1251
1099
  agentId = BigInt(config.agentId);
@@ -1276,7 +1124,7 @@ async function cmdRegister(name) {
1276
1124
  const agentURI = `data:application/json;base64,${Buffer.from(registrationFile).toString("base64")}`;
1277
1125
  const tx = await agentRegistry["register(string)"](agentURI);
1278
1126
  const receipt = await waitForTx(tx);
1279
- const transferTopic = import_ethers3.ethers.id("Transfer(address,address,uint256)");
1127
+ const transferTopic = import_ethers2.ethers.id("Transfer(address,address,uint256)");
1280
1128
  const transferLog = receipt.logs.find((log) => log.topics[0] === transferTopic);
1281
1129
  if (transferLog && transferLog.topics.length >= 4) {
1282
1130
  agentId = BigInt(transferLog.topics[3]);
@@ -1309,11 +1157,11 @@ async function cmdRegister(name) {
1309
1157
  if (chainId === 31337 || chainId === 1) {
1310
1158
  console.log(" [3/4] Minting test USDC (Hardhat fork)...");
1311
1159
  const deployerPk = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
1312
- const deployer = new import_ethers3.ethers.Wallet(deployerPk, provider);
1160
+ const deployer = new import_ethers2.ethers.Wallet(deployerPk, provider);
1313
1161
  const usdcAddr = contracts.usdc;
1314
1162
  if (usdcAddr) {
1315
1163
  try {
1316
- const usdc = new import_ethers3.ethers.Contract(usdcAddr, MOCK_ERC20_ABI, deployer);
1164
+ const usdc = new import_ethers2.ethers.Contract(usdcAddr, MOCK_ERC20_ABI, deployer);
1317
1165
  const tx = await usdc.mint(signer.address, BigInt(5e10));
1318
1166
  await waitForTx(tx);
1319
1167
  console.log(" \u2713 Minted $50,000 USDC");
@@ -1326,7 +1174,7 @@ async function cmdRegister(name) {
1326
1174
  }
1327
1175
  console.log(" [4/4] Creating AgentAccount...");
1328
1176
  if (factoryAddr) {
1329
- const factory = new import_ethers3.ethers.Contract(factoryAddr, ACCOUNT_FACTORY_ABI2, signer);
1177
+ const factory = new import_ethers2.ethers.Contract(factoryAddr, ACCOUNT_FACTORY_ABI2, signer);
1330
1178
  try {
1331
1179
  const exists = await factory.accountExists(agentId);
1332
1180
  if (exists) {
@@ -1344,7 +1192,7 @@ async function cmdRegister(name) {
1344
1192
  }
1345
1193
  }
1346
1194
  if (validationAddr) {
1347
- const vr = new import_ethers3.ethers.Contract(validationAddr, VALIDATION_REGISTRY_ABI, provider);
1195
+ const vr = new import_ethers2.ethers.Contract(validationAddr, VALIDATION_REGISTRY_ABI, provider);
1348
1196
  try {
1349
1197
  const approved = await vr.isAgentCodeApproved(agentId);
1350
1198
  console.log(`
@@ -1565,7 +1413,7 @@ async function cmdX402Call(url, method = "GET", body) {
1565
1413
  const config = requireConfig();
1566
1414
  console.log("\n\u{1F510} x402 Paid API Call\n");
1567
1415
  const x402 = await getX402Client(config);
1568
- console.log(` Wallet: ${new import_ethers3.ethers.Wallet(config.privateKey).address}`);
1416
+ console.log(` Wallet: ${new import_ethers2.ethers.Wallet(config.privateKey).address}`);
1569
1417
  console.log(`
1570
1418
  \u{1F4E1} ${method} ${url}`);
1571
1419
  if (body) console.log(`\u{1F4E6} Body: ${body}`);
package/dist/index.d.mts CHANGED
@@ -206,10 +206,12 @@ interface BalancesResult {
206
206
  address: string;
207
207
  eth: string;
208
208
  usdc: string;
209
+ collateral: Record<string, string>;
209
210
  agentAccount?: {
210
211
  address: string;
211
212
  eth: string;
212
213
  usdc: string;
214
+ collateral: Record<string, string>;
213
215
  };
214
216
  }
215
217
  interface RegisterResult {
@@ -294,7 +296,7 @@ declare class MorphoClient {
294
296
  * If already registered, returns existing state.
295
297
  */
296
298
  register(_name?: string): Promise<RegisterResult>;
297
- /** Get ETH / USDC balances for EOA and AgentAccount. */
299
+ /** Get ETH / USDC / collateral balances for EOA and AgentAccount. */
298
300
  getBalances(): Promise<BalancesResult>;
299
301
  /** Transfer USDC from EOA to AgentAccount. */
300
302
  fundAccount(usdcAmount: string): Promise<FundResult>;
@@ -397,22 +399,17 @@ declare class MorphoClient {
397
399
  /**
398
400
  * x402 HTTP Client — Make paid API calls via the x402 protocol (v2)
399
401
  *
400
- * Implements the Coinbase x402 spec:
401
- * https://github.com/coinbase/x402
402
+ * Built on top of the official @x402/fetch + @x402/evm SDK.
403
+ * https://docs.x402.org/getting-started/quickstart-for-buyers
402
404
  *
403
405
  * Flow:
404
406
  * 1. Client → Resource Server (normal request)
405
- * 2. Resource Server → 402 with PaymentRequired JSON body
406
- * Body: { x402Version, error, resource, accepts: [PaymentRequirements…] }
407
- * 3. Client picks a PaymentRequirements from `accepts`,
408
- * signs an EIP-3009 transferWithAuthorization (EIP-712 typed data),
409
- * builds a PaymentPayload, base64-encodes it as PAYMENT-SIGNATURE header
410
- * 4. Client → Resource Server (retries with PAYMENT-SIGNATURE)
411
- * 5. Resource Server forwards to Facilitator /verify → /settle
412
- * 6. Resource Server → 200 + data (or error)
407
+ * 2. Resource Server → 402 with PAYMENT-REQUIRED header (base64 JSON)
408
+ * 3. @x402/fetch auto-picks PaymentRequirements, signs EIP-3009 via EVM scheme
409
+ * 4. Client Resource Server (retries with PAYMENT-SIGNATURE header)
410
+ * 5. Resource Server verifies via facilitator → settles → 200 + data
413
411
  *
414
- * Chain support: Base (8453), Ethereum (1), and Hardhat fork (31337).
415
- * USDC domain is resolved per-chain from USDC_DOMAINS map.
412
+ * Chain support: Base (8453), Base Sepolia (84532), Ethereum (1).
416
413
  */
417
414
  interface X402Config {
418
415
  privateKey: string;
@@ -443,16 +440,14 @@ interface PaymentRequirements {
443
440
  extra?: Record<string, unknown>;
444
441
  }
445
442
  declare class X402Client {
446
- private wallet;
447
443
  private config;
444
+ private paidFetch;
445
+ private address;
448
446
  constructor(config: X402Config);
449
447
  get<T = unknown>(url: string, opts?: RequestInit): Promise<X402Response<T>>;
450
448
  post<T = unknown>(url: string, body?: unknown, opts?: RequestInit): Promise<X402Response<T>>;
451
449
  getAddress(): string;
452
450
  private request;
453
- private parsePaymentRequired;
454
- private buildPaymentPayload;
455
- private riskCheck;
456
451
  }
457
452
 
458
453
  /**
package/dist/index.d.ts CHANGED
@@ -206,10 +206,12 @@ interface BalancesResult {
206
206
  address: string;
207
207
  eth: string;
208
208
  usdc: string;
209
+ collateral: Record<string, string>;
209
210
  agentAccount?: {
210
211
  address: string;
211
212
  eth: string;
212
213
  usdc: string;
214
+ collateral: Record<string, string>;
213
215
  };
214
216
  }
215
217
  interface RegisterResult {
@@ -294,7 +296,7 @@ declare class MorphoClient {
294
296
  * If already registered, returns existing state.
295
297
  */
296
298
  register(_name?: string): Promise<RegisterResult>;
297
- /** Get ETH / USDC balances for EOA and AgentAccount. */
299
+ /** Get ETH / USDC / collateral balances for EOA and AgentAccount. */
298
300
  getBalances(): Promise<BalancesResult>;
299
301
  /** Transfer USDC from EOA to AgentAccount. */
300
302
  fundAccount(usdcAmount: string): Promise<FundResult>;
@@ -397,22 +399,17 @@ declare class MorphoClient {
397
399
  /**
398
400
  * x402 HTTP Client — Make paid API calls via the x402 protocol (v2)
399
401
  *
400
- * Implements the Coinbase x402 spec:
401
- * https://github.com/coinbase/x402
402
+ * Built on top of the official @x402/fetch + @x402/evm SDK.
403
+ * https://docs.x402.org/getting-started/quickstart-for-buyers
402
404
  *
403
405
  * Flow:
404
406
  * 1. Client → Resource Server (normal request)
405
- * 2. Resource Server → 402 with PaymentRequired JSON body
406
- * Body: { x402Version, error, resource, accepts: [PaymentRequirements…] }
407
- * 3. Client picks a PaymentRequirements from `accepts`,
408
- * signs an EIP-3009 transferWithAuthorization (EIP-712 typed data),
409
- * builds a PaymentPayload, base64-encodes it as PAYMENT-SIGNATURE header
410
- * 4. Client → Resource Server (retries with PAYMENT-SIGNATURE)
411
- * 5. Resource Server forwards to Facilitator /verify → /settle
412
- * 6. Resource Server → 200 + data (or error)
407
+ * 2. Resource Server → 402 with PAYMENT-REQUIRED header (base64 JSON)
408
+ * 3. @x402/fetch auto-picks PaymentRequirements, signs EIP-3009 via EVM scheme
409
+ * 4. Client Resource Server (retries with PAYMENT-SIGNATURE header)
410
+ * 5. Resource Server verifies via facilitator → settles → 200 + data
413
411
  *
414
- * Chain support: Base (8453), Ethereum (1), and Hardhat fork (31337).
415
- * USDC domain is resolved per-chain from USDC_DOMAINS map.
412
+ * Chain support: Base (8453), Base Sepolia (84532), Ethereum (1).
416
413
  */
417
414
  interface X402Config {
418
415
  privateKey: string;
@@ -443,16 +440,14 @@ interface PaymentRequirements {
443
440
  extra?: Record<string, unknown>;
444
441
  }
445
442
  declare class X402Client {
446
- private wallet;
447
443
  private config;
444
+ private paidFetch;
445
+ private address;
448
446
  constructor(config: X402Config);
449
447
  get<T = unknown>(url: string, opts?: RequestInit): Promise<X402Response<T>>;
450
448
  post<T = unknown>(url: string, body?: unknown, opts?: RequestInit): Promise<X402Response<T>>;
451
449
  getAddress(): string;
452
450
  private request;
453
- private parsePaymentRequired;
454
- private buildPaymentPayload;
455
- private riskCheck;
456
451
  }
457
452
 
458
453
  /**