@toon-protocol/client 0.14.11 → 0.15.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/index.js CHANGED
@@ -80,6 +80,29 @@ var PeerAlreadyExistsError = class extends ToonClientError {
80
80
  this.name = "PeerAlreadyExistsError";
81
81
  }
82
82
  };
83
+ var ChannelFundingError = class extends ToonClientError {
84
+ retryable = true;
85
+ constructor(message, cause) {
86
+ super(message, "CHANNEL_FUNDING", cause);
87
+ this.name = "ChannelFundingError";
88
+ }
89
+ };
90
+ var INSUFFICIENT_GAS_MARKERS = [
91
+ "exceeds the balance of the account",
92
+ "insufficient funds for gas",
93
+ "insufficient funds for intrinsic transaction cost",
94
+ "insufficient funds for transfer"
95
+ ];
96
+ function isInsufficientGasError(err) {
97
+ const parts = [];
98
+ let cur = err;
99
+ for (let i = 0; i < 10 && cur != null; i++) {
100
+ parts.push(cur instanceof Error ? cur.message : String(cur));
101
+ cur = cur instanceof Error ? cur.cause : void 0;
102
+ }
103
+ const text = parts.join(" | ").toLowerCase();
104
+ return INSUFFICIENT_GAS_MARKERS.some((m) => text.includes(m));
105
+ }
83
106
 
84
107
  // src/keys/KeyDerivation.ts
85
108
  import { generateSecretKey, getPublicKey } from "nostr-tools/pure";
@@ -2790,14 +2813,33 @@ var OnChainChannelClient = class {
2790
2813
  };
2791
2814
  }
2792
2815
  /**
2793
- * Opens an EVM payment channel on-chain.
2816
+ * Opens an EVM payment channel on-chain, remapping the one-time
2817
+ * insufficient-native-gas revert into an actionable {@link ChannelFundingError}
2818
+ * so callers surface "fund the wallet" instead of the raw viem
2819
+ * "...exceeds the balance of the account" string (toon-meta#65). Only the gas
2820
+ * case is remapped; every other error propagates unchanged.
2821
+ */
2822
+ async openEvmChannel(params) {
2823
+ try {
2824
+ return await this.openEvmChannelUnchecked(params);
2825
+ } catch (err) {
2826
+ if (!isInsufficientGasError(err)) throw err;
2827
+ const chainFamily = params.chain.split(":")[0] || params.chain;
2828
+ throw new ChannelFundingError(
2829
+ `Settlement wallet ${this.evmSigner.address} has no gas on ${chainFamily} to open a payment channel. Run toon_fund_wallet (or fund the wallet) and retry.`,
2830
+ err instanceof Error ? err : void 0
2831
+ );
2832
+ }
2833
+ }
2834
+ /**
2835
+ * Raw EVM channel-open (no gas-error remapping — see {@link openEvmChannel}).
2794
2836
  *
2795
2837
  * 1. Approve token spend if needed
2796
2838
  * 2. Call TokenNetwork.openChannel()
2797
2839
  * 3. Extract channelId from ChannelOpened event
2798
2840
  * 4. Deposit initial funds if specified
2799
2841
  */
