@4mica/sdk 0.5.3 → 0.5.5

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.
@@ -0,0 +1,132 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RecipientClient = void 0;
4
+ const bls_1 = require("../bls");
5
+ const payment_1 = require("../payment");
6
+ const guarantee_1 = require("../guarantee");
7
+ const errors_1 = require("../errors");
8
+ const models_1 = require("../models");
9
+ const debug_1 = require("../debug");
10
+ const utils_1 = require("../utils");
11
+ const shared_1 = require("./shared");
12
+ class RecipientClient {
13
+ client;
14
+ constructor(client) {
15
+ this.client = client;
16
+ }
17
+ get recipientAddress() {
18
+ return (0, utils_1.normalizeAddress)(this.client.signer.signer.address);
19
+ }
20
+ get guaranteeDomain() {
21
+ return this.client.guaranteeDomain;
22
+ }
23
+ async createTab(userAddress, recipientAddress, erc20Token, ttl) {
24
+ const body = {
25
+ user_address: (0, utils_1.normalizeAddress)(userAddress),
26
+ recipient_address: (0, utils_1.normalizeAddress)(recipientAddress),
27
+ erc20_token: erc20Token ? (0, utils_1.normalizeAddress)(erc20Token) : null,
28
+ ttl: ttl ?? null,
29
+ };
30
+ const result = await this.client.rpc.createPaymentTab(body);
31
+ const record = result;
32
+ const tabIdRaw = record.id ?? record.tabId ?? record.tab_id;
33
+ const tabId = (0, shared_1.isNumericLike)(tabIdRaw) ? tabIdRaw : 0;
34
+ return (0, utils_1.parseU256)(tabId);
35
+ }
36
+ async getTabPaymentStatus(tabId) {
37
+ const status = await this.client.gateway.getPaymentStatus(tabId);
38
+ return (0, shared_1.tabStatusFromRpc)(status);
39
+ }
40
+ async issuePaymentGuarantee(claims, signature, scheme) {
41
+ const payload = (0, payment_1.buildPaymentPayload)(claims, signature, scheme);
42
+ const cert = await this.client.rpc.issueGuarantee(payload);
43
+ const record = cert;
44
+ const certClaims = typeof record.claims === 'string' ? record.claims : '';
45
+ const signatureOut = typeof record.signature === 'string' ? record.signature : '';
46
+ return { claims: certClaims, signature: signatureOut };
47
+ }
48
+ verifyPaymentGuarantee(cert) {
49
+ const claims = (0, guarantee_1.decodeGuaranteeClaims)(cert.claims);
50
+ const domainHex = this.guaranteeDomain.startsWith('0x')
51
+ ? this.guaranteeDomain.slice(2)
52
+ : Buffer.from(this.guaranteeDomain).toString('hex');
53
+ const claimsHex = Buffer.from(claims.domain).toString('hex');
54
+ if (claimsHex !== domainHex) {
55
+ throw new errors_1.VerificationError('guarantee domain mismatch');
56
+ }
57
+ return claims;
58
+ }
59
+ async remunerate(cert, waitOptions) {
60
+ this.verifyPaymentGuarantee(cert);
61
+ const describeValue = (value) => {
62
+ if (value === null)
63
+ return 'null';
64
+ if (value === undefined)
65
+ return 'undefined';
66
+ if (Array.isArray(value))
67
+ return `array(len=${value.length})`;
68
+ if (typeof value === 'object') {
69
+ const keys = Object.keys(value);
70
+ return `object(keys=${keys.slice(0, 6).join(',')}${keys.length > 6 ? ',...' : ''})`;
71
+ }
72
+ return typeof value;
73
+ };
74
+ if (debug_1.DEBUG_CERTS) {
75
+ const preview = typeof cert.signature === 'string' ? cert.signature.slice(0, 12) : '';
76
+ console.log(` debug remunerate: signature=${describeValue(cert.signature)} ${preview}`);
77
+ }
78
+ if (typeof cert.claims !== 'string') {
79
+ throw new errors_1.VerificationError(`certificate.claims must be a hex string, got ${describeValue(cert.claims)}`);
80
+ }
81
+ if (typeof cert.signature !== 'string') {
82
+ throw new errors_1.VerificationError(`certificate.signature must be a hex string, got ${describeValue(cert.signature)}`);
83
+ }
84
+ const sigWords = await (0, bls_1.signatureToWordsAsync)(cert.signature);
85
+ const claimsBytes = Buffer.from(cert.claims.replace(/^0x/, ''), 'hex');
86
+ if (waitOptions) {
87
+ return this.client.gateway.remunerate(claimsBytes, sigWords, waitOptions);
88
+ }
89
+ return this.client.gateway.remunerate(claimsBytes, sigWords);
90
+ }
91
+ async listSettledTabs() {
92
+ const tabs = await this.client.rpc.listSettledTabs(this.recipientAddress);
93
+ return tabs.map((t) => models_1.TabInfo.fromRpc(t));
94
+ }
95
+ async listPendingRemunerations() {
96
+ const items = await this.client.rpc.listPendingRemunerations(this.recipientAddress);
97
+ return items.map((item) => models_1.PendingRemunerationInfo.fromRpc(item));
98
+ }
99
+ async getTab(tabId) {
100
+ const result = await this.client.rpc.getTab(tabId);
101
+ return result ? models_1.TabInfo.fromRpc(result) : null;
102
+ }
103
+ async listRecipientTabs(settlementStatuses) {
104
+ const tabs = await this.client.rpc.listRecipientTabs(this.recipientAddress, settlementStatuses);
105
+ return tabs.map((t) => models_1.TabInfo.fromRpc(t));
106
+ }
107
+ async getTabGuarantees(tabId) {
108
+ const guarantees = await this.client.rpc.getTabGuarantees(tabId);
109
+ return guarantees.map((g) => models_1.GuaranteeInfo.fromRpc(g));
110
+ }
111
+ async getLatestGuarantee(tabId) {
112
+ const result = await this.client.rpc.getLatestGuarantee(tabId);
113
+ return result ? models_1.GuaranteeInfo.fromRpc(result) : null;
114
+ }
115
+ async getGuarantee(tabId, reqId) {
116
+ const result = await this.client.rpc.getGuarantee(tabId, reqId);
117
+ return result ? models_1.GuaranteeInfo.fromRpc(result) : null;
118
+ }
119
+ async listRecipientPayments() {
120
+ const payments = await this.client.rpc.listRecipientPayments(this.recipientAddress);
121
+ return payments.map((p) => models_1.RecipientPaymentInfo.fromRpc(p));
122
+ }
123
+ async getCollateralEventsForTab(tabId) {
124
+ const events = await this.client.rpc.getCollateralEventsForTab(tabId);
125
+ return events.map((ev) => models_1.CollateralEventInfo.fromRpc(ev));
126
+ }
127
+ async getUserAssetBalance(userAddress, assetAddress) {
128
+ const balance = await this.client.rpc.getUserAssetBalance(userAddress, assetAddress);
129
+ return balance ? models_1.AssetBalanceInfo.fromRpc(balance) : null;
130
+ }
131
+ }
132
+ exports.RecipientClient = RecipientClient;
@@ -0,0 +1,11 @@
1
+ import { TabPaymentStatus } from '../models';
2
+ export declare const isNumericLike: (value: unknown) => value is number | bigint | string;
3
+ export type RpcTabStatus = {
4
+ paid?: number | bigint | string;
5
+ paidAmount?: number | bigint | string;
6
+ remunerated?: boolean;
7
+ paidOut?: boolean;
8
+ asset?: string;
9
+ assetAddress?: string;
10
+ };
11
+ export declare function tabStatusFromRpc(status: RpcTabStatus): TabPaymentStatus;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isNumericLike = void 0;
4
+ exports.tabStatusFromRpc = tabStatusFromRpc;
5
+ const utils_1 = require("../utils");
6
+ const isNumericLike = (value) => typeof value === 'number' || typeof value === 'bigint' || typeof value === 'string';
7
+ exports.isNumericLike = isNumericLike;
8
+ function tabStatusFromRpc(status) {
9
+ const paid = status.paid !== undefined ? status.paid : (status.paidAmount ?? 0);
10
+ const remunerated = status.remunerated ?? status.paidOut ?? false;
11
+ const asset = status.asset ?? status.assetAddress ?? '';
12
+ return {
13
+ paid: (0, utils_1.parseU256)(paid),
14
+ remunerated: Boolean(remunerated),
15
+ asset,
16
+ };
17
+ }
@@ -0,0 +1,17 @@
1
+ import { PaymentGuaranteeRequestClaims, PaymentSignature, SigningScheme, TabPaymentStatus, UserInfo } from '../models';
2
+ import type { TxReceiptWaitOptions } from '../contract';
3
+ import type { Client } from './index';
4
+ export declare class UserClient {
5
+ private client;
6
+ constructor(client: Client);
7
+ get guaranteeDomain(): string;
8
+ approveErc20(token: string, amount: number | bigint | string, waitOptions?: TxReceiptWaitOptions): Promise<import("viem").TransactionReceipt>;
9
+ deposit(amount: number | bigint | string, erc20Token?: string, waitOptions?: TxReceiptWaitOptions): Promise<import("viem").TransactionReceipt>;
10
+ getUser(): Promise<UserInfo[]>;
11
+ getTabPaymentStatus(tabId: number | bigint): Promise<TabPaymentStatus>;
12
+ signPayment(claims: PaymentGuaranteeRequestClaims, scheme?: SigningScheme): Promise<PaymentSignature>;
13
+ payTab(tabId: number | bigint, reqId: number | bigint, amount: number | bigint | string, recipientAddress: string, erc20Token?: string, waitOptions?: TxReceiptWaitOptions): Promise<import("viem").TransactionReceipt>;
14
+ requestWithdrawal(amount: number | bigint | string, erc20Token?: string, waitOptions?: TxReceiptWaitOptions): Promise<import("viem").TransactionReceipt>;
15
+ cancelWithdrawal(erc20Token?: string, waitOptions?: TxReceiptWaitOptions): Promise<import("viem").TransactionReceipt>;
16
+ finalizeWithdrawal(erc20Token?: string, waitOptions?: TxReceiptWaitOptions): Promise<import("viem").TransactionReceipt>;
17
+ }
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UserClient = void 0;
4
+ const models_1 = require("../models");
5
+ const shared_1 = require("./shared");
6
+ const utils_1 = require("../utils");
7
+ class UserClient {
8
+ client;
9
+ constructor(client) {
10
+ this.client = client;
11
+ }
12
+ get guaranteeDomain() {
13
+ return this.client.guaranteeDomain;
14
+ }
15
+ async approveErc20(token, amount, waitOptions) {
16
+ if (waitOptions) {
17
+ return this.client.gateway.approveErc20(token, amount, waitOptions);
18
+ }
19
+ return this.client.gateway.approveErc20(token, amount);
20
+ }
21
+ async deposit(amount, erc20Token, waitOptions) {
22
+ if (waitOptions) {
23
+ return this.client.gateway.deposit(amount, erc20Token, waitOptions);
24
+ }
25
+ return this.client.gateway.deposit(amount, erc20Token);
26
+ }
27
+ async getUser() {
28
+ const assets = await this.client.gateway.getUserAssets();
29
+ return assets.map((a) => ({
30
+ asset: a.asset,
31
+ collateral: (0, utils_1.parseU256)(a.collateral),
32
+ withdrawalRequestAmount: (0, utils_1.parseU256)(a.withdrawalRequestAmount),
33
+ withdrawalRequestTimestamp: Number(a.withdrawalRequestTimestamp),
34
+ }));
35
+ }
36
+ async getTabPaymentStatus(tabId) {
37
+ const status = await this.client.gateway.getPaymentStatus(tabId);
38
+ return (0, shared_1.tabStatusFromRpc)(status);
39
+ }
40
+ async signPayment(claims, scheme = models_1.SigningScheme.EIP712) {
41
+ return this.client.signer.signRequest(this.client.params, claims, scheme);
42
+ }
43
+ async payTab(tabId, reqId, amount, recipientAddress, erc20Token, waitOptions) {
44
+ if (erc20Token) {
45
+ if (waitOptions) {
46
+ return this.client.gateway.payTabErc20(tabId, amount, erc20Token, recipientAddress, waitOptions);
47
+ }
48
+ return this.client.gateway.payTabErc20(tabId, amount, erc20Token, recipientAddress);
49
+ }
50
+ if (waitOptions) {
51
+ return this.client.gateway.payTabEth(tabId, reqId, amount, recipientAddress, waitOptions);
52
+ }
53
+ return this.client.gateway.payTabEth(tabId, reqId, amount, recipientAddress);
54
+ }
55
+ async requestWithdrawal(amount, erc20Token, waitOptions) {
56
+ if (waitOptions) {
57
+ return this.client.gateway.requestWithdrawal(amount, erc20Token, waitOptions);
58
+ }
59
+ return this.client.gateway.requestWithdrawal(amount, erc20Token);
60
+ }
61
+ async cancelWithdrawal(erc20Token, waitOptions) {
62
+ if (waitOptions) {
63
+ return this.client.gateway.cancelWithdrawal(erc20Token, waitOptions);
64
+ }
65
+ return this.client.gateway.cancelWithdrawal(erc20Token);
66
+ }
67
+ async finalizeWithdrawal(erc20Token, waitOptions) {
68
+ if (waitOptions) {
69
+ return this.client.gateway.finalizeWithdrawal(erc20Token, waitOptions);
70
+ }
71
+ return this.client.gateway.finalizeWithdrawal(erc20Token);
72
+ }
73
+ }
74
+ exports.UserClient = UserClient;
package/dist/client.js CHANGED
@@ -187,7 +187,30 @@ class RecipientClient {
187
187
  }
