@4mica/sdk 0.5.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.
Files changed (105) hide show
  1. package/.eslintrc.cjs +29 -0
  2. package/.github/workflows/ci.yml +31 -0
  3. package/.prettierignore +3 -0
  4. package/.prettierrc +6 -0
  5. package/LICENSE +21 -0
  6. package/README.md +444 -0
  7. package/dist/abi/core4mica.json +1605 -0
  8. package/dist/abi/erc20.json +187 -0
  9. package/dist/auth.d.ts +62 -0
  10. package/dist/auth.js +255 -0
  11. package/dist/bls.d.ts +5 -0
  12. package/dist/bls.js +58 -0
  13. package/dist/client.d.ts +58 -0
  14. package/dist/client.js +245 -0
  15. package/dist/config.d.ts +36 -0
  16. package/dist/config.js +123 -0
  17. package/dist/contract.d.ts +33 -0
  18. package/dist/contract.js +134 -0
  19. package/dist/errors.d.ts +43 -0
  20. package/dist/errors.js +62 -0
  21. package/dist/guarantee.d.ts +3 -0
  22. package/dist/guarantee.js +66 -0
  23. package/dist/index.d.ts +12 -0
  24. package/dist/index.js +28 -0
  25. package/dist/models.d.ts +150 -0
  26. package/dist/models.js +176 -0
  27. package/dist/rpc.d.ts +37 -0
  28. package/dist/rpc.js +163 -0
  29. package/dist/signing.d.ts +106 -0
  30. package/dist/signing.js +223 -0
  31. package/dist/src/abi/core4mica.json +1605 -0
  32. package/dist/src/abi/erc20.json +187 -0
  33. package/dist/src/bls.d.ts +5 -0
  34. package/dist/src/bls.js +45 -0
  35. package/dist/src/client.d.ts +55 -0
  36. package/dist/src/client.js +214 -0
  37. package/dist/src/config.d.ts +21 -0
  38. package/dist/src/config.js +76 -0
  39. package/dist/src/contract.d.ts +33 -0
  40. package/dist/src/contract.js +121 -0
  41. package/dist/src/errors.d.ts +17 -0
  42. package/dist/src/errors.js +31 -0
  43. package/dist/src/guarantee.d.ts +3 -0
  44. package/dist/src/guarantee.js +66 -0
  45. package/dist/src/index.d.ts +11 -0
  46. package/dist/src/index.js +27 -0
  47. package/dist/src/models.d.ts +119 -0
  48. package/dist/src/models.js +132 -0
  49. package/dist/src/rpc.d.ts +30 -0
  50. package/dist/src/rpc.js +122 -0
  51. package/dist/src/signing.d.ts +16 -0
  52. package/dist/src/signing.js +102 -0
  53. package/dist/src/utils.d.ts +8 -0
  54. package/dist/src/utils.js +78 -0
  55. package/dist/src/x402.d.ts +77 -0
  56. package/dist/src/x402.js +214 -0
  57. package/dist/tests/config.test.d.ts +1 -0
  58. package/dist/tests/config.test.js +26 -0
  59. package/dist/tests/guarantee.test.d.ts +1 -0
  60. package/dist/tests/guarantee.test.js +26 -0
  61. package/dist/tests/rpc.test.d.ts +1 -0
  62. package/dist/tests/rpc.test.js +44 -0
  63. package/dist/tests/signing.test.d.ts +1 -0
  64. package/dist/tests/signing.test.js +25 -0
  65. package/dist/tests/utils.test.d.ts +1 -0
  66. package/dist/tests/utils.test.js +25 -0
  67. package/dist/tests/x402.test.d.ts +1 -0
  68. package/dist/tests/x402.test.js +65 -0
  69. package/dist/utils.d.ts +8 -0
  70. package/dist/utils.js +78 -0
  71. package/dist/x402/index.d.ts +22 -0
  72. package/dist/x402/index.js +136 -0
  73. package/dist/x402/models.d.ts +80 -0
  74. package/dist/x402/models.js +2 -0
  75. package/dist/x402.d.ts +78 -0
  76. package/dist/x402.js +231 -0
  77. package/eslint.config.mjs +22 -0
  78. package/package.json +31 -0
  79. package/src/abi/core4mica.json +1605 -0
  80. package/src/abi/erc20.json +187 -0
  81. package/src/auth.ts +325 -0
  82. package/src/bls.ts +76 -0
  83. package/src/client.ts +347 -0
  84. package/src/config.ts +149 -0
  85. package/src/contract.ts +194 -0
  86. package/src/errors.ts +40 -0
  87. package/src/guarantee.ts +96 -0
  88. package/src/index.ts +12 -0
  89. package/src/models.ts +309 -0
  90. package/src/rpc.ts +225 -0
  91. package/src/signing.ts +330 -0
  92. package/src/utils.ts +75 -0
  93. package/src/x402/index.ts +192 -0
  94. package/src/x402/models.ts +94 -0
  95. package/tests/auth.integration.test.ts +97 -0
  96. package/tests/auth.test.ts +292 -0
  97. package/tests/config.test.ts +56 -0
  98. package/tests/guarantee.test.ts +26 -0
  99. package/tests/rpc.test.ts +76 -0
  100. package/tests/signing.test.ts +52 -0
  101. package/tests/utils.test.ts +35 -0
  102. package/tests/x402.test.ts +152 -0
  103. package/tsconfig.build.json +5 -0
  104. package/tsconfig.json +15 -0
  105. package/vitest.config.ts +12 -0
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.encodeGuaranteeClaims = encodeGuaranteeClaims;
4
+ exports.decodeGuaranteeClaims = decodeGuaranteeClaims;
5
+ const ethers_1 = require("ethers");
6
+ const errors_1 = require("./errors");
7
+ const utils_1 = require("./utils");
8
+ const CLAIM_TYPES = [
9
+ 'bytes32',
10
+ 'uint256',
11
+ 'uint256',
12
+ 'address',
13
+ 'address',
14
+ 'uint256',
15
+ 'uint256',
16
+ 'address',
17
+ 'uint64',
18
+ 'uint64',
19
+ ];
20
+ const coder = ethers_1.AbiCoder.defaultAbiCoder();
21
+ function ensureDomainBytes(domain) {
22
+ const bytes = typeof domain === 'string' ? (0, ethers_1.getBytes)(domain) : domain;
23
+ if (bytes.length !== 32) {
24
+ throw new errors_1.VerificationError('domain separator must be 32 bytes');
25
+ }
26
+ return bytes;
27
+ }
28
+ function encodeGuaranteeClaims(claims) {
29
+ if (claims.version !== 1) {
30
+ throw new errors_1.VerificationError(`unsupported guarantee claims version: ${claims.version}`);
31
+ }
32
+ const domain = ensureDomainBytes(claims.domain);
33
+ const encoded = coder.encode(CLAIM_TYPES, [
34
+ domain,
35
+ (0, utils_1.parseU256)(claims.tabId),
36
+ (0, utils_1.parseU256)(claims.reqId),
37
+ claims.userAddress,
38
+ claims.recipientAddress,
39
+ (0, utils_1.parseU256)(claims.amount),
40
+ (0, utils_1.parseU256)(claims.totalAmount),
41
+ claims.assetAddress,
42
+ BigInt(claims.timestamp),
43
+ BigInt(claims.version),
44
+ ]);
45
+ return coder.encode(['uint64', 'bytes'], [BigInt(claims.version), encoded]);
46
+ }
47
+ function decodeGuaranteeClaims(data) {
48
+ const rawBytes = typeof data === 'string' ? (0, ethers_1.getBytes)(data) : data;
49
+ const [version, encoded] = coder.decode(['uint64', 'bytes'], rawBytes);
50
+ if (version !== 1n) {
51
+ throw new errors_1.VerificationError(`unsupported guarantee claims version: ${version}`);
52
+ }
53
+ const [domain, tabId, reqId, user, recipient, amount, totalAmount, asset, timestamp, claimsVersion,] = coder.decode(CLAIM_TYPES, encoded);
54
+ return {
55
+ domain: (0, ethers_1.getBytes)(domain),
56
+ userAddress: user,
57
+ recipientAddress: recipient,
58
+ tabId: (0, utils_1.parseU256)(tabId),
59
+ reqId: (0, utils_1.parseU256)(reqId),
60
+ amount: (0, utils_1.parseU256)(amount),
61
+ totalAmount: (0, utils_1.parseU256)(totalAmount),
62
+ assetAddress: asset,
63
+ timestamp: Number(timestamp),
64
+ version: Number(claimsVersion),
65
+ };
66
+ }
@@ -0,0 +1,12 @@
1
+ export * from './errors';
2
+ export * from './config';
3
+ export * from './utils';
4
+ export * from './models';
5
+ export * from './signing';
6
+ export * from './rpc';
7
+ export * from './auth';
8
+ export * from './contract';
9
+ export * from './guarantee';
10
+ export * from './bls';
11
+ export * from './x402/index';
12
+ export * from './client';
package/dist/index.js ADDED
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./errors"), exports);
18
+ __exportStar(require("./config"), exports);
19
+ __exportStar(require("./utils"), exports);
20
+ __exportStar(require("./models"), exports);
21
+ __exportStar(require("./signing"), exports);
22
+ __exportStar(require("./rpc"), exports);
23
+ __exportStar(require("./auth"), exports);
24
+ __exportStar(require("./contract"), exports);
25
+ __exportStar(require("./guarantee"), exports);
26
+ __exportStar(require("./bls"), exports);
27
+ __exportStar(require("./x402/index"), exports);
28
+ __exportStar(require("./client"), exports);
@@ -0,0 +1,150 @@
1
+ export declare enum SigningScheme {
2
+ EIP712 = "eip712",
3
+ EIP191 = "eip191"
4
+ }
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
+ export interface PaymentSignature {
10
+ signature: string;
11
+ scheme: SigningScheme;
12
+ }
13
+ export declare class PaymentGuaranteeRequestClaims {
14
+ userAddress: string;
15
+ recipientAddress: string;
16
+ tabId: bigint;
17
+ reqId: bigint;
18
+ amount: bigint;
19
+ timestamp: number;
20
+ assetAddress: string;
21
+ constructor(init: {
22
+ userAddress: string;
23
+ recipientAddress: string;
24
+ tabId: bigint;
25
+ reqId?: bigint;
26
+ amount: bigint;
27
+ timestamp: number;
28
+ assetAddress: string;
29
+ });
30
+ static new(userAddress: string, recipientAddress: string, tabId: number | bigint | string, amount: number | bigint | string, timestamp: number, erc20Token?: string | null, reqId?: number | bigint | string): PaymentGuaranteeRequestClaims;
31
+ }
32
+ export interface PaymentGuaranteeClaims {
33
+ domain: Uint8Array;
34
+ userAddress: string;
35
+ recipientAddress: string;
36
+ tabId: bigint;
37
+ reqId: bigint;
38
+ amount: bigint;
39
+ totalAmount: bigint;
40
+ assetAddress: string;
41
+ timestamp: number;
42
+ version: number;
43
+ }
44
+ export interface BLSCert {
45
+ claims: string;
46
+ signature: string;
47
+ }
48
+ export interface TabPaymentStatus {
49
+ paid: bigint;
50
+ remunerated: boolean;
51
+ asset: string;
52
+ }
53
+ export interface UserInfo {
54
+ asset: string;
55
+ collateral: bigint;
56
+ withdrawalRequestAmount: bigint;
57
+ withdrawalRequestTimestamp: number;
58
+ }
59
+ export declare class UserSuspensionStatus {
60
+ userAddress: string;
61
+ suspended: boolean;
62
+ updatedAt: number;
63
+ constructor(userAddress: string, suspended: boolean, updatedAt: number);
64
+ static fromRpc(raw: Record<string, unknown>): UserSuspensionStatus;
65
+ }
66
+ export declare class AdminApiKeyInfo {
67
+ id: string;
68
+ name: string;
69
+ scopes: string[];
70
+ createdAt: number;
71
+ revokedAt?: number | null | undefined;
72
+ constructor(id: string, name: string, scopes: string[], createdAt: number, revokedAt?: number | null | undefined);
73
+ static fromRpc(raw: Record<string, unknown>): AdminApiKeyInfo;
74
+ }
75
+ export declare class AdminApiKeySecret {
76
+ id: string;
77
+ name: string;
78
+ scopes: string[];
79
+ createdAt: number;
80
+ apiKey: string;
81
+ constructor(id: string, name: string, scopes: string[], createdAt: number, apiKey: string);
82
+ static fromRpc(raw: Record<string, unknown>): AdminApiKeySecret;
83
+ }
84
+ export declare class TabInfo {
85
+ tabId: bigint;
86
+ userAddress: string;
87
+ recipientAddress: string;
88
+ assetAddress: string;
89
+ startTimestamp: number;
90
+ ttlSeconds: number;
91
+ status: string;
92
+ settlementStatus: string;
93
+ createdAt: number;
94
+ updatedAt: number;
95
+ constructor(tabId: bigint, userAddress: string, recipientAddress: string, assetAddress: string, startTimestamp: number, ttlSeconds: number, status: string, settlementStatus: string, createdAt: number, updatedAt: number);
96
+ static fromRpc(raw: Record<string, unknown>): TabInfo;
97
+ }
98
+ export declare class GuaranteeInfo {
99
+ tabId: bigint;
100
+ reqId: bigint;
101
+ fromAddress: string;
102
+ toAddress: string;
103
+ assetAddress: string;
104
+ amount: bigint;
105
+ timestamp: number;
106
+ certificate?: string | null | undefined;
107
+ constructor(tabId: bigint, reqId: bigint, fromAddress: string, toAddress: string, assetAddress: string, amount: bigint, timestamp: number, certificate?: string | null | undefined);
108
+ static fromRpc(raw: Record<string, unknown>): GuaranteeInfo;
109
+ }
110
+ export declare class PendingRemunerationInfo {
111
+ tab: TabInfo;
112
+ latestGuarantee?: (GuaranteeInfo | null) | undefined;
113
+ constructor(tab: TabInfo, latestGuarantee?: (GuaranteeInfo | null) | undefined);
114
+ static fromRpc(raw: Record<string, unknown>): PendingRemunerationInfo;
115
+ }
116
+ export declare class CollateralEventInfo {
117
+ id: string;
118
+ userAddress: string;
119
+ assetAddress: string;
120
+ amount: bigint;
121
+ eventType: string;
122
+ tabId?: bigint | null | undefined;
123
+ reqId?: bigint | null | undefined;
124
+ txId?: string | null | undefined;
125
+ createdAt: number;
126
+ constructor(id: string, userAddress: string, assetAddress: string, amount: bigint, eventType: string, tabId?: bigint | null | undefined, reqId?: bigint | null | undefined, txId?: string | null | undefined, createdAt?: number);
127
+ static fromRpc(raw: Record<string, unknown>): CollateralEventInfo;
128
+ }
129
+ export declare class AssetBalanceInfo {
130
+ userAddress: string;
131
+ assetAddress: string;
132
+ total: bigint;
133
+ locked: bigint;
134
+ version: number;
135
+ updatedAt: number;
136
+ constructor(userAddress: string, assetAddress: string, total: bigint, locked: bigint, version: number, updatedAt: number);
137
+ static fromRpc(raw: Record<string, unknown>): AssetBalanceInfo;
138
+ }
139
+ export declare class RecipientPaymentInfo {
140
+ userAddress: string;
141
+ recipientAddress: string;
142
+ txHash: string;
143
+ amount: bigint;
144
+ verified: boolean;
145
+ finalized: boolean;
146
+ failed: boolean;
147
+ createdAt: number;
148
+ constructor(userAddress: string, recipientAddress: string, txHash: string, amount: bigint, verified: boolean, finalized: boolean, failed: boolean, createdAt: number);
149
+ static fromRpc(raw: Record<string, unknown>): RecipientPaymentInfo;
150
+ }
package/dist/models.js ADDED
@@ -0,0 +1,176 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RecipientPaymentInfo = exports.AssetBalanceInfo = exports.CollateralEventInfo = exports.PendingRemunerationInfo = exports.GuaranteeInfo = exports.TabInfo = exports.AdminApiKeySecret = exports.AdminApiKeyInfo = exports.UserSuspensionStatus = exports.PaymentGuaranteeRequestClaims = exports.ADMIN_SCOPE_MANAGE_KEYS = exports.ADMIN_SCOPE_SUSPEND_USERS = exports.ADMIN_API_KEY_PREFIX = exports.ADMIN_API_KEY_HEADER = exports.SigningScheme = void 0;
4
+ const utils_1 = require("./utils");
5
+ var SigningScheme;
6
+ (function (SigningScheme) {
7
+ SigningScheme["EIP712"] = "eip712";
8
+ SigningScheme["EIP191"] = "eip191";
9
+ })(SigningScheme || (exports.SigningScheme = SigningScheme = {}));
10
+ exports.ADMIN_API_KEY_HEADER = 'x-api-key';
11
+ exports.ADMIN_API_KEY_PREFIX = 'ak_';
12
+ exports.ADMIN_SCOPE_SUSPEND_USERS = 'user_suspension:write';
13
+ exports.ADMIN_SCOPE_MANAGE_KEYS = 'admin_api_keys:manage';
14
+ class PaymentGuaranteeRequestClaims {
15
+ constructor(init) {
16
+ this.userAddress = init.userAddress;
17
+ this.recipientAddress = init.recipientAddress;
18
+ this.tabId = init.tabId;
19
+ this.reqId = init.reqId ?? 0n;
20
+ this.amount = init.amount;
21
+ this.timestamp = init.timestamp;
22
+ this.assetAddress = init.assetAddress;
23
+ }
24
+ static new(userAddress, recipientAddress, tabId, amount, timestamp, erc20Token, reqId) {
25
+ const asset = erc20Token ?? '0x0000000000000000000000000000000000000000';
26
+ return new PaymentGuaranteeRequestClaims({
27
+ userAddress: (0, utils_1.normalizeAddress)(userAddress),
28
+ recipientAddress: (0, utils_1.normalizeAddress)(recipientAddress),
29
+ tabId: (0, utils_1.parseU256)(tabId),
30
+ reqId: reqId !== undefined ? (0, utils_1.parseU256)(reqId) : 0n,
31
+ amount: (0, utils_1.parseU256)(amount),
32
+ timestamp: Number(timestamp),
33
+ assetAddress: (0, utils_1.normalizeAddress)(asset),
34
+ });
35
+ }
36
+ }
37
+ exports.PaymentGuaranteeRequestClaims = PaymentGuaranteeRequestClaims;
38
+ class UserSuspensionStatus {
39
+ constructor(userAddress, suspended, updatedAt) {
40
+ this.userAddress = userAddress;
41
+ this.suspended = suspended;
42
+ this.updatedAt = updatedAt;
43
+ }
44
+ static fromRpc(raw) {
45
+ return new UserSuspensionStatus((getAny(raw, 'user_address', 'userAddress') ?? ''), Boolean(getAny(raw, 'suspended')), Number(getAny(raw, 'updated_at', 'updatedAt') ?? 0));
46
+ }
47
+ }
48
+ exports.UserSuspensionStatus = UserSuspensionStatus;
49
+ class AdminApiKeyInfo {
50
+ constructor(id, name, scopes, createdAt, revokedAt) {
51
+ this.id = id;
52
+ this.name = name;
53
+ this.scopes = scopes;
54
+ this.createdAt = createdAt;
55
+ this.revokedAt = revokedAt;
56
+ }
57
+ static fromRpc(raw) {
58
+ const revoked = getAny(raw, 'revoked_at', 'revokedAt');
59
+ return new AdminApiKeyInfo((getAny(raw, 'id') ?? ''), (getAny(raw, 'name') ?? ''), (getAny(raw, 'scopes') ?? []).map(String), Number(getAny(raw, 'created_at', 'createdAt') ?? 0), revoked === undefined || revoked === null ? null : Number(revoked));
60
+ }
61
+ }
62
+ exports.AdminApiKeyInfo = AdminApiKeyInfo;
63
+ class AdminApiKeySecret {
64
+ constructor(id, name, scopes, createdAt, apiKey) {
65
+ this.id = id;
66
+ this.name = name;
67
+ this.scopes = scopes;
68
+ this.createdAt = createdAt;
69
+ this.apiKey = apiKey;
70
+ }
71
+ static fromRpc(raw) {
72
+ return new AdminApiKeySecret((getAny(raw, 'id') ?? ''), (getAny(raw, 'name') ?? ''), (getAny(raw, 'scopes') ?? []).map(String), Number(getAny(raw, 'created_at', 'createdAt') ?? 0), (getAny(raw, 'api_key', 'apiKey') ?? ''));
73
+ }
74
+ }
75
+ exports.AdminApiKeySecret = AdminApiKeySecret;
76
+ function getAny(raw, ...keys) {
77
+ for (const key of keys) {
78
+ if (key in raw)
79
+ return raw[key];
80
+ }
81
+ return undefined;
82
+ }
83
+ class TabInfo {
84
+ constructor(tabId, userAddress, recipientAddress, assetAddress, startTimestamp, ttlSeconds, status, settlementStatus, createdAt, updatedAt) {
85
+ this.tabId = tabId;
86
+ this.userAddress = userAddress;
87
+ this.recipientAddress = recipientAddress;
88
+ this.assetAddress = assetAddress;
89
+ this.startTimestamp = startTimestamp;
90
+ this.ttlSeconds = ttlSeconds;
91
+ this.status = status;
92
+ this.settlementStatus = settlementStatus;
93
+ this.createdAt = createdAt;
94
+ this.updatedAt = updatedAt;
95
+ }
96
+ static fromRpc(raw) {
97
+ return new TabInfo((0, utils_1.parseU256)((getAny(raw, 'tab_id', 'tabId') ?? 0)), (getAny(raw, 'user_address', 'userAddress') ?? ''), (getAny(raw, 'recipient_address', 'recipientAddress') ?? ''), (getAny(raw, 'asset_address', 'assetAddress') ?? ''), Number(getAny(raw, 'start_timestamp', 'startTimestamp')), Number(getAny(raw, 'ttl_seconds', 'ttlSeconds')), (getAny(raw, 'status') ?? ''), (getAny(raw, 'settlement_status', 'settlementStatus') ?? ''), Number(getAny(raw, 'created_at', 'createdAt')), Number(getAny(raw, 'updated_at', 'updatedAt')));
98
+ }
99
+ }
100
+ exports.TabInfo = TabInfo;
101
+ class GuaranteeInfo {
102
+ constructor(tabId, reqId, fromAddress, toAddress, assetAddress, amount, timestamp, certificate) {
103
+ this.tabId = tabId;
104
+ this.reqId = reqId;
105
+ this.fromAddress = fromAddress;
106
+ this.toAddress = toAddress;
107
+ this.assetAddress = assetAddress;
108
+ this.amount = amount;
109
+ this.timestamp = timestamp;
110
+ this.certificate = certificate;
111
+ }
112
+ static fromRpc(raw) {
113
+ return new GuaranteeInfo((0, utils_1.parseU256)((getAny(raw, 'tab_id', 'tabId') ?? 0)), (0, utils_1.parseU256)((getAny(raw, 'req_id', 'reqId') ?? 0)), (getAny(raw, 'from_address', 'fromAddress') ?? ''), (getAny(raw, 'to_address', 'toAddress') ?? ''), (getAny(raw, 'asset_address', 'assetAddress') ?? ''), (0, utils_1.parseU256)((getAny(raw, 'amount') ?? 0)), Number(getAny(raw, 'start_timestamp', 'startTimestamp', 'timestamp') ?? 0), getAny(raw, 'certificate'));
114
+ }
115
+ }
116
+ exports.GuaranteeInfo = GuaranteeInfo;
117
+ class PendingRemunerationInfo {
118
+ constructor(tab, latestGuarantee) {
119
+ this.tab = tab;
120
+ this.latestGuarantee = latestGuarantee;
121
+ }
122
+ static fromRpc(raw) {
123
+ const latest = getAny(raw, 'latest_guarantee', 'latestGuarantee');
124
+ return new PendingRemunerationInfo(TabInfo.fromRpc(getAny(raw, 'tab') ?? {}), latest ? GuaranteeInfo.fromRpc(latest) : null);
125
+ }
126
+ }
127
+ exports.PendingRemunerationInfo = PendingRemunerationInfo;
128
+ class CollateralEventInfo {
129
+ constructor(id, userAddress, assetAddress, amount, eventType, tabId, reqId, txId, createdAt = 0) {
130
+ this.id = id;
131
+ this.userAddress = userAddress;
132
+ this.assetAddress = assetAddress;
133
+ this.amount = amount;
134
+ this.eventType = eventType;
135
+ this.tabId = tabId;
136
+ this.reqId = reqId;
137
+ this.txId = txId;
138
+ this.createdAt = createdAt;
139
+ }
140
+ static fromRpc(raw) {
141
+ const tabId = getAny(raw, 'tab_id', 'tabId');
142
+ const reqId = getAny(raw, 'req_id', 'reqId');
143
+ return new CollateralEventInfo((getAny(raw, 'id') ?? ''), (getAny(raw, 'user_address', 'userAddress') ?? ''), (getAny(raw, 'asset_address', 'assetAddress') ?? ''), (0, utils_1.parseU256)((getAny(raw, 'amount') ?? 0)), (getAny(raw, 'event_type', 'eventType') ?? ''), tabId !== undefined && tabId !== null ? (0, utils_1.parseU256)(tabId) : null, reqId !== undefined && reqId !== null ? (0, utils_1.parseU256)(reqId) : null, getAny(raw, 'tx_id', 'txId'), Number(getAny(raw, 'created_at', 'createdAt') ?? 0));
144
+ }
145
+ }
146
+ exports.CollateralEventInfo = CollateralEventInfo;
147
+ class AssetBalanceInfo {
148
+ constructor(userAddress, assetAddress, total, locked, version, updatedAt) {
149
+ this.userAddress = userAddress;
150
+ this.assetAddress = assetAddress;
151
+ this.total = total;
152
+ this.locked = locked;
153
+ this.version = version;
154
+ this.updatedAt = updatedAt;
155
+ }
156
+ static fromRpc(raw) {
157
+ return new AssetBalanceInfo((getAny(raw, 'user_address', 'userAddress') ?? ''), (getAny(raw, 'asset_address', 'assetAddress') ?? ''), (0, utils_1.parseU256)((getAny(raw, 'total') ?? 0)), (0, utils_1.parseU256)((getAny(raw, 'locked') ?? 0)), Number(getAny(raw, 'version') ?? 0), Number(getAny(raw, 'updated_at', 'updatedAt') ?? 0));
158
+ }
159
+ }
160
+ exports.AssetBalanceInfo = AssetBalanceInfo;
161
+ class RecipientPaymentInfo {
162
+ constructor(userAddress, recipientAddress, txHash, amount, verified, finalized, failed, createdAt) {
163
+ this.userAddress = userAddress;
164
+ this.recipientAddress = recipientAddress;
165
+ this.txHash = txHash;
166
+ this.amount = amount;
167
+ this.verified = verified;
168
+ this.finalized = finalized;
169
+ this.failed = failed;
170
+ this.createdAt = createdAt;
171
+ }
172
+ static fromRpc(raw) {
173
+ return new RecipientPaymentInfo((getAny(raw, 'user_address', 'userAddress') ?? ''), (getAny(raw, 'recipient_address', 'recipientAddress') ?? ''), (getAny(raw, 'tx_hash', 'txHash') ?? ''), (0, utils_1.parseU256)((getAny(raw, 'amount') ?? 0)), Boolean(getAny(raw, 'verified')), Boolean(getAny(raw, 'finalized')), Boolean(getAny(raw, 'failed')), Number(getAny(raw, 'created_at', 'createdAt') ?? 0));
174
+ }
175
+ }
176
+ exports.RecipientPaymentInfo = RecipientPaymentInfo;
package/dist/rpc.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { AdminApiKeyInfo, AdminApiKeySecret, UserSuspensionStatus } from './models';
2
+ import { CorePublicParameters } from './signing';
3
+ export type FetchFn = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
4
+ export type BearerTokenProvider = () => string | Promise<string>;
5
+ export declare class RpcProxy {
6
+ private baseUrl;
7
+ private adminApiKey?;
8
+ private bearerToken?;
9
+ private bearerTokenProvider?;
10
+ private fetchFn;
11
+ constructor(endpoint: string, adminApiKey?: string, fetchFn?: FetchFn);
12
+ aclose(): Promise<void>;
13
+ withBearerToken(token: string): RpcProxy;
14
+ withTokenProvider(provider: BearerTokenProvider): RpcProxy;
15
+ private headers;
16
+ private resolveBearerToken;
17
+ private decode;
18
+ private get;
19
+ private post;
20
+ getPublicParams(): Promise<CorePublicParameters>;
21
+ issueGuarantee(body: Record<string, unknown>): Promise<Record<string, unknown>>;
22
+ createPaymentTab(body: Record<string, unknown>): Promise<Record<string, unknown>>;
23
+ listSettledTabs(recipientAddress: string): Promise<Record<string, unknown>[]>;
24
+ listPendingRemunerations(recipientAddress: string): Promise<Record<string, unknown>[]>;
25
+ getTab(tabId: number | bigint): Promise<Record<string, unknown> | null>;
26
+ listRecipientTabs(recipientAddress: string, settlementStatuses?: string[]): Promise<Record<string, unknown>[]>;
27
+ getTabGuarantees(tabId: number | bigint): Promise<Record<string, unknown>[]>;
28
+ getLatestGuarantee(tabId: number | bigint): Promise<Record<string, unknown> | null>;
29
+ getGuarantee(tabId: number | bigint, reqId: number | bigint): Promise<Record<string, unknown> | null>;
30
+ listRecipientPayments(recipientAddress: string): Promise<Record<string, unknown>[]>;
31
+ getCollateralEventsForTab(tabId: number | bigint): Promise<Record<string, unknown>[]>;
32
+ getUserAssetBalance(userAddress: string, assetAddress: string): Promise<Record<string, unknown> | null>;
33
+ updateUserSuspension(userAddress: string, suspended: boolean): Promise<UserSuspensionStatus>;
34
+ createAdminApiKey(body: Record<string, unknown>): Promise<AdminApiKeySecret>;
35
+ listAdminApiKeys(): Promise<AdminApiKeyInfo[]>;
36
+ revokeAdminApiKey(keyId: string): Promise<AdminApiKeyInfo>;
37
+ }
package/dist/rpc.js ADDED
@@ -0,0 +1,163 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RpcProxy = void 0;
4
+ const models_1 = require("./models");
5
+ const signing_1 = require("./signing");
6
+ const errors_1 = require("./errors");
7
+ function serializeTabId(tabId) {
8
+ return `0x${BigInt(tabId).toString(16)}`;
9
+ }
10
+ class RpcProxy {
11
+ constructor(endpoint, adminApiKey, fetchFn = fetch) {
12
+ this.baseUrl = endpoint.endsWith('/') ? endpoint.slice(0, -1) : endpoint;
13
+ this.adminApiKey = adminApiKey;
14
+ this.fetchFn = fetchFn;
15
+ }
16
+ async aclose() {
17
+ // no-op for symmetry with Python SDK
18
+ }
19
+ withBearerToken(token) {
20
+ this.bearerToken = token;
21
+ return this;
22
+ }
23
+ withTokenProvider(provider) {
24
+ this.bearerTokenProvider = provider;
25
+ return this;
26
+ }
27
+ async headers() {
28
+ const headers = {};
29
+ if (this.adminApiKey) {
30
+ headers[models_1.ADMIN_API_KEY_HEADER] = this.adminApiKey;
31
+ }
32
+ const token = await this.resolveBearerToken();
33
+ if (token) {
34
+ headers['Authorization'] = token;
35
+ }
36
+ return headers;
37
+ }
38
+ async resolveBearerToken() {
39
+ let token = this.bearerToken;
40
+ if (!token && this.bearerTokenProvider) {
41
+ token = await this.bearerTokenProvider();
42
+ }
43
+ if (!token) {
44
+ return undefined;
45
+ }
46
+ const trimmed = token.trim();
47
+ if (/^bearer\s+/i.test(trimmed)) {
48
+ return trimmed;
49
+ }
50
+ return `Bearer ${trimmed}`;
51
+ }
52
+ async decode(response) {
53
+ let payload;
54
+ try {
55
+ payload = await response.json();
56
+ }
57
+ catch (err) {
58
+ if (response.ok) {
59
+ throw new errors_1.RpcError(`invalid JSON response from ${response.url}: ${String(err)}`);
60
+ }
61
+ payload = await response.text();
62
+ }
63
+ if (response.ok) {
64
+ return payload;
65
+ }
66
+ let message = 'unknown error';
67
+ if (payload && typeof payload === 'object') {
68
+ const record = payload;
69
+ const error = record.error;
70
+ const msg = record.message;
71
+ message =
72
+ (typeof error === 'string' && error) ||
73
+ (typeof msg === 'string' && msg) ||
74
+ JSON.stringify(record, (_k, v) => v);
75
+ }
76
+ else if (typeof payload === 'string' && payload.trim()) {
77
+ message = payload.trim();
78
+ }
79
+ throw new errors_1.RpcError(`${response.status}: ${message}`, {
80
+ status: response.status,
81
+ body: payload,
82
+ });
83
+ }
84
+ async get(path) {
85
+ const resp = await this.fetchFn(`${this.baseUrl}${path}`, {
86
+ headers: await this.headers(),
87
+ method: 'GET',
88
+ });
89
+ return this.decode(resp);
90
+ }
91
+ async post(path, body) {
92
+ const resp = await this.fetchFn(`${this.baseUrl}${path}`, {
93
+ headers: { 'content-type': 'application/json', ...(await this.headers()) },
94
+ method: 'POST',
95
+ body: JSON.stringify(body),
96
+ });
97
+ return this.decode(resp);
98
+ }
99
+ async getPublicParams() {
100
+ const data = await this.get('/core/public-params');
101
+ return signing_1.CorePublicParameters.fromRpc(data);
102
+ }
103
+ async issueGuarantee(body) {
104
+ return this.post('/core/guarantees', body);
105
+ }
106
+ async createPaymentTab(body) {
107
+ return this.post('/core/payment-tabs', body);
108
+ }
109
+ async listSettledTabs(recipientAddress) {
110
+ return this.get(`/core/recipients/${recipientAddress}/settled-tabs`);
111
+ }
112
+ async listPendingRemunerations(recipientAddress) {
113
+ return this.get(`/core/recipients/${recipientAddress}/pending-remunerations`);
114
+ }
115
+ async getTab(tabId) {
116
+ return this.get(`/core/tabs/${serializeTabId(tabId)}`);
117
+ }
118
+ async listRecipientTabs(recipientAddress, settlementStatuses) {
119
+ let query = '';
120
+ if (settlementStatuses?.length) {
121
+ query =
122
+ '?' + settlementStatuses.map((s) => `settlement_status=${encodeURIComponent(s)}`).join('&');
123
+ }
124
+ return this.get(`/core/recipients/${recipientAddress}/tabs${query}`);
125
+ }
126
+ async getTabGuarantees(tabId) {
127
+ return this.get(`/core/tabs/${serializeTabId(tabId)}/guarantees`);
128
+ }
129
+ async getLatestGuarantee(tabId) {
130
+ return this.get(`/core/tabs/${serializeTabId(tabId)}/guarantees/latest`);
131
+ }
132
+ async getGuarantee(tabId, reqId) {
133
+ return this.get(`/core/tabs/${serializeTabId(tabId)}/guarantees/${reqId}`);
134
+ }
135
+ async listRecipientPayments(recipientAddress) {
136
+ return this.get(`/core/recipients/${recipientAddress}/payments`);
137
+ }
138
+ async getCollateralEventsForTab(tabId) {
139
+ return this.get(`/core/tabs/${serializeTabId(tabId)}/collateral-events`);
140
+ }
141
+ async getUserAssetBalance(userAddress, assetAddress) {
142
+ return this.get(`/core/users/${userAddress}/assets/${assetAddress}`);
143
+ }
144
+ async updateUserSuspension(userAddress, suspended) {
145
+ const data = await this.post(`/core/users/${userAddress}/suspension`, {
146
+ suspended,
147
+ });
148
+ return models_1.UserSuspensionStatus.fromRpc(data);
149
+ }
150
+ async createAdminApiKey(body) {
151
+ const data = await this.post('/core/admin/api-keys', body);
152
+ return models_1.AdminApiKeySecret.fromRpc(data);
153
+ }
154
+ async listAdminApiKeys() {
155
+ const data = await this.get('/core/admin/api-keys');
156
+ return data.map((entry) => models_1.AdminApiKeyInfo.fromRpc(entry));
157
+ }
158
+ async revokeAdminApiKey(keyId) {
159
+ const data = await this.post(`/core/admin/api-keys/${keyId}/revoke`, {});
160
+ return models_1.AdminApiKeyInfo.fromRpc(data);
161
+ }
162
+ }
163
+ exports.RpcProxy = RpcProxy;