2800
- async openEvmChannel(params) {
2842
+ async openEvmChannelUnchecked(params) {
2801
2843
  const {
2802
2844
  chain,
2803
2845
  tokenNetwork,
@@ -5563,435 +5605,6 @@ var HttpConnectorAdmin = class {
5563
5605
  }
5564
5606
  };
5565
5607
 
5566
- // src/pet/filterPetDvmProviders.ts
5567
- import { parseServiceDiscovery } from "@toon-protocol/core";
5568
- import { PET_INTERACTION_REQUEST_KIND } from "@toon-protocol/core";
5569
- function filterPetDvmProviders(events) {
5570
- const providers = [];
5571
- for (const event of events) {
5572
- let parsed;
5573
- try {
5574
- parsed = parseServiceDiscovery(event);
5575
- } catch {
5576
- continue;
5577
- }
5578
- if (!parsed) continue;
5579
- const skill = parsed.skill;
5580
- if (!skill) continue;
5581
- if (!skill.kinds.includes(PET_INTERACTION_REQUEST_KIND)) continue;
5582
- const pricing = skill.pricing[String(PET_INTERACTION_REQUEST_KIND)] ?? "0";
5583
- providers.push({
5584
- ilpAddress: parsed.ilpAddress,
5585
- pricing,
5586
- pubkey: event.pubkey,
5587
- features: skill.features
5588
- });
5589
- }
5590
- providers.sort((a, b) => {
5591
- const priceA = Number(a.pricing) || 0;
5592
- const priceB = Number(b.pricing) || 0;
5593
- return priceA - priceB;
5594
- });
5595
- return providers;
5596
- }
5597
-
5598
- // src/pet/buildPetInteractionRequest.ts
5599
- import { PET_INTERACTION_REQUEST_KIND as PET_INTERACTION_REQUEST_KIND2 } from "@toon-protocol/core";
5600
- var MAX_ACTION_TYPE = 10;
5601
- function buildPetInteractionRequest(params) {
5602
- const { blobbiId, actionType, itemId, tokenCost, isSleeping } = params;
5603
- if (!blobbiId || blobbiId.trim() === "") {
5604
- throw new ValidationError("blobbiId must be a non-empty string");
5605
- }
5606
- if (!Number.isInteger(actionType) || actionType < 0 || actionType > MAX_ACTION_TYPE) {
5607
- throw new ValidationError(
5608
- `actionType must be an integer between 0 and ${MAX_ACTION_TYPE}, got ${actionType}`
5609
- );
5610
- }
5611
- if (!Number.isInteger(itemId) || itemId < 0) {
5612
- throw new ValidationError(
5613
- `itemId must be a non-negative integer, got ${itemId}`
5614
- );
5615
- }
5616
- if (!Number.isFinite(tokenCost) || tokenCost < 0) {
5617
- throw new ValidationError(
5618
- `tokenCost must be a non-negative number, got ${tokenCost}`
5619
- );
5620
- }
5621
- return {
5622
- kind: PET_INTERACTION_REQUEST_KIND2,
5623
- created_at: Math.floor(Date.now() / 1e3),
5624
- tags: [
5625
- ["d", blobbiId],
5626
- ["action", String(actionType)],
5627
- ["item", String(itemId)],
5628
- ["cost", String(tokenCost)],
5629
- ["sleeping", String(isSleeping)]
5630
- ],
5631
- content: ""
5632
- };
5633
- }
5634
-
5635
- // src/pet/parsePetInteractionResult.ts
5636
- var STAT_FIELDS = [
5637
- "hunger",
5638
- "happiness",
5639
- "health",
5640
- "hygiene",
5641
- "energy"
5642
- ];
5643
- var HEX_64_RE = /^[0-9a-f]{64}$/i;
5644
- function isValidStats(obj) {
5645
- if (typeof obj !== "object" || obj === null) return false;
5646
- const record = obj;
5647
- return STAT_FIELDS.every(
5648
- (field) => typeof record[field] === "number" && Number.isFinite(record[field])
5649
- );
5650
- }
5651
- function parsePetInteractionResult(data) {
5652
- if (!data) return null;
5653
- let json;
5654
- try {
5655
- json = atob(data);
5656
- } catch {
5657
- return null;
5658
- }
5659
- let parsed;
5660
- try {
5661
- parsed = JSON.parse(json);
5662
- } catch {
5663
- return null;
5664
- }
5665
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
5666
- return null;
5667
- }
5668
- const record = parsed;
5669
- if (!isValidStats(record["stats"])) return null;
5670
- const stage = record["stage"];
5671
- if (typeof stage !== "number" || !Number.isInteger(stage) || stage < 0 || stage > 2) {
5672
- return null;
5673
- }
5674
- const cycle = record["cycle"];
5675
- if (typeof cycle !== "number" || !Number.isInteger(cycle) || cycle < 0) {
5676
- return null;
5677
- }
5678
- const lastInteraction = record["lastInteraction"];
5679
- if (typeof lastInteraction !== "number" || !Number.isFinite(lastInteraction)) {
5680
- return null;
5681
- }
5682
- const brainHash = record["brainHash"];
5683
- if (typeof brainHash !== "string" || !HEX_64_RE.test(brainHash)) {
5684
- return null;
5685
- }
5686
- const cooldownTimestamps = record["cooldownTimestamps"];
5687
- if (!Array.isArray(cooldownTimestamps)) return null;
5688
- if (!cooldownTimestamps.every(
5689
- (t) => typeof t === "number" && Number.isFinite(t)
5690
- )) {
5691
- return null;
5692
- }
5693
- const validatedStats = record["stats"];
5694
- const stats = {
5695
- hunger: validatedStats.hunger,
5696
- happiness: validatedStats.happiness,
5697
- health: validatedStats.health,
5698
- hygiene: validatedStats.hygiene,
5699
- energy: validatedStats.energy
5700
- };
5701
- return {
5702
- stats,
5703
- stage,
5704
- cycle,
5705
- lastInteraction,
5706
- brainHash,
5707
- cooldownTimestamps: [...cooldownTimestamps]
5708
- };
5709
- }
5710
-
5711
- // src/pet/parsePetInteractionEvent.ts
5712
- function getTagValue(tags, name) {
5713
- for (const tag of tags) {
5714
- if (tag[0] === name) {
5715
- return tag[1];
5716
- }
5717
- }
5718
- return void 0;
5719
- }
5720
- function isStatLike(obj) {
5721
- if (typeof obj !== "object" || obj === null) return false;
5722
- const r = obj;
5723
- return typeof r["hunger"] === "number" && Number.isFinite(r["hunger"]) && typeof r["happiness"] === "number" && Number.isFinite(r["happiness"]) && typeof r["health"] === "number" && Number.isFinite(r["health"]) && typeof r["hygiene"] === "number" && Number.isFinite(r["hygiene"]) && typeof r["energy"] === "number" && Number.isFinite(r["energy"]);
5724
- }
5725
- function cleanStats(obj) {
5726
- return {
5727
- hunger: obj["hunger"],
5728
- happiness: obj["happiness"],
5729
- health: obj["health"],
5730
- hygiene: obj["hygiene"],
5731
- energy: obj["energy"]
5732
- };
5733
- }
5734
- function parseContent(content) {
5735
- try {
5736
- const parsed = JSON.parse(content);
5737
- if (typeof parsed !== "object" || parsed === null) return null;
5738
- if (!isStatLike(parsed.priorStats) || !isStatLike(parsed.decayedStats) || !isStatLike(parsed.finalStats)) {
5739
- return null;
5740
- }
5741
- if (typeof parsed.cycle !== "number" || typeof parsed.stage !== "number" || typeof parsed.tokenCost !== "number") {
5742
- return null;
5743
- }
5744
- return {
5745
- priorStats: cleanStats(parsed.priorStats),
5746
- decayedStats: cleanStats(parsed.decayedStats),
5747
- finalStats: cleanStats(parsed.finalStats),
5748
- cycle: parsed.cycle,
5749
- stage: parsed.stage,
5750
- tokenCost: parsed.tokenCost
5751
- };
5752
- } catch {
5753
- return null;
5754
- }
5755
- }
5756
- function parsePetInteractionEvent(event) {
5757
- const tags = event.tags;
5758
- const blobbiId = getTagValue(tags, "d");
5759
- if (!blobbiId) return null;
5760
- const actionStr = getTagValue(tags, "action");
5761
- if (!actionStr) return null;
5762
- const actionType = Number(actionStr);
5763
- if (!Number.isFinite(actionType)) return null;
5764
- const itemStr = getTagValue(tags, "item");
5765
- if (!itemStr) return null;
5766
- const itemId = Number(itemStr);
5767
- if (!Number.isFinite(itemId)) return null;
5768
- const costStr = getTagValue(tags, "cost");
5769
- if (!costStr) return null;
5770
- const tokenCost = Number(costStr);
5771
- if (!Number.isFinite(tokenCost)) return null;
5772
- const cycleStr = getTagValue(tags, "cycle");
5773
- if (!cycleStr) return null;
5774
- const cycle = Number(cycleStr);
5775
- if (!Number.isFinite(cycle)) return null;
5776
- const stageStr = getTagValue(tags, "stage");
5777
- if (!stageStr) return null;
5778
- const stage = Number(stageStr);
5779
- if (!Number.isFinite(stage)) return null;
5780
- const brainHash = getTagValue(tags, "brain_hash");
5781
- if (!brainHash) return null;
5782
- const proof = getTagValue(tags, "proof");
5783
- const minaTx = getTagValue(tags, "mina_tx");
5784
- const proofStatus = proof && minaTx ? "proven" : "optimistic";
5785
- const content = parseContent(event.content);
5786
- const result = {
5787
- blobbiId,
5788
- actionType,
5789
- itemId,
5790
- tokenCost,
5791
- cycle,
5792
- stage,
5793
- brainHash,
5794
- proofStatus,
5795
- content
5796
- };
5797
- if (proof) result.proof = proof;
5798
- if (minaTx) result.minaTx = minaTx;
5799
- return result;
5800
- }
5801
-
5802
- // src/pet/buildPetListingEvent.ts
5803
- var PET_LISTING_KIND = 30402;
5804
- var STAGE_NAMES = {
5805
- 0: "Egg",
5806
- 1: "Baby",
5807
- 2: "Adult"
5808
- };
5809
- function buildPetListingEvent(params) {
5810
- const {
5811
- blobbiId,
5812
- askPriceUsdc,
5813
- lifecycleHash,
5814
- totalSpent,
5815
- stage,
5816
- stats,
5817
- sellerPubkey,
5818
- relayUrl,
5819
- expiresAt
5820
- } = params;
5821
- const stageName = STAGE_NAMES[stage] ?? "Unknown";
5822
- const summary = `${stageName} pet for sale \u2014 ${totalSpent} PET tokens spent (verified biography)`;
5823
- return {
5824
- kind: PET_LISTING_KIND,
5825
- created_at: Math.floor(Date.now() / 1e3),
5826
- tags: [
5827
- ["d", blobbiId],
5828
- ["title", `Pet ${blobbiId} for sale`],
5829
- ["price", String(askPriceUsdc), "USDC", ""],
5830
- ["summary", summary],
5831
- ["t", "pet"],
5832
- ["t", "toon-pet"],
5833
- ["lifecycle_hash", lifecycleHash],
5834
- ["total_spent", totalSpent],
5835
- ["stage", String(stage)],
5836
- ["expiration", String(expiresAt)],
5837
- ["relay", relayUrl],
5838
- ["p", sellerPubkey]
5839
- ],
5840
- content: JSON.stringify(stats)
5841
- };
5842
- }
5843
-
5844
- // src/pet/parsePetListing.ts
5845
- var HEX_64_RE2 = /^[0-9a-f]{64}$/i;
5846
- function getTagValue2(tags, name) {
5847
- for (const tag of tags) {
5848
- if (tag[0] === name) {
5849
- return tag[1];
5850
- }
5851
- }
5852
- return void 0;
5853
- }
5854
- var DEFAULT_STATS = {
5855
- hunger: 0,
5856
- happiness: 0,
5857
- health: 0,
5858
- hygiene: 0,
5859
- energy: 0
5860
- };
5861
- function parseStats(content) {
5862
- try {
5863
- const parsed = JSON.parse(content);
5864
- if (typeof parsed !== "object" || parsed === null) return DEFAULT_STATS;
5865
- const r = parsed;
5866
- if (typeof r["hunger"] === "number" && typeof r["happiness"] === "number" && typeof r["health"] === "number" && typeof r["hygiene"] === "number" && typeof r["energy"] === "number") {
5867
- return {
5868
- hunger: r["hunger"],
5869
- happiness: r["happiness"],
5870
- health: r["health"],
5871
- hygiene: r["hygiene"],
5872
- energy: r["energy"]
5873
- };
5874
- }
5875
- return DEFAULT_STATS;
5876
- } catch {
5877
- return DEFAULT_STATS;
5878
- }
5879
- }
5880
- function parsePetListing(event) {
5881
- if (event.kind !== 30402) return null;
5882
- const { tags } = event;
5883
- const blobbiId = getTagValue2(tags, "d");
5884
- if (!blobbiId || blobbiId.trim() === "") return null;
5885
- let askPriceUsdc = 0;
5886
- let foundPrice = false;
5887
- for (const tag of tags) {
5888
- if (tag[0] === "price") {
5889
- const priceStr = tag[1];
5890
- if (priceStr === void 0) return null;
5891
- const parsed = Number(priceStr);
5892
- if (!Number.isFinite(parsed) || parsed <= 0) return null;
5893
- askPriceUsdc = parsed;
5894
- foundPrice = true;
5895
- break;
5896
- }
5897
- }
5898
- if (!foundPrice) return null;
5899
- const lifecycleHash = getTagValue2(tags, "lifecycle_hash");
5900
- if (!lifecycleHash) return null;
5901
- if (!HEX_64_RE2.test(lifecycleHash)) return null;
5902
- const totalSpent = getTagValue2(tags, "total_spent");
5903
- if (totalSpent === void 0 || totalSpent === "") return null;
5904
- const totalSpentNum = Number(totalSpent);
5905
- if (!Number.isFinite(totalSpentNum) || totalSpentNum < 0) return null;
5906
- const stageStr = getTagValue2(tags, "stage");
5907
- if (stageStr === void 0) return null;
5908
- const stage = Number(stageStr);
5909
- if (!Number.isFinite(stage)) return null;
5910
- const sellerPubkey = getTagValue2(tags, "p") ?? "";
5911
- const relayUrl = getTagValue2(tags, "relay") ?? "";
5912
- const expiresAtStr = getTagValue2(tags, "expiration");
5913
- const expiresAt = expiresAtStr !== void 0 ? Number(expiresAtStr) : 0;
5914
- const stats = parseStats(event.content);
5915
- return {
5916
- blobbiId,
5917
- askPriceUsdc,
5918
- lifecycleHash,
5919
- totalSpent,
5920
- stage,
5921
- stats,
5922
- sellerPubkey,
5923
- relayUrl,
5924
- expiresAt,
5925
- eventId: event.id,
5926
- createdAt: event.created_at
5927
- };
5928
- }
5929
-
5930
- // src/pet/filterPetListings.ts
5931
- function compareNumericStrings(a, b) {
5932
- if (a === b) return 0;
5933
- try {
5934
- const bigA = BigInt(a);
5935
- const bigB = BigInt(b);
5936
- if (bigA < bigB) return -1;
5937
- if (bigA > bigB) return 1;
5938
- return 0;
5939
- } catch {
5940
- const fa = Number(a);
5941
- const fb = Number(b);
5942
- if (!Number.isFinite(fa) && !Number.isFinite(fb)) return 0;
5943
- if (!Number.isFinite(fa)) return -1;
5944
- if (!Number.isFinite(fb)) return 1;
5945
- return fa - fb;
5946
- }
5947
- }
5948
- function filterPetListings(events, options) {
5949
- const now = Math.floor(Date.now() / 1e3);
5950
- const listings = [];
5951
- for (const event of events) {
5952
- const listing = parsePetListing(event);
5953
- if (listing === null) continue;
5954
- if (listing.expiresAt > 0 && listing.expiresAt < now) continue;
5955
- if (options?.minStage !== void 0 && listing.stage < options.minStage) {
5956
- continue;
5957
- }
5958
- if (options?.maxAskPriceUsdc !== void 0 && listing.askPriceUsdc > options.maxAskPriceUsdc) {
5959
- continue;
5960
- }
5961
- if (options?.minTotalSpent !== void 0) {
5962
- if (compareNumericStrings(listing.totalSpent, options.minTotalSpent) < 0) {
5963
- continue;
5964
- }
5965
- }
5966
- if (options?.sellerPubkey !== void 0 && listing.sellerPubkey !== options.sellerPubkey) {
5967
- continue;
5968
- }
5969
- listings.push(listing);
5970
- }
5971
- listings.sort((a, b) => compareNumericStrings(b.totalSpent, a.totalSpent));
5972
- return listings;
5973
- }
5974
-
5975
- // src/pet/buildPetPurchaseRequest.ts
5976
- import { PET_INTERACTION_REQUEST_KIND as PET_INTERACTION_REQUEST_KIND3 } from "@toon-protocol/core";
5977
- var TRANSFER_OWNERSHIP_ACTION = 9;
5978
- function buildPetPurchaseRequest(params) {
5979
- const { blobbiId, listingEventId, buyerPubkey, tokenCost, sellerPubkey } = params;
5980
- return {
5981
- kind: PET_INTERACTION_REQUEST_KIND3,
5982
- created_at: Math.floor(Date.now() / 1e3),
5983
- tags: [
5984
- ["action", String(TRANSFER_OWNERSHIP_ACTION)],
5985
- ["i", blobbiId],
5986
- ["listing", listingEventId],
5987
- ["buyer", buyerPubkey],
5988
- ["p", sellerPubkey],
5989
- ["cost", String(tokenCost)]
5990
- ],
5991
- content: ""
5992
- };
5993
- }
5994
-
5995
5608
  // src/faucet.ts
5996
5609
  function defaultFaucetTimeout(chain) {
5997
5610
  return chain === "mina" ? 12e4 : 3e4;
@@ -7100,6 +6713,7 @@ function writeKeystoreFile(path, keystore) {
7100
6713
  }
7101
6714
  export {
7102
6715
  BtpRuntimeClient,
6716
+ ChannelFundingError,
7103
6717
  ChannelManager,
7104
6718
  ConnectorError,
7105
6719
  EvmSigner,
@@ -7130,9 +6744,6 @@ export {
7130
6744
  buildBackupEvent,
7131
6745
  buildBackupFilter,
7132
6746
  buildConsentRequest,
7133
- buildPetInteractionRequest,
7134
- buildPetListingEvent,
7135
- buildPetPurchaseRequest,
7136
6747
  buildRendererEventTemplate,
7137
6748
  buildSettlementInfo,
7138
6749
  buildStoreWriteEnvelope,
@@ -7145,9 +6756,8 @@ export {
7145
6756
  deriveNostrKeyFromMnemonic,
7146
6757
  deterministicGenerator,
7147
6758
  encryptMnemonic2 as encryptMnemonic,
6759
+ extractArweaveTxId,
7148
6760
  extractUiResource,
7149
- filterPetDvmProviders,
7150
- filterPetListings,
7151
6761
  fundWallet,
7152
6762
  generateKeystore,
7153
6763
  generateMnemonic,
@@ -7157,6 +6767,7 @@ export {
7157
6767
  guardedRenderDispatch,
7158
6768
  httpEndpointToBtpUrl,
7159
6769
  importKeystore,
6770
+ isInsufficientGasError,
7160
6771
  isPrfSupported,
7161
6772
  isTrustDowngrade,
7162
6773
  loadKeystore,
@@ -7164,9 +6775,6 @@ export {
7164
6775
  parseFulfillHttp,
7165
6776
  parseFulfillHttpBytes,
7166
6777
  parseHttpResponse,
7167
- parsePetInteractionEvent,
7168
- parsePetInteractionResult,
7169
- parsePetListing,
7170
6778
  parseUiCoordinate,
7171
6779
  parseX402Body,
7172
6780
  parseX402Challenge,