188
188
  async remunerate(cert) {
189
189
  this.verifyPaymentGuarantee(cert);
190
- const sigWords = (0, bls_1.signatureToWords)(cert.signature);
190
+ const describeValue = (value) => {
191
+ if (value === null)
192
+ return 'null';
193
+ if (value === undefined)
194
+ return 'undefined';
195
+ if (Array.isArray(value))
196
+ return `array(len=${value.length})`;
197
+ if (typeof value === 'object') {
198
+ const keys = Object.keys(value);
199
+ return `object(keys=${keys.slice(0, 6).join(',')}${keys.length > 6 ? ',...' : ''})`;
200
+ }
201
+ return typeof value;
202
+ };
203
+ if (process.env.DEBUG_CERTS === '1') {
204
+ const preview = typeof cert.signature === 'string' ? cert.signature.slice(0, 12) : '';
205
+ console.log(` debug remunerate: signature=${describeValue(cert.signature)} ${preview}`);
206
+ }
207
+ if (typeof cert.claims !== 'string') {
208
+ throw new errors_1.VerificationError(`certificate.claims must be a hex string, got ${describeValue(cert.claims)}`);
209
+ }
210
+ if (typeof cert.signature !== 'string') {
211
+ throw new errors_1.VerificationError(`certificate.signature must be a hex string, got ${describeValue(cert.signature)}`);
212
+ }
213
+ const sigWords = await (0, bls_1.signatureToWordsAsync)(cert.signature);
191
214
  const claimsBytes = Buffer.from(cert.claims.replace(/^0x/, ''), 'hex');
192
215
  return this.client.gateway.remunerate(claimsBytes, sigWords);
193
216
  }
@@ -0,0 +1,4 @@
1
+ export declare const ADMIN_API_KEY_HEADER = "x-api-key";
2
+ export declare const ADMIN_API_KEY_PREFIX = "ak_";
3
+ export declare const ADMIN_SCOPE_SUSPEND_USERS = "user_suspension:write";
4
+ export declare const ADMIN_SCOPE_MANAGE_KEYS = "admin_api_keys:manage";
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ADMIN_SCOPE_MANAGE_KEYS = exports.ADMIN_SCOPE_SUSPEND_USERS = exports.ADMIN_API_KEY_PREFIX = exports.ADMIN_API_KEY_HEADER = void 0;
4
+ exports.ADMIN_API_KEY_HEADER = 'x-api-key';
5
+ exports.ADMIN_API_KEY_PREFIX = 'ak_';
6
+ exports.ADMIN_SCOPE_SUSPEND_USERS = 'user_suspension:write';
7
+ exports.ADMIN_SCOPE_MANAGE_KEYS = 'admin_api_keys:manage';
@@ -6,6 +6,10 @@ type CoreContract = GetContractReturnType<typeof core4micaAbi, {
6
6
  public: ReturnType<typeof createPublicClient>;
7
7
  wallet: TWalletClient;
8
8
  }>;
9
+ export type TxReceiptWaitOptions = {
10
+ timeout?: number;
11
+ pollingInterval?: number;
12
+ };
9
13
  export declare class ContractGateway {
10
14
  readonly publicClient: TPublicClient;
11
15
  readonly walletClient: TWalletClient;
@@ -15,8 +19,8 @@ export declare class ContractGateway {
15
19
  static create(rpcUrl: string, signer: Account, contractAddress: Hex, chainId: number): Promise<ContractGateway>;
16
20
  private erc20;
17
21
  getGuaranteeDomain(): Promise<string>;
18
- approveErc20(token: string, amount: number | bigint | string): Promise<import("viem").TransactionReceipt>;
19
- deposit(amount: number | bigint | string, erc20Token?: string): Promise<import("viem").TransactionReceipt>;
22
+ approveErc20(token: string, amount: number | bigint | string, waitOptions?: TxReceiptWaitOptions): Promise<import("viem").TransactionReceipt>;
23
+ deposit(amount: number | bigint | string, erc20Token?: string, waitOptions?: TxReceiptWaitOptions): Promise<import("viem").TransactionReceipt>;
20
24
  getUserAssets(): Promise<{
21
25
  asset: `0x${string}`;
22
26
  collateral: bigint;
@@ -28,11 +32,11 @@ export declare class ContractGateway {
28
32
  remunerated: boolean;
29
33
  asset: Hex;
30
34
  }>;
31
- payTabEth(tabId: number | bigint, reqId: number | bigint, amount: number | bigint | string, recipient: string): Promise<import("viem").TransactionReceipt>;
32
- payTabErc20(tabId: number | bigint, amount: number | bigint | string, erc20Token: string, recipient: string): Promise<import("viem").TransactionReceipt>;
33
- requestWithdrawal(amount: number | bigint | string, erc20Token?: string): Promise<import("viem").TransactionReceipt>;
34
- cancelWithdrawal(erc20Token?: string): Promise<import("viem").TransactionReceipt>;
35
- finalizeWithdrawal(erc20Token?: string): Promise<import("viem").TransactionReceipt>;
36
- remunerate(claimsBlob: Uint8Array, signatureWords: Uint8Array[]): Promise<import("viem").TransactionReceipt>;
35
+ payTabEth(tabId: number | bigint, reqId: number | bigint, amount: number | bigint | string, recipient: string, waitOptions?: TxReceiptWaitOptions): Promise<import("viem").TransactionReceipt>;
36
+ payTabErc20(tabId: number | bigint, amount: number | bigint | string, erc20Token: string, recipient: string, waitOptions?: TxReceiptWaitOptions): Promise<import("viem").TransactionReceipt>;
37
+ requestWithdrawal(amount: number | bigint | string, erc20Token?: string, waitOptions?: TxReceiptWaitOptions): Promise<import("viem").TransactionReceipt>;
38
+ cancelWithdrawal(erc20Token?: string, waitOptions?: TxReceiptWaitOptions): Promise<import("viem").TransactionReceipt>;
39
+ finalizeWithdrawal(erc20Token?: string, waitOptions?: TxReceiptWaitOptions): Promise<import("viem").TransactionReceipt>;
40
+ remunerate(claimsBlob: Uint8Array, signatureWords: Uint8Array[], waitOptions?: TxReceiptWaitOptions): Promise<import("viem").TransactionReceipt>;
37
41
  }
38
42
  export {};
package/dist/contract.js CHANGED
@@ -2,31 +2,9 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ContractGateway = void 0;
4
4
  const viem_1 = require("viem");
5
- const chains_1 = require("viem/chains");
6
5
  const core4mica_1 = require("./abi/core4mica");
6
+ const chain_1 = require("./chain");
7
7
  const utils_1 = require("./utils");
8
- const CHAINS = {
9
- 1: chains_1.mainnet,
10
- 11155111: chains_1.sepolia,
11
- 8453: chains_1.base,
12
- 84532: chains_1.baseSepolia,
13
- 137: chains_1.polygon,
14
- 80002: chains_1.polygonAmoy,
15
- };
16
- function getChain(chainId, rpcUrl) {
17
- const chain = CHAINS[chainId];
18
- if (chain)
19
- return chain;
20
- return {
21
- id: chainId,
22
- name: `local-${chainId}`,
23
- nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
24
- rpcUrls: {
25
- default: { http: [rpcUrl] },
26
- public: { http: [rpcUrl] },
27
- },
28
- };
29
- }
30
8
  class ContractGateway {
31
9
  publicClient;
32
10
  walletClient;
@@ -38,7 +16,7 @@ class ContractGateway {
38
16
  this.contract = contract;
39
17
  }
40
18
  static async create(rpcUrl, signer, contractAddress, chainId) {
41
- const chain = getChain(chainId, rpcUrl);
19
+ const chain = (0, chain_1.getChain)(chainId, rpcUrl);
42
20
  const publicClient = (0, viem_1.createPublicClient)({
43
21
  transport: (0, viem_1.http)(rpcUrl),
44
22
  });
@@ -74,14 +52,14 @@ class ContractGateway {
74
52
  async getGuaranteeDomain() {
75
53
  return this.contract.read.guaranteeDomainSeparator();
76
54
  }
77
- async approveErc20(token, amount) {
55
+ async approveErc20(token, amount, waitOptions) {
78
56
  const erc20 = this.erc20(token);
79
57
  // spender address logic
80
58
  const spender = this.contract.address;
81
59
  const hash = await erc20.write.approve([spender, (0, utils_1.parseU256)(amount)]);
82
- return this.publicClient.waitForTransactionReceipt({ hash });
60
+ return this.publicClient.waitForTransactionReceipt({ hash, ...(waitOptions ?? {}) });
83
61
  }
84
- async deposit(amount, erc20Token) {
62
+ async deposit(amount, erc20Token, waitOptions) {
85
63
  let hash;
86
64
  if (erc20Token) {
87
65
  hash = await this.contract.write.depositStablecoin([erc20Token, (0, utils_1.parseU256)(amount)]);
@@ -89,7 +67,7 @@ class ContractGateway {
89
67
  else {
90
68
  hash = await this.contract.write.deposit({ value: (0, utils_1.parseU256)(amount) });
91
69
  }
92
- return this.publicClient.waitForTransactionReceipt({ hash });
70
+ return this.publicClient.waitForTransactionReceipt({ hash, ...(waitOptions ?? {}) });
93
71
  }
94
72
  async getUserAssets() {
95
73
  const addr = this.walletClient.account.address;
@@ -111,25 +89,25 @@ class ContractGateway {
111
89
  asset,
112
90
  };
113
91
  }
114
- async payTabEth(tabId, reqId, amount, recipient) {
92
+ async payTabEth(tabId, reqId, amount, recipient, waitOptions) {
115
93
  const data = new TextEncoder().encode(`tab_id:${tabId.toString(16)};req_id:${reqId.toString(16)}`);
116
94
  const hash = await this.walletClient.sendTransaction({
117
95
  to: recipient,
118
96
  value: (0, utils_1.parseU256)(amount),
119
97
  data: (0, utils_1.hexFromBytes)(data),
120
98
  });
121
- return this.publicClient.waitForTransactionReceipt({ hash });
99
+ return this.publicClient.waitForTransactionReceipt({ hash, ...(waitOptions ?? {}) });
122
100
  }
123
- async payTabErc20(tabId, amount, erc20Token, recipient) {
101
+ async payTabErc20(tabId, amount, erc20Token, recipient, waitOptions) {
124
102
  const hash = await this.contract.write.payTabInERC20Token([
125
103
  (0, utils_1.parseU256)(tabId),
126
104
  erc20Token,
127
105
  (0, utils_1.parseU256)(amount),
128
106
  recipient,
129
107
  ]);
130
- return this.publicClient.waitForTransactionReceipt({ hash });
108
+ return this.publicClient.waitForTransactionReceipt({ hash, ...(waitOptions ?? {}) });
131
109
  }
132
- async requestWithdrawal(amount, erc20Token) {
110
+ async requestWithdrawal(amount, erc20Token, waitOptions) {
133
111
  const value = (0, utils_1.parseU256)(amount);
134
112
  let hash;
135
113
  if (erc20Token) {
@@ -138,9 +116,9 @@ class ContractGateway {
138
116
  else {
139
117
  hash = await this.contract.write.requestWithdrawal([value]);
140
118
  }
141
- return this.publicClient.waitForTransactionReceipt({ hash });
119
+ return this.publicClient.waitForTransactionReceipt({ hash, ...(waitOptions ?? {}) });
142
120
  }
143
- async cancelWithdrawal(erc20Token) {
121
+ async cancelWithdrawal(erc20Token, waitOptions) {
144
122
  let hash;
145
123
  if (erc20Token) {
146
124
  hash = await this.contract.write.cancelWithdrawal([erc20Token]);
@@ -148,9 +126,9 @@ class ContractGateway {
148
126
  else {
149
127
  hash = await this.contract.write.cancelWithdrawal();
150
128
  }
151
- return this.publicClient.waitForTransactionReceipt({ hash });
129
+ return this.publicClient.waitForTransactionReceipt({ hash, ...(waitOptions ?? {}) });
152
130
  }
153
- async finalizeWithdrawal(erc20Token) {
131
+ async finalizeWithdrawal(erc20Token, waitOptions) {
154
132
  let hash;
155
133
  if (erc20Token) {
156
134
  hash = await this.contract.write.finalizeWithdrawal([erc20Token]);
@@ -158,9 +136,9 @@ class ContractGateway {
158
136
  else {
159
137
  hash = await this.contract.write.finalizeWithdrawal();
160
138
  }
161
- return this.publicClient.waitForTransactionReceipt({ hash });
139
+ return this.publicClient.waitForTransactionReceipt({ hash, ...(waitOptions ?? {}) });
162
140
  }
163
- async remunerate(claimsBlob, signatureWords) {
141
+ async remunerate(claimsBlob, signatureWords, waitOptions) {
164
142
  const sigStruct = {
165
143
  x_c0_a: (0, utils_1.hexFromBytes)(signatureWords[0]),
166
144
  x_c0_b: (0, utils_1.hexFromBytes)(signatureWords[1]),
@@ -172,7 +150,7 @@ class ContractGateway {
172
150
  y_c1_b: (0, utils_1.hexFromBytes)(signatureWords[7]),
173
151
  };
174
152
  const hash = await this.contract.write.remunerate([(0, utils_1.hexFromBytes)(claimsBlob), sigStruct]);
175
- return this.publicClient.waitForTransactionReceipt({ hash });
153
+ return this.publicClient.waitForTransactionReceipt({ hash, ...(waitOptions ?? {}) });
176
154
  }
177
155
  }
178
156
  exports.ContractGateway = ContractGateway;
@@ -0,0 +1,2 @@
1
+ export declare const DEBUG_BLS: boolean;
2
+ export declare const DEBUG_CERTS: boolean;
package/dist/debug.js ADDED
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEBUG_CERTS = exports.DEBUG_BLS = void 0;
4
+ exports.DEBUG_BLS = process.env.DEBUG_BLS === '1';
5
+ exports.DEBUG_CERTS = process.env.DEBUG_CERTS === '1';
package/dist/guarantee.js CHANGED
@@ -5,6 +5,8 @@ exports.decodeGuaranteeClaims = decodeGuaranteeClaims;
5
5
  const viem_1 = require("viem");
6
6
  const errors_1 = require("./errors");
7
7
  const utils_1 = require("./utils");
8
+ const CLAIMS_ENCODED_BYTES = 32 * 10;
9
+ const WRAPPED_CLAIMS_BYTES = 32 * 2 + 32 + CLAIMS_ENCODED_BYTES;
8
10
  const CLAIM_TYPES = [
9
11
  { type: 'bytes32' },
10
12
  { type: 'uint256' },
@@ -24,6 +26,12 @@ function ensureDomainBytes(domain) {
24
26
  }
25
27
  return bytes;
26
28
  }
29
+ function normalizeHexBytes(data) {
30
+ if (typeof data === 'string') {
31
+ return (data.startsWith('0x') ? data : `0x${data}`);
32
+ }
33
+ return (0, utils_1.hexFromBytes)(data);
34
+ }
27
35
  function encodeGuaranteeClaims(claims) {
28
36
  if (claims.version !== 1) {
29
37
  throw new errors_1.VerificationError(`unsupported guarantee claims version: ${claims.version}`);
@@ -44,12 +52,26 @@ function encodeGuaranteeClaims(claims) {
44
52
  return (0, viem_1.encodeAbiParameters)([{ type: 'uint64' }, { type: 'bytes' }], [BigInt(claims.version), encoded]);
45
53
  }
46
54
  function decodeGuaranteeClaims(data) {
47
- const rawBytes = typeof data === 'string' ? (0, viem_1.toBytes)(data) : data;
48
- const [version, encoded] = (0, viem_1.decodeAbiParameters)([{ type: 'uint64' }, { type: 'bytes' }], rawBytes);
49
- if (version !== 1n) {
50
- throw new errors_1.VerificationError(`unsupported guarantee claims version: ${version}`);
55
+ const hex = normalizeHexBytes(data);
56
+ const byteLen = (hex.length - 2) / 2;
57
+ let encoded;
58
+ if (byteLen === CLAIMS_ENCODED_BYTES) {
59
+ encoded = hex;
60
+ }
61
+ else {
62
+ if (byteLen !== WRAPPED_CLAIMS_BYTES) {
63
+ throw new errors_1.VerificationError(`unexpected guarantee claims length: ${byteLen} bytes`);
64
+ }
65
+ const [version, wrapped] = (0, viem_1.decodeAbiParameters)([{ type: 'uint64' }, { type: 'bytes' }], hex);
66
+ if (version !== 1n) {
67
+ throw new errors_1.VerificationError(`unsupported guarantee claims version: ${version}`);
68
+ }
69
+ encoded = wrapped;
51
70
  }
52
71
  const [domain, tabId, reqId, user, recipient, amount, totalAmount, asset, timestamp, claimsVersion,] = (0, viem_1.decodeAbiParameters)(CLAIM_TYPES, encoded);
72
+ if (claimsVersion !== 1n) {
73
+ throw new errors_1.VerificationError(`unsupported guarantee claims version: ${claimsVersion}`);
74
+ }
53
75
  return {
54
76
  domain: (0, viem_1.toBytes)(domain),
55
77
  userAddress: user,
package/dist/http.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ export type FetchFn = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
2
+ type DecodeErrorFactory = (message: string, response: Response) => Error;
3
+ type HttpErrorFactory = (message: string, response: Response, body: unknown) => Error;
4
+ export declare function normalizeBaseUrl(endpoint: string): string;
5
+ export declare function extractErrorMessage(payload: unknown): string;
6
+ export declare function requestJson<T>(fetchFn: FetchFn, url: string, init: RequestInit, options: {
7
+ decodeError: DecodeErrorFactory;
8
+ httpError: HttpErrorFactory;
9
+ allowEmptyOk?: boolean;
10
+ }): Promise<T>;
11
+ export {};
package/dist/http.js ADDED
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeBaseUrl = normalizeBaseUrl;
4
+ exports.extractErrorMessage = extractErrorMessage;
5
+ exports.requestJson = requestJson;
6
+ function normalizeBaseUrl(endpoint) {
7
+ return endpoint.endsWith('/') ? endpoint.slice(0, -1) : endpoint;
8
+ }
9
+ function extractErrorMessage(payload) {
10
+ if (payload && typeof payload === 'object') {
11
+ const record = payload;
12
+ const error = record.error;
13
+ const msg = record.message;
14
+ return ((typeof error === 'string' && error) ||
15
+ (typeof msg === 'string' && msg) ||
16
+ JSON.stringify(record, (_k, v) => v));
17
+ }
18
+ if (typeof payload === 'string' && payload.trim()) {
19
+ return payload.trim();
20
+ }
21
+ return 'unknown error';
22
+ }
23
+ async function requestJson(fetchFn, url, init, options) {
24
+ const response = await fetchFn(url, init);
25
+ let text = '';
26
+ try {
27
+ text = await response.text();
28
+ }
29
+ catch (err) {
30
+ throw options.decodeError(`invalid response from ${response.url}: ${String(err)}`, response);
31
+ }
32
+ let payload = null;
33
+ let parsed = false;
34
+ let parseError;
35
+ if (text) {
36
+ try {
37
+ payload = JSON.parse(text);
38
+ parsed = true;
39
+ }
40
+ catch (err) {
41
+ payload = text;
42
+ parseError = err;
43
+ }
44
+ }
45
+ if (!response.ok) {
46
+ const message = `${response.status}: ${extractErrorMessage(payload)}`;
47
+ throw options.httpError(message, response, payload);
48
+ }
49
+ if (!text && !options.allowEmptyOk) {
50
+ throw options.decodeError(`invalid JSON response from ${response.url}: empty response body`, response);
51
+ }
52
+ if (text && !parsed) {
53
+ const detail = parseError instanceof Error ? parseError.message : String(parseError);
54
+ throw options.decodeError(`invalid JSON response from ${response.url}: ${detail}`, response);
55
+ }
56
+ return payload;
57
+ }
package/dist/index.d.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  export * from './errors';
2
+ export * from './constants';
2
3
  export * from './config';
3
4
  export * from './utils';
4
5
  export * from './models';
6
+ export * from './payment';
5
7
  export * from './signing';
6
8
  export * from './rpc';
7
9
  export * from './auth';
package/dist/index.js CHANGED
@@ -15,9 +15,11 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./errors"), exports);
18
+ __exportStar(require("./constants"), exports);
18
19
  __exportStar(require("./config"), exports);
19
20
  __exportStar(require("./utils"), exports);
20
21
  __exportStar(require("./models"), exports);
22
+ __exportStar(require("./payment"), exports);
21
23
  __exportStar(require("./signing"), exports);
22
24
  __exportStar(require("./rpc"), exports);
23
25
  __exportStar(require("./auth"), exports);
package/dist/models.d.ts CHANGED
@@ -1,11 +1,8 @@
1
+ export { ADMIN_API_KEY_HEADER, ADMIN_API_KEY_PREFIX, ADMIN_SCOPE_MANAGE_KEYS, ADMIN_SCOPE_SUSPEND_USERS, } from './constants';
1
2
  export declare enum SigningScheme {
2
3
  EIP712 = "eip712",
3
4
  EIP191 = "eip191"
4
5
  }
5
- export declare const ADMIN_API_KEY_HEADER = "x-api-key";
6
- export declare const ADMIN_API_KEY_PREFIX = "ak_";
7
- export declare const ADMIN_SCOPE_SUSPEND_USERS = "user_suspension:write";
8
- export declare const ADMIN_SCOPE_MANAGE_KEYS = "admin_api_keys:manage";
9
6
  export interface PaymentSignature {
10
7
  signature: string;
11
8
  scheme: SigningScheme;