@amadeus-protocol/wallet-sdk 0.1.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/README.md +73 -0
- package/dist/binary.d.ts +30 -0
- package/dist/binary.d.ts.map +1 -0
- package/dist/binary.js +56 -0
- package/dist/binary.js.map +1 -0
- package/dist/bytes.d.ts +20 -0
- package/dist/bytes.d.ts.map +1 -0
- package/dist/bytes.js +48 -0
- package/dist/bytes.js.map +1 -0
- package/dist/client/injected.d.ts +41 -0
- package/dist/client/injected.d.ts.map +1 -0
- package/dist/client/injected.js +87 -0
- package/dist/client/injected.js.map +1 -0
- package/dist/constants.d.ts +70 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/constants.js +82 -0
- package/dist/constants.js.map +1 -0
- package/dist/crypto/apikey.d.ts +72 -0
- package/dist/crypto/apikey.d.ts.map +1 -0
- package/dist/crypto/apikey.js +109 -0
- package/dist/crypto/apikey.js.map +1 -0
- package/dist/crypto/bls.d.ts +31 -0
- package/dist/crypto/bls.d.ts.map +1 -0
- package/dist/crypto/bls.js +65 -0
- package/dist/crypto/bls.js.map +1 -0
- package/dist/crypto/box.d.ts +43 -0
- package/dist/crypto/box.d.ts.map +1 -0
- package/dist/crypto/box.js +82 -0
- package/dist/crypto/box.js.map +1 -0
- package/dist/crypto/connect.d.ts +59 -0
- package/dist/crypto/connect.d.ts.map +1 -0
- package/dist/crypto/connect.js +72 -0
- package/dist/crypto/connect.js.map +1 -0
- package/dist/errors.d.ts +10 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +14 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +18 -0
- package/dist/react/index.d.ts +20 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.js +95 -0
- package/dist/react/index.js.map +1 -0
- package/dist/schema.d.ts +63 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +52 -0
- package/dist/schema.js.map +1 -0
- package/dist/transport/bridge.d.ts +82 -0
- package/dist/transport/bridge.d.ts.map +1 -0
- package/dist/transport/bridge.js +125 -0
- package/dist/transport/bridge.js.map +1 -0
- package/dist/transport/envelope.d.ts +73 -0
- package/dist/transport/envelope.d.ts.map +1 -0
- package/dist/transport/envelope.js +123 -0
- package/dist/transport/envelope.js.map +1 -0
- package/dist/transport/session.d.ts +70 -0
- package/dist/transport/session.d.ts.map +1 -0
- package/dist/transport/session.js +119 -0
- package/dist/transport/session.js.map +1 -0
- package/dist/transport/uri.d.ts +49 -0
- package/dist/transport/uri.d.ts.map +1 -0
- package/dist/transport/uri.js +101 -0
- package/dist/transport/uri.js.map +1 -0
- package/dist/tx.d.ts +42 -0
- package/dist/tx.d.ts.map +1 -0
- package/dist/tx.js +61 -0
- package/dist/tx.js.map +1 -0
- package/dist/types.d.ts +80 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +14 -0
- package/dist/types.js.map +1 -0
- package/dist/wallet/handler.d.ts +18 -0
- package/dist/wallet/handler.d.ts.map +1 -0
- package/dist/wallet/handler.js +79 -0
- package/dist/wallet/handler.js.map +1 -0
- package/package.json +92 -0
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import "../constants.js";
|
|
2
|
+
import { WalletSdkError } from "../errors.js";
|
|
3
|
+
import { bytesToUtf8, utf8ToBytes } from "../bytes.js";
|
|
4
|
+
import { open, seal } from "../crypto/box.js";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
//#region src/transport/envelope.ts
|
|
7
|
+
/**
|
|
8
|
+
* The encrypted request/response envelope that flows over ANY transport (deep
|
|
9
|
+
* link, QR, or the cross-device bridge). Post-connect, both sides hold the x25519
|
|
10
|
+
* shared key, so every request and response is sealed — even same-device deep
|
|
11
|
+
* links carry ciphertext, so a hijacked scheme yields an unusable blob.
|
|
12
|
+
*
|
|
13
|
+
* Methods mirror the wallet extension's provider vocabulary so a dApp integrates
|
|
14
|
+
* once against the same names on every transport.
|
|
15
|
+
*/
|
|
16
|
+
const WALLET_METHODS = [
|
|
17
|
+
"amadeus_signTransaction",
|
|
18
|
+
"amadeus_signMessage",
|
|
19
|
+
"amadeus_getAccounts",
|
|
20
|
+
"amadeus_generateApiKey",
|
|
21
|
+
"amadeus_switchNetwork"
|
|
22
|
+
];
|
|
23
|
+
const walletRequestSchema = z.object({
|
|
24
|
+
v: z.number().int(),
|
|
25
|
+
id: z.string().min(1).max(128),
|
|
26
|
+
method: z.enum(WALLET_METHODS),
|
|
27
|
+
origin: z.string().min(1),
|
|
28
|
+
params: z.unknown(),
|
|
29
|
+
exp: z.number().int()
|
|
30
|
+
});
|
|
31
|
+
const walletResponseSchema = z.union([z.object({
|
|
32
|
+
v: z.number().int(),
|
|
33
|
+
id: z.string().min(1).max(128),
|
|
34
|
+
ok: z.literal(true),
|
|
35
|
+
result: z.unknown()
|
|
36
|
+
}), z.object({
|
|
37
|
+
v: z.number().int(),
|
|
38
|
+
id: z.string().min(1).max(128),
|
|
39
|
+
ok: z.literal(false),
|
|
40
|
+
error: z.object({
|
|
41
|
+
code: z.string(),
|
|
42
|
+
message: z.string()
|
|
43
|
+
})
|
|
44
|
+
})]);
|
|
45
|
+
/** Build an unsealed request with the current protocol version and a TTL. */
|
|
46
|
+
function makeRequest(params) {
|
|
47
|
+
const nowSec = Math.floor((params.now ?? Date.now()) / 1e3);
|
|
48
|
+
return {
|
|
49
|
+
v: 1,
|
|
50
|
+
id: params.id,
|
|
51
|
+
method: params.method,
|
|
52
|
+
origin: params.origin,
|
|
53
|
+
params: params.params,
|
|
54
|
+
exp: nowSec + (params.ttlSeconds ?? 120)
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
function sealRequest(sharedKey, request) {
|
|
58
|
+
return seal(sharedKey, utf8ToBytes(JSON.stringify(request)));
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Decrypt + structurally validate an inbound request. Throws `DECRYPT_FAILED` if
|
|
62
|
+
* the envelope is not authentic, `INVALID_ARGUMENT` if the plaintext is not a
|
|
63
|
+
* well-formed request. Does NOT check expiry/replay — call `guardRequest` for
|
|
64
|
+
* that policy step (kept separate so the crypto and the policy are distinct).
|
|
65
|
+
*/
|
|
66
|
+
function openRequest(sharedKey, envelope) {
|
|
67
|
+
const bytes = open(sharedKey, envelope);
|
|
68
|
+
let parsed;
|
|
69
|
+
try {
|
|
70
|
+
parsed = JSON.parse(bytesToUtf8(bytes));
|
|
71
|
+
} catch {
|
|
72
|
+
throw new WalletSdkError("INVALID_ARGUMENT", "request is not valid JSON");
|
|
73
|
+
}
|
|
74
|
+
const result = walletRequestSchema.safeParse(parsed);
|
|
75
|
+
if (!result.success) throw new WalletSdkError("INVALID_ARGUMENT", "request failed schema validation");
|
|
76
|
+
return result.data;
|
|
77
|
+
}
|
|
78
|
+
function sealResponse(sharedKey, response) {
|
|
79
|
+
return seal(sharedKey, utf8ToBytes(JSON.stringify(response)));
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Decrypt + validate an inbound response, optionally asserting it answers
|
|
83
|
+
* `expectedId` (defends against a swapped/mismatched reply).
|
|
84
|
+
*/
|
|
85
|
+
function openResponse(sharedKey, envelope, expectedId) {
|
|
86
|
+
const bytes = open(sharedKey, envelope);
|
|
87
|
+
let parsed;
|
|
88
|
+
try {
|
|
89
|
+
parsed = JSON.parse(bytesToUtf8(bytes));
|
|
90
|
+
} catch {
|
|
91
|
+
throw new WalletSdkError("INVALID_ARGUMENT", "response is not valid JSON");
|
|
92
|
+
}
|
|
93
|
+
const result = walletResponseSchema.safeParse(parsed);
|
|
94
|
+
if (!result.success) throw new WalletSdkError("INVALID_ARGUMENT", "response failed schema validation");
|
|
95
|
+
const response = result.data;
|
|
96
|
+
if (expectedId !== void 0 && response.id !== expectedId) throw new WalletSdkError("INVALID_ARGUMENT", "response id does not match the request");
|
|
97
|
+
return response;
|
|
98
|
+
}
|
|
99
|
+
function createMemorySeenStore(maxEntries = 1e4) {
|
|
100
|
+
const ids = /* @__PURE__ */ new Set();
|
|
101
|
+
return {
|
|
102
|
+
has: (id) => ids.has(id),
|
|
103
|
+
add: (id) => {
|
|
104
|
+
if (ids.size >= maxEntries) ids.delete(ids.values().next().value);
|
|
105
|
+
ids.add(id);
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Policy gate: enforce expiry + one-time id BEFORE acting on a request (i.e.
|
|
111
|
+
* before building/signing anything). Atomic check-and-add against `store`.
|
|
112
|
+
* Throws `EXPIRED` or `INVALID_ARGUMENT` (duplicate).
|
|
113
|
+
*/
|
|
114
|
+
function guardRequest(request, store, now) {
|
|
115
|
+
const nowSec = Math.floor((now ?? Date.now()) / 1e3);
|
|
116
|
+
if (request.exp <= nowSec) throw new WalletSdkError("EXPIRED", "request has expired");
|
|
117
|
+
if (store.has(request.id)) throw new WalletSdkError("INVALID_ARGUMENT", "duplicate request id (replay)");
|
|
118
|
+
store.add(request.id);
|
|
119
|
+
}
|
|
120
|
+
//#endregion
|
|
121
|
+
export { WALLET_METHODS, createMemorySeenStore, guardRequest, makeRequest, openRequest, openResponse, sealRequest, sealResponse };
|
|
122
|
+
|
|
123
|
+
//# sourceMappingURL=envelope.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"envelope.js","names":[],"sources":["../../src/transport/envelope.ts"],"sourcesContent":["/**\n * The encrypted request/response envelope that flows over ANY transport (deep\n * link, QR, or the cross-device bridge). Post-connect, both sides hold the x25519\n * shared key, so every request and response is sealed — even same-device deep\n * links carry ciphertext, so a hijacked scheme yields an unusable blob.\n *\n * Methods mirror the wallet extension's provider vocabulary so a dApp integrates\n * once against the same names on every transport.\n */\n\nimport { z } from 'zod'\n\nimport { PROTOCOL_VERSION } from '../constants'\nimport { bytesToUtf8, utf8ToBytes } from '../bytes'\nimport { open, seal, type SealedEnvelope } from '../crypto/box'\nimport { WalletSdkError } from '../errors'\n\nexport const WALLET_METHODS = [\n\t'amadeus_signTransaction',\n\t'amadeus_signMessage',\n\t'amadeus_getAccounts',\n\t'amadeus_generateApiKey',\n\t'amadeus_switchNetwork'\n] as const\n\nexport type WalletMethod = (typeof WALLET_METHODS)[number]\n\nexport interface WalletRequest {\n\t/** Protocol version. */\n\tv: number\n\t/** Unique, one-time request id (replay key). */\n\tid: string\n\tmethod: WalletMethod\n\t/** The dApp origin, echoed for display in the approval UI. */\n\torigin: string\n\tparams: unknown\n\t/** Unix-seconds expiry. */\n\texp: number\n}\n\nexport type WalletResponse =\n\t| { v: number; id: string; ok: true; result: unknown }\n\t| { v: number; id: string; ok: false; error: { code: string; message: string } }\n\nconst walletRequestSchema = z.object({\n\tv: z.number().int(),\n\tid: z.string().min(1).max(128),\n\tmethod: z.enum(WALLET_METHODS),\n\torigin: z.string().min(1),\n\tparams: z.unknown(),\n\texp: z.number().int()\n})\n\nconst walletResponseSchema = z.union([\n\tz.object({\n\t\tv: z.number().int(),\n\t\tid: z.string().min(1).max(128),\n\t\tok: z.literal(true),\n\t\tresult: z.unknown()\n\t}),\n\tz.object({\n\t\tv: z.number().int(),\n\t\tid: z.string().min(1).max(128),\n\t\tok: z.literal(false),\n\t\terror: z.object({ code: z.string(), message: z.string() })\n\t})\n])\n\n/** Build an unsealed request with the current protocol version and a TTL. */\nexport function makeRequest(params: {\n\tid: string\n\tmethod: WalletMethod\n\torigin: string\n\tparams: unknown\n\tttlSeconds?: number\n\tnow?: number\n}): WalletRequest {\n\tconst nowSec = Math.floor((params.now ?? Date.now()) / 1000)\n\treturn {\n\t\tv: PROTOCOL_VERSION,\n\t\tid: params.id,\n\t\tmethod: params.method,\n\t\torigin: params.origin,\n\t\tparams: params.params,\n\t\texp: nowSec + (params.ttlSeconds ?? 120)\n\t}\n}\n\nexport function sealRequest(sharedKey: Uint8Array, request: WalletRequest): SealedEnvelope {\n\treturn seal(sharedKey, utf8ToBytes(JSON.stringify(request)))\n}\n\n/**\n * Decrypt + structurally validate an inbound request. Throws `DECRYPT_FAILED` if\n * the envelope is not authentic, `INVALID_ARGUMENT` if the plaintext is not a\n * well-formed request. Does NOT check expiry/replay — call `guardRequest` for\n * that policy step (kept separate so the crypto and the policy are distinct).\n */\nexport function openRequest(sharedKey: Uint8Array, envelope: SealedEnvelope): WalletRequest {\n\tconst bytes = open(sharedKey, envelope)\n\tlet parsed: unknown\n\ttry {\n\t\tparsed = JSON.parse(bytesToUtf8(bytes))\n\t} catch {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'request is not valid JSON')\n\t}\n\tconst result = walletRequestSchema.safeParse(parsed)\n\tif (!result.success) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'request failed schema validation')\n\t}\n\treturn result.data as WalletRequest\n}\n\nexport function sealResponse(sharedKey: Uint8Array, response: WalletResponse): SealedEnvelope {\n\treturn seal(sharedKey, utf8ToBytes(JSON.stringify(response)))\n}\n\n/**\n * Decrypt + validate an inbound response, optionally asserting it answers\n * `expectedId` (defends against a swapped/mismatched reply).\n */\nexport function openResponse(\n\tsharedKey: Uint8Array,\n\tenvelope: SealedEnvelope,\n\texpectedId?: string\n): WalletResponse {\n\tconst bytes = open(sharedKey, envelope)\n\tlet parsed: unknown\n\ttry {\n\t\tparsed = JSON.parse(bytesToUtf8(bytes))\n\t} catch {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'response is not valid JSON')\n\t}\n\tconst result = walletResponseSchema.safeParse(parsed)\n\tif (!result.success) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'response failed schema validation')\n\t}\n\tconst response = result.data as WalletResponse\n\tif (expectedId !== undefined && response.id !== expectedId) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'response id does not match the request')\n\t}\n\treturn response\n}\n\n/**\n * A one-time-id store for replay defense. The in-memory default is fine for a\n * single process; the mobile wallet should supply a PERSISTED implementation\n * (e.g. expo-secure-store) so a crash/relaunch inside the TTL window can't let a\n * captured approval replay. `has`+`add` must be atomic in the persisted impl.\n */\nexport interface SeenStore {\n\thas(id: string): boolean\n\tadd(id: string): void\n}\n\nexport function createMemorySeenStore(maxEntries = 10_000): SeenStore {\n\tconst ids = new Set<string>()\n\treturn {\n\t\thas: (id) => ids.has(id),\n\t\tadd: (id) => {\n\t\t\tif (ids.size >= maxEntries) ids.delete(ids.values().next().value as string)\n\t\t\tids.add(id)\n\t\t}\n\t}\n}\n\n/**\n * Policy gate: enforce expiry + one-time id BEFORE acting on a request (i.e.\n * before building/signing anything). Atomic check-and-add against `store`.\n * Throws `EXPIRED` or `INVALID_ARGUMENT` (duplicate).\n */\nexport function guardRequest(request: WalletRequest, store: SeenStore, now?: number): void {\n\tconst nowSec = Math.floor((now ?? Date.now()) / 1000)\n\tif (request.exp <= nowSec) {\n\t\tthrow new WalletSdkError('EXPIRED', 'request has expired')\n\t}\n\tif (store.has(request.id)) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'duplicate request id (replay)')\n\t}\n\tstore.add(request.id)\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiBA,MAAa,iBAAiB;CAC7B;CACA;CACA;CACA;CACA;AACD;AAqBA,MAAM,sBAAsB,EAAE,OAAO;CACpC,GAAG,EAAE,OAAO,CAAC,CAAC,IAAI;CAClB,IAAI,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG;CAC7B,QAAQ,EAAE,KAAK,cAAc;CAC7B,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CACxB,QAAQ,EAAE,QAAQ;CAClB,KAAK,EAAE,OAAO,CAAC,CAAC,IAAI;AACrB,CAAC;AAED,MAAM,uBAAuB,EAAE,MAAM,CACpC,EAAE,OAAO;CACR,GAAG,EAAE,OAAO,CAAC,CAAC,IAAI;CAClB,IAAI,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG;CAC7B,IAAI,EAAE,QAAQ,IAAI;CAClB,QAAQ,EAAE,QAAQ;AACnB,CAAC,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1E;CACA,MAAM,SAAS,qBAAqB,UAAU,MAAM;CACpD,IAAI,CAAC,OAAO,SACX,MAAM,IAAI,eAAe,oBAAoB,mCAAmC;CAEjF,MAAM,WAAW,OAAO;CACxB,IAAI,eAAe,KAAA,KAAa,SAAS,OAAO,YAC/C,MAAM,IAAI,eAAe,oBAAoB,wCAAwC;CAEtF,OAAO;AACR;AAaA,SAAgB,sBAAsB,aAAa,KAAmB;CACrE,MAAM,sBAAM,IAAI,IAAY;CAC5B,OAAO;EACN,MAAM,OAAO,IAAI,IAAI,EAAE;EACvB,MAAM,OAAO;GACZ,IAAI,IAAI,QAAQ,YAAY,IAAI,OAAO,IAAI,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,KAAe;GAC1E,IAAI,IAAI,EAAE;EACX;CACD;AACD;;;;;;AAOA,SAAgB,aAAa,SAAwB,OAAkB,KAAoB;CAC1F,MAAM,SAAS,KAAK,OAAO,OAAO,KAAK,IAAI,KAAK,GAAI;CACpD,IAAI,QAAQ,OAAO,QAClB,MAAM,IAAI,eAAe,WAAW,qBAAqB;CAE1D,IAAI,MAAM,IAAI,QAAQ,EAAE,GACvB,MAAM,IAAI,eAAe,oBAAoB,+BAA+B;CAE7E,MAAM,IAAI,QAAQ,EAAE;AACrB"}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { SessionKeypair } from "../crypto/box.js";
|
|
2
|
+
import { ConnectRequestParams, ConnectResponseParams } from "./uri.js";
|
|
3
|
+
//#region src/transport/session.d.ts
|
|
4
|
+
/** State the dApp keeps locally between issuing a connect request and completing it. */
|
|
5
|
+
interface PendingConnect {
|
|
6
|
+
requestId: string;
|
|
7
|
+
challenge: string;
|
|
8
|
+
origin: string;
|
|
9
|
+
/** The dApp's ephemeral session keypair (secret stays local). */
|
|
10
|
+
dappKeypair: SessionKeypair;
|
|
11
|
+
exp: number;
|
|
12
|
+
bridgeUrl?: string;
|
|
13
|
+
}
|
|
14
|
+
interface EstablishedSession {
|
|
15
|
+
/** The connected wallet address (Base58 public key). */
|
|
16
|
+
address: string;
|
|
17
|
+
/** 32-byte symmetric key for sealing/opening envelopes. Keep in memory only. */
|
|
18
|
+
sharedKey: Uint8Array;
|
|
19
|
+
/** The wallet's session key — the peer's bridge client id to send frames to. */
|
|
20
|
+
walletPublicKey: string;
|
|
21
|
+
/** This dApp's session key — its own bridge client id to listen on. */
|
|
22
|
+
selfPublicKey: string;
|
|
23
|
+
origin: string;
|
|
24
|
+
/** Relay base URL for post-connect sealed messages, if provided. */
|
|
25
|
+
bridgeUrl?: string;
|
|
26
|
+
}
|
|
27
|
+
/** dApp: create a connect request. Returns the URI to display and the pending state to keep. */
|
|
28
|
+
declare function createConnectRequest(options: {
|
|
29
|
+
origin: string;
|
|
30
|
+
redirectLink?: string;
|
|
31
|
+
bridgeUrl?: string;
|
|
32
|
+
ttlSeconds?: number;
|
|
33
|
+
now?: number;
|
|
34
|
+
}): {
|
|
35
|
+
uri: string;
|
|
36
|
+
pending: PendingConnect;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* dApp: verify the wallet's connect response and establish the session. Throws
|
|
40
|
+
* `INVALID_ARGUMENT` if the response is for a different request, or
|
|
41
|
+
* `BAD_SIGNATURE` if the connect proof does not verify against the transcript.
|
|
42
|
+
*/
|
|
43
|
+
declare function completeConnect(pending: PendingConnect, response: ConnectResponseParams): EstablishedSession;
|
|
44
|
+
interface WalletSession {
|
|
45
|
+
/** The response to hand back to the dApp (via callback URI or bridge frame). */
|
|
46
|
+
response: ConnectResponseParams;
|
|
47
|
+
/** 32-byte symmetric key for sealing/opening envelopes. Keep in memory only. */
|
|
48
|
+
sharedKey: Uint8Array;
|
|
49
|
+
/** The wallet's ephemeral session keypair for this dApp (its own bridge client id). */
|
|
50
|
+
walletKeypair: SessionKeypair;
|
|
51
|
+
/** The dApp's session key — the peer's bridge client id to send frames to. */
|
|
52
|
+
peerPublicKey: string;
|
|
53
|
+
/** Relay base URL for post-connect sealed messages, if the dApp supplied one. */
|
|
54
|
+
bridgeUrl?: string;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Wallet: approve a connect request and produce the signed response + session.
|
|
58
|
+
* Call this ONLY AFTER the user has approved in the UI and the request's expiry
|
|
59
|
+
* has been checked. `address` is the account that will be bound to this session
|
|
60
|
+
* (bind to a specific account, not the live "active" one).
|
|
61
|
+
*/
|
|
62
|
+
declare function approveConnect(request: ConnectRequestParams, options: {
|
|
63
|
+
seed: string;
|
|
64
|
+
address: string;
|
|
65
|
+
}): WalletSession;
|
|
66
|
+
/** Whether a parsed connect request has expired (wallet should reject/re-park). */
|
|
67
|
+
declare function isConnectRequestExpired(request: ConnectRequestParams, now?: number): boolean;
|
|
68
|
+
//#endregion
|
|
69
|
+
export { EstablishedSession, PendingConnect, WalletSession, approveConnect, completeConnect, createConnectRequest, isConnectRequestExpired };
|
|
70
|
+
//# sourceMappingURL=session.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session.d.ts","names":[],"sources":["../../src/transport/session.ts"],"mappings":";;;;UA4BiB;EAChB;EACA;EACA;;EAEA,aAAa;EACb;EACA;;UAGgB;;EAEhB;;EAEA,WAAW;;EAEX;;EAEA;EACA;;EAEA;;;iBAIe,qBAAqB;EACpC;EACA;EACA;EACA;EACA;;EACK;EAAa,SAAS;;;;;;;iBAkCZ,gBACf,SAAS,gBACT,UAAU,wBACR;UA4Bc;;EAEhB,UAAU;;EAEV,WAAW;;EAEX,eAAe;;EAEf;;EAEA;;;;;;;;iBASe,eACf,SAAS,sBACT;EAAW;EAAc;IACvB;;iBA4Ba,wBAAwB,SAAS,sBAAsB"}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { WalletSdkError } from "../errors.js";
|
|
2
|
+
import { randomBytes, randomId } from "../bytes.js";
|
|
3
|
+
import { signConnect, verifyConnect } from "../crypto/connect.js";
|
|
4
|
+
import { deriveSharedKey, generateSessionKeypair } from "../crypto/box.js";
|
|
5
|
+
import { buildConnectUri } from "./uri.js";
|
|
6
|
+
import { toBase58 } from "@amadeus-protocol/sdk";
|
|
7
|
+
//#region src/transport/session.ts
|
|
8
|
+
/**
|
|
9
|
+
* The connect handshake, orchestrated for both sides. This is where the crypto
|
|
10
|
+
* primitives (connect transcript signing + x25519 box) and the URI transport
|
|
11
|
+
* come together into an actual dApp <-> wallet session.
|
|
12
|
+
*
|
|
13
|
+
* Flow:
|
|
14
|
+
* dApp: createConnectRequest() -> show `uri` (link/QR), keep `pending`
|
|
15
|
+
* wallet: parseConnectUri(uri) -> [approve in UI] -> approveConnect()
|
|
16
|
+
* -> return `response` to the dApp
|
|
17
|
+
* dApp: completeConnect(pending, response) -> EstablishedSession
|
|
18
|
+
*
|
|
19
|
+
* After that both sides hold the same `sharedKey` and exchange sealed envelopes
|
|
20
|
+
* (see envelope.ts). The wallet signs the transcript binding origin + BOTH
|
|
21
|
+
* session keys + challenge + requestId, so a captured proof can't be replayed
|
|
22
|
+
* under substituted keys.
|
|
23
|
+
*/
|
|
24
|
+
/** dApp: create a connect request. Returns the URI to display and the pending state to keep. */
|
|
25
|
+
function createConnectRequest(options) {
|
|
26
|
+
const dappKeypair = generateSessionKeypair();
|
|
27
|
+
const challenge = toBase58(randomBytes(16));
|
|
28
|
+
const requestId = randomId();
|
|
29
|
+
const exp = Math.floor((options.now ?? Date.now()) / 1e3) + (options.ttlSeconds ?? 120);
|
|
30
|
+
return {
|
|
31
|
+
uri: buildConnectUri({
|
|
32
|
+
origin: options.origin,
|
|
33
|
+
dappPublicKey: dappKeypair.publicKey,
|
|
34
|
+
challenge,
|
|
35
|
+
requestId,
|
|
36
|
+
exp,
|
|
37
|
+
redirectLink: options.redirectLink,
|
|
38
|
+
bridgeUrl: options.bridgeUrl
|
|
39
|
+
}),
|
|
40
|
+
pending: {
|
|
41
|
+
requestId,
|
|
42
|
+
challenge,
|
|
43
|
+
origin: options.origin,
|
|
44
|
+
dappKeypair,
|
|
45
|
+
exp,
|
|
46
|
+
bridgeUrl: options.bridgeUrl
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* dApp: verify the wallet's connect response and establish the session. Throws
|
|
52
|
+
* `INVALID_ARGUMENT` if the response is for a different request, or
|
|
53
|
+
* `BAD_SIGNATURE` if the connect proof does not verify against the transcript.
|
|
54
|
+
*/
|
|
55
|
+
function completeConnect(pending, response) {
|
|
56
|
+
if (response.requestId !== pending.requestId) throw new WalletSdkError("INVALID_ARGUMENT", "response does not match the pending request");
|
|
57
|
+
const transcript = {
|
|
58
|
+
origin: pending.origin,
|
|
59
|
+
dappPublicKey: pending.dappKeypair.publicKey,
|
|
60
|
+
walletPublicKey: response.walletPublicKey,
|
|
61
|
+
challenge: pending.challenge,
|
|
62
|
+
requestId: pending.requestId
|
|
63
|
+
};
|
|
64
|
+
if (!verifyConnect({
|
|
65
|
+
address: response.address,
|
|
66
|
+
transcript,
|
|
67
|
+
signature: response.signature
|
|
68
|
+
})) throw new WalletSdkError("BAD_SIGNATURE", "connect proof failed verification");
|
|
69
|
+
const sharedKey = deriveSharedKey(response.walletPublicKey, pending.dappKeypair.secretKey);
|
|
70
|
+
return {
|
|
71
|
+
address: response.address,
|
|
72
|
+
sharedKey,
|
|
73
|
+
walletPublicKey: response.walletPublicKey,
|
|
74
|
+
selfPublicKey: pending.dappKeypair.publicKey,
|
|
75
|
+
origin: pending.origin,
|
|
76
|
+
bridgeUrl: pending.bridgeUrl
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Wallet: approve a connect request and produce the signed response + session.
|
|
81
|
+
* Call this ONLY AFTER the user has approved in the UI and the request's expiry
|
|
82
|
+
* has been checked. `address` is the account that will be bound to this session
|
|
83
|
+
* (bind to a specific account, not the live "active" one).
|
|
84
|
+
*/
|
|
85
|
+
function approveConnect(request, options) {
|
|
86
|
+
const walletKeypair = generateSessionKeypair();
|
|
87
|
+
const transcript = {
|
|
88
|
+
origin: request.origin,
|
|
89
|
+
dappPublicKey: request.dappPublicKey,
|
|
90
|
+
walletPublicKey: walletKeypair.publicKey,
|
|
91
|
+
challenge: request.challenge,
|
|
92
|
+
requestId: request.requestId
|
|
93
|
+
};
|
|
94
|
+
const signature = signConnect({
|
|
95
|
+
seed: options.seed,
|
|
96
|
+
transcript
|
|
97
|
+
});
|
|
98
|
+
const sharedKey = deriveSharedKey(request.dappPublicKey, walletKeypair.secretKey);
|
|
99
|
+
return {
|
|
100
|
+
response: {
|
|
101
|
+
requestId: request.requestId,
|
|
102
|
+
address: options.address,
|
|
103
|
+
walletPublicKey: walletKeypair.publicKey,
|
|
104
|
+
signature
|
|
105
|
+
},
|
|
106
|
+
sharedKey,
|
|
107
|
+
walletKeypair,
|
|
108
|
+
peerPublicKey: request.dappPublicKey,
|
|
109
|
+
bridgeUrl: request.bridgeUrl
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/** Whether a parsed connect request has expired (wallet should reject/re-park). */
|
|
113
|
+
function isConnectRequestExpired(request, now) {
|
|
114
|
+
return request.exp <= Math.floor((now ?? Date.now()) / 1e3);
|
|
115
|
+
}
|
|
116
|
+
//#endregion
|
|
117
|
+
export { approveConnect, completeConnect, createConnectRequest, isConnectRequestExpired };
|
|
118
|
+
|
|
119
|
+
//# sourceMappingURL=session.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session.js","names":[],"sources":["../../src/transport/session.ts"],"sourcesContent":["/**\n * The connect handshake, orchestrated for both sides. This is where the crypto\n * primitives (connect transcript signing + x25519 box) and the URI transport\n * come together into an actual dApp <-> wallet session.\n *\n * Flow:\n * dApp: createConnectRequest() -> show `uri` (link/QR), keep `pending`\n * wallet: parseConnectUri(uri) -> [approve in UI] -> approveConnect()\n * -> return `response` to the dApp\n * dApp: completeConnect(pending, response) -> EstablishedSession\n *\n * After that both sides hold the same `sharedKey` and exchange sealed envelopes\n * (see envelope.ts). The wallet signs the transcript binding origin + BOTH\n * session keys + challenge + requestId, so a captured proof can't be replayed\n * under substituted keys.\n */\n\nimport { toBase58 } from '@amadeus-protocol/sdk'\n\nimport { randomBytes, randomId } from '../bytes'\nimport { signConnect, verifyConnect, type ConnectTranscript } from '../crypto/connect'\nimport { deriveSharedKey, generateSessionKeypair, type SessionKeypair } from '../crypto/box'\nimport { WalletSdkError } from '../errors'\nimport { buildConnectUri, type ConnectRequestParams, type ConnectResponseParams } from './uri'\n\n// ── dApp side ───────────────────────────────────────────────────────────────\n\n/** State the dApp keeps locally between issuing a connect request and completing it. */\nexport interface PendingConnect {\n\trequestId: string\n\tchallenge: string\n\torigin: string\n\t/** The dApp's ephemeral session keypair (secret stays local). */\n\tdappKeypair: SessionKeypair\n\texp: number\n\tbridgeUrl?: string\n}\n\nexport interface EstablishedSession {\n\t/** The connected wallet address (Base58 public key). */\n\taddress: string\n\t/** 32-byte symmetric key for sealing/opening envelopes. Keep in memory only. */\n\tsharedKey: Uint8Array\n\t/** The wallet's session key — the peer's bridge client id to send frames to. */\n\twalletPublicKey: string\n\t/** This dApp's session key — its own bridge client id to listen on. */\n\tselfPublicKey: string\n\torigin: string\n\t/** Relay base URL for post-connect sealed messages, if provided. */\n\tbridgeUrl?: string\n}\n\n/** dApp: create a connect request. Returns the URI to display and the pending state to keep. */\nexport function createConnectRequest(options: {\n\torigin: string\n\tredirectLink?: string\n\tbridgeUrl?: string\n\tttlSeconds?: number\n\tnow?: number\n}): { uri: string; pending: PendingConnect } {\n\tconst dappKeypair = generateSessionKeypair()\n\tconst challenge = toBase58(randomBytes(16))\n\tconst requestId = randomId()\n\tconst nowSec = Math.floor((options.now ?? Date.now()) / 1000)\n\tconst exp = nowSec + (options.ttlSeconds ?? 120)\n\n\tconst params: ConnectRequestParams = {\n\t\torigin: options.origin,\n\t\tdappPublicKey: dappKeypair.publicKey,\n\t\tchallenge,\n\t\trequestId,\n\t\texp,\n\t\tredirectLink: options.redirectLink,\n\t\tbridgeUrl: options.bridgeUrl\n\t}\n\treturn {\n\t\turi: buildConnectUri(params),\n\t\tpending: {\n\t\t\trequestId,\n\t\t\tchallenge,\n\t\t\torigin: options.origin,\n\t\t\tdappKeypair,\n\t\t\texp,\n\t\t\tbridgeUrl: options.bridgeUrl\n\t\t}\n\t}\n}\n\n/**\n * dApp: verify the wallet's connect response and establish the session. Throws\n * `INVALID_ARGUMENT` if the response is for a different request, or\n * `BAD_SIGNATURE` if the connect proof does not verify against the transcript.\n */\nexport function completeConnect(\n\tpending: PendingConnect,\n\tresponse: ConnectResponseParams\n): EstablishedSession {\n\tif (response.requestId !== pending.requestId) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'response does not match the pending request')\n\t}\n\tconst transcript: ConnectTranscript = {\n\t\torigin: pending.origin,\n\t\tdappPublicKey: pending.dappKeypair.publicKey,\n\t\twalletPublicKey: response.walletPublicKey,\n\t\tchallenge: pending.challenge,\n\t\trequestId: pending.requestId\n\t}\n\tif (!verifyConnect({ address: response.address, transcript, signature: response.signature })) {\n\t\tthrow new WalletSdkError('BAD_SIGNATURE', 'connect proof failed verification')\n\t}\n\t// deriveSharedKey validates the wallet's session key (fails closed on a bad point).\n\tconst sharedKey = deriveSharedKey(response.walletPublicKey, pending.dappKeypair.secretKey)\n\treturn {\n\t\taddress: response.address,\n\t\tsharedKey,\n\t\twalletPublicKey: response.walletPublicKey,\n\t\tselfPublicKey: pending.dappKeypair.publicKey,\n\t\torigin: pending.origin,\n\t\tbridgeUrl: pending.bridgeUrl\n\t}\n}\n\n// ── wallet side ───────────────────────────────────────────────────────────────\n\nexport interface WalletSession {\n\t/** The response to hand back to the dApp (via callback URI or bridge frame). */\n\tresponse: ConnectResponseParams\n\t/** 32-byte symmetric key for sealing/opening envelopes. Keep in memory only. */\n\tsharedKey: Uint8Array\n\t/** The wallet's ephemeral session keypair for this dApp (its own bridge client id). */\n\twalletKeypair: SessionKeypair\n\t/** The dApp's session key — the peer's bridge client id to send frames to. */\n\tpeerPublicKey: string\n\t/** Relay base URL for post-connect sealed messages, if the dApp supplied one. */\n\tbridgeUrl?: string\n}\n\n/**\n * Wallet: approve a connect request and produce the signed response + session.\n * Call this ONLY AFTER the user has approved in the UI and the request's expiry\n * has been checked. `address` is the account that will be bound to this session\n * (bind to a specific account, not the live \"active\" one).\n */\nexport function approveConnect(\n\trequest: ConnectRequestParams,\n\toptions: { seed: string; address: string }\n): WalletSession {\n\tconst walletKeypair = generateSessionKeypair()\n\tconst transcript: ConnectTranscript = {\n\t\torigin: request.origin,\n\t\tdappPublicKey: request.dappPublicKey,\n\t\twalletPublicKey: walletKeypair.publicKey,\n\t\tchallenge: request.challenge,\n\t\trequestId: request.requestId\n\t}\n\tconst signature = signConnect({ seed: options.seed, transcript })\n\t// deriveSharedKey validates the dApp's session key (fails closed on a bad point).\n\tconst sharedKey = deriveSharedKey(request.dappPublicKey, walletKeypair.secretKey)\n\n\treturn {\n\t\tresponse: {\n\t\t\trequestId: request.requestId,\n\t\t\taddress: options.address,\n\t\t\twalletPublicKey: walletKeypair.publicKey,\n\t\t\tsignature\n\t\t},\n\t\tsharedKey,\n\t\twalletKeypair,\n\t\tpeerPublicKey: request.dappPublicKey,\n\t\tbridgeUrl: request.bridgeUrl\n\t}\n}\n\n/** Whether a parsed connect request has expired (wallet should reject/re-park). */\nexport function isConnectRequestExpired(request: ConnectRequestParams, now?: number): boolean {\n\treturn request.exp <= Math.floor((now ?? Date.now()) / 1000)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAqDA,SAAgB,qBAAqB,SAMQ;CAC5C,MAAM,cAAc,uBAAuB;CAC3C,MAAM,YAAY,SAAS,YAAY,EAAE,CAAC;CAC1C,MAAM,YAAY,SAAS;CAE3B,MAAM,MADS,KAAK,OAAO,QAAQ,OAAO,KAAK,IAAI,KAAK,GACvC,KAAK,QAAQ,cAAc;CAW5C,OAAO;EACN,KAAK,gBAAgB;GATrB,QAAQ,QAAQ;GAChB,eAAe,YAAY;GAC3B;GACA;GACA;GACA,cAA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AAK,GAAI;AAC5D"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
//#region src/transport/uri.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Deep-link / QR URI construction and parsing for the connect handshake.
|
|
4
|
+
*
|
|
5
|
+
* The connect bootstrap params (dApp session pubkey, challenge, request id,
|
|
6
|
+
* origin) are necessarily PLAINTEXT — there is no shared key yet, and they are
|
|
7
|
+
* public handshake material. Everything AFTER connect is sealed (see envelope).
|
|
8
|
+
*
|
|
9
|
+
* Query parsing is hand-rolled with encode/decodeURIComponent so it is fully
|
|
10
|
+
* portable across Node, browsers, and React Native/Hermes (no dependency on a
|
|
11
|
+
* URL/URLSearchParams polyfill).
|
|
12
|
+
*/
|
|
13
|
+
declare const URI_SCHEME = "amadeus";
|
|
14
|
+
interface ConnectRequestParams {
|
|
15
|
+
origin: string;
|
|
16
|
+
/** dApp ephemeral x25519 session public key (Base58). */
|
|
17
|
+
dappPublicKey: string;
|
|
18
|
+
challenge: string;
|
|
19
|
+
requestId: string;
|
|
20
|
+
/** Unix-seconds expiry. */
|
|
21
|
+
exp: number;
|
|
22
|
+
/** Same-device return target; omit for QR / bridge (cross-device). */
|
|
23
|
+
redirectLink?: string;
|
|
24
|
+
/** Relay base URL for post-connect sealed messages (cross-device). */
|
|
25
|
+
bridgeUrl?: string;
|
|
26
|
+
}
|
|
27
|
+
interface ConnectResponseParams {
|
|
28
|
+
requestId: string;
|
|
29
|
+
address: string;
|
|
30
|
+
/** Wallet ephemeral x25519 session public key (Base58). */
|
|
31
|
+
walletPublicKey: string;
|
|
32
|
+
/** Base58 connect-transcript signature. */
|
|
33
|
+
signature: string;
|
|
34
|
+
}
|
|
35
|
+
/** Build the `amadeus://vN/connect?...` URI a dApp shows as a link or QR. */
|
|
36
|
+
declare function buildConnectUri(params: ConnectRequestParams): string;
|
|
37
|
+
/** Parse + validate a connect URI. Throws `INVALID_ARGUMENT` on anything off. */
|
|
38
|
+
declare function parseConnectUri(uri: string): ConnectRequestParams;
|
|
39
|
+
/**
|
|
40
|
+
* Build the same-device callback URI the wallet opens to return the connect
|
|
41
|
+
* response to the dApp. `data` fields are plaintext connect material (the shared
|
|
42
|
+
* key is derived from them); post-connect requests use sealed envelopes instead.
|
|
43
|
+
*/
|
|
44
|
+
declare function buildConnectResponseUri(redirectLink: string, response: ConnectResponseParams): string;
|
|
45
|
+
/** Parse a connect response from a callback URL's query string. */
|
|
46
|
+
declare function parseConnectResponseUri(uri: string): ConnectResponseParams;
|
|
47
|
+
//#endregion
|
|
48
|
+
export { ConnectRequestParams, ConnectResponseParams, URI_SCHEME, buildConnectResponseUri, buildConnectUri, parseConnectResponseUri, parseConnectUri };
|
|
49
|
+
//# sourceMappingURL=uri.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"uri.d.ts","names":[],"sources":["../../src/transport/uri.ts"],"mappings":";;;;;;;;;;;;cAea;UAEI;EAChB;;EAEA;EACA;EACA;;EAEA;;EAEA;;EAEA;;UAGgB;EAChB;EACA;;EAEA;;EAEA;;;iBAsCe,gBAAgB,QAAQ;;iBAcxB,gBAAgB,cAAc;;;;;;iBA6B9B,wBACf,sBACA,UAAU;;iBAaK,wBAAwB,cAAc"}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import "../constants.js";
|
|
2
|
+
import { WalletSdkError } from "../errors.js";
|
|
3
|
+
//#region src/transport/uri.ts
|
|
4
|
+
/**
|
|
5
|
+
* Deep-link / QR URI construction and parsing for the connect handshake.
|
|
6
|
+
*
|
|
7
|
+
* The connect bootstrap params (dApp session pubkey, challenge, request id,
|
|
8
|
+
* origin) are necessarily PLAINTEXT — there is no shared key yet, and they are
|
|
9
|
+
* public handshake material. Everything AFTER connect is sealed (see envelope).
|
|
10
|
+
*
|
|
11
|
+
* Query parsing is hand-rolled with encode/decodeURIComponent so it is fully
|
|
12
|
+
* portable across Node, browsers, and React Native/Hermes (no dependency on a
|
|
13
|
+
* URL/URLSearchParams polyfill).
|
|
14
|
+
*/
|
|
15
|
+
const URI_SCHEME = "amadeus";
|
|
16
|
+
function buildQuery(entries) {
|
|
17
|
+
return Object.entries(entries).filter(([, v]) => v !== void 0 && v !== "").map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join("&");
|
|
18
|
+
}
|
|
19
|
+
function parseQuery(query) {
|
|
20
|
+
const out = {};
|
|
21
|
+
for (const pair of query.split("&")) {
|
|
22
|
+
if (!pair) continue;
|
|
23
|
+
const eq = pair.indexOf("=");
|
|
24
|
+
const key = decodeURIComponent(eq < 0 ? pair : pair.slice(0, eq));
|
|
25
|
+
out[key] = eq < 0 ? "" : decodeURIComponent(pair.slice(eq + 1));
|
|
26
|
+
}
|
|
27
|
+
return out;
|
|
28
|
+
}
|
|
29
|
+
/** Split a URI into { scheme, path, query } without relying on the URL class. */
|
|
30
|
+
function splitUri(uri) {
|
|
31
|
+
const schemeSep = uri.indexOf("://");
|
|
32
|
+
if (schemeSep < 0) throw new WalletSdkError("INVALID_ARGUMENT", "not a valid URI");
|
|
33
|
+
const scheme = uri.slice(0, schemeSep);
|
|
34
|
+
const rest = uri.slice(schemeSep + 3);
|
|
35
|
+
const q = rest.indexOf("?");
|
|
36
|
+
return {
|
|
37
|
+
scheme,
|
|
38
|
+
path: q < 0 ? rest : rest.slice(0, q),
|
|
39
|
+
query: q < 0 ? "" : rest.slice(q + 1)
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
const CONNECT_PATH = `v1/connect`;
|
|
43
|
+
/** Build the `amadeus://vN/connect?...` URI a dApp shows as a link or QR. */
|
|
44
|
+
function buildConnectUri(params) {
|
|
45
|
+
const query = buildQuery({
|
|
46
|
+
origin: params.origin,
|
|
47
|
+
dapp_key: params.dappPublicKey,
|
|
48
|
+
challenge: params.challenge,
|
|
49
|
+
id: params.requestId,
|
|
50
|
+
exp: String(params.exp),
|
|
51
|
+
redirect: params.redirectLink,
|
|
52
|
+
bridge: params.bridgeUrl
|
|
53
|
+
});
|
|
54
|
+
return `${URI_SCHEME}://${CONNECT_PATH}?${query}`;
|
|
55
|
+
}
|
|
56
|
+
/** Parse + validate a connect URI. Throws `INVALID_ARGUMENT` on anything off. */
|
|
57
|
+
function parseConnectUri(uri) {
|
|
58
|
+
const { scheme, path, query } = splitUri(uri);
|
|
59
|
+
if (scheme !== "amadeus") throw new WalletSdkError("INVALID_ARGUMENT", `unexpected scheme "${scheme}"`);
|
|
60
|
+
if (path !== CONNECT_PATH) throw new WalletSdkError("INVALID_ARGUMENT", `unexpected path "${path}"`);
|
|
61
|
+
const q = parseQuery(query);
|
|
62
|
+
const exp = Number(q.exp);
|
|
63
|
+
if (!q.origin || !q.dapp_key || !q.challenge || !q.id || !Number.isInteger(exp)) throw new WalletSdkError("INVALID_ARGUMENT", "connect URI is missing required fields");
|
|
64
|
+
return {
|
|
65
|
+
origin: q.origin,
|
|
66
|
+
dappPublicKey: q.dapp_key,
|
|
67
|
+
challenge: q.challenge,
|
|
68
|
+
requestId: q.id,
|
|
69
|
+
exp,
|
|
70
|
+
redirectLink: q.redirect || void 0,
|
|
71
|
+
bridgeUrl: q.bridge || void 0
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Build the same-device callback URI the wallet opens to return the connect
|
|
76
|
+
* response to the dApp. `data` fields are plaintext connect material (the shared
|
|
77
|
+
* key is derived from them); post-connect requests use sealed envelopes instead.
|
|
78
|
+
*/
|
|
79
|
+
function buildConnectResponseUri(redirectLink, response) {
|
|
80
|
+
return `${redirectLink}${redirectLink.includes("?") ? "&" : "?"}${buildQuery({
|
|
81
|
+
id: response.requestId,
|
|
82
|
+
address: response.address,
|
|
83
|
+
wallet_key: response.walletPublicKey,
|
|
84
|
+
sig: response.signature
|
|
85
|
+
})}`;
|
|
86
|
+
}
|
|
87
|
+
/** Parse a connect response from a callback URL's query string. */
|
|
88
|
+
function parseConnectResponseUri(uri) {
|
|
89
|
+
const q = parseQuery(uri.includes("?") ? uri.slice(uri.indexOf("?") + 1) : uri);
|
|
90
|
+
if (!q.id || !q.address || !q.wallet_key || !q.sig) throw new WalletSdkError("INVALID_ARGUMENT", "connect response is missing required fields");
|
|
91
|
+
return {
|
|
92
|
+
requestId: q.id,
|
|
93
|
+
address: q.address,
|
|
94
|
+
walletPublicKey: q.wallet_key,
|
|
95
|
+
signature: q.sig
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
//#endregion
|
|
99
|
+
export { URI_SCHEME, buildConnectResponseUri, buildConnectUri, parseConnectResponseUri, parseConnectUri };
|
|
100
|
+
|
|
101
|
+
//# sourceMappingURL=uri.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"uri.js","names":[],"sources":["../../src/transport/uri.ts"],"sourcesContent":["/**\n * Deep-link / QR URI construction and parsing for the connect handshake.\n *\n * The connect bootstrap params (dApp session pubkey, challenge, request id,\n * origin) are necessarily PLAINTEXT — there is no shared key yet, and they are\n * public handshake material. Everything AFTER connect is sealed (see envelope).\n *\n * Query parsing is hand-rolled with encode/decodeURIComponent so it is fully\n * portable across Node, browsers, and React Native/Hermes (no dependency on a\n * URL/URLSearchParams polyfill).\n */\n\nimport { PROTOCOL_VERSION } from '../constants'\nimport { WalletSdkError } from '../errors'\n\nexport const URI_SCHEME = 'amadeus'\n\nexport interface ConnectRequestParams {\n\torigin: string\n\t/** dApp ephemeral x25519 session public key (Base58). */\n\tdappPublicKey: string\n\tchallenge: string\n\trequestId: string\n\t/** Unix-seconds expiry. */\n\texp: number\n\t/** Same-device return target; omit for QR / bridge (cross-device). */\n\tredirectLink?: string\n\t/** Relay base URL for post-connect sealed messages (cross-device). */\n\tbridgeUrl?: string\n}\n\nexport interface ConnectResponseParams {\n\trequestId: string\n\taddress: string\n\t/** Wallet ephemeral x25519 session public key (Base58). */\n\twalletPublicKey: string\n\t/** Base58 connect-transcript signature. */\n\tsignature: string\n}\n\nfunction buildQuery(entries: Record<string, string | undefined>): string {\n\treturn Object.entries(entries)\n\t\t.filter(([, v]) => v !== undefined && v !== '')\n\t\t.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v as string)}`)\n\t\t.join('&')\n}\n\nfunction parseQuery(query: string): Record<string, string> {\n\tconst out: Record<string, string> = {}\n\tfor (const pair of query.split('&')) {\n\t\tif (!pair) continue\n\t\tconst eq = pair.indexOf('=')\n\t\tconst key = decodeURIComponent(eq < 0 ? pair : pair.slice(0, eq))\n\t\tout[key] = eq < 0 ? '' : decodeURIComponent(pair.slice(eq + 1))\n\t}\n\treturn out\n}\n\n/** Split a URI into { scheme, path, query } without relying on the URL class. */\nfunction splitUri(uri: string): { scheme: string; path: string; query: string } {\n\tconst schemeSep = uri.indexOf('://')\n\tif (schemeSep < 0) throw new WalletSdkError('INVALID_ARGUMENT', 'not a valid URI')\n\tconst scheme = uri.slice(0, schemeSep)\n\tconst rest = uri.slice(schemeSep + 3)\n\tconst q = rest.indexOf('?')\n\treturn {\n\t\tscheme,\n\t\tpath: q < 0 ? rest : rest.slice(0, q),\n\t\tquery: q < 0 ? '' : rest.slice(q + 1)\n\t}\n}\n\nconst CONNECT_PATH = `v${PROTOCOL_VERSION}/connect`\n\n/** Build the `amadeus://vN/connect?...` URI a dApp shows as a link or QR. */\nexport function buildConnectUri(params: ConnectRequestParams): string {\n\tconst query = buildQuery({\n\t\torigin: params.origin,\n\t\tdapp_key: params.dappPublicKey,\n\t\tchallenge: params.challenge,\n\t\tid: params.requestId,\n\t\texp: String(params.exp),\n\t\tredirect: params.redirectLink,\n\t\tbridge: params.bridgeUrl\n\t})\n\treturn `${URI_SCHEME}://${CONNECT_PATH}?${query}`\n}\n\n/** Parse + validate a connect URI. Throws `INVALID_ARGUMENT` on anything off. */\nexport function parseConnectUri(uri: string): ConnectRequestParams {\n\tconst { scheme, path, query } = splitUri(uri)\n\tif (scheme !== URI_SCHEME) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', `unexpected scheme \"${scheme}\"`)\n\t}\n\tif (path !== CONNECT_PATH) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', `unexpected path \"${path}\"`)\n\t}\n\tconst q = parseQuery(query)\n\tconst exp = Number(q.exp)\n\tif (!q.origin || !q.dapp_key || !q.challenge || !q.id || !Number.isInteger(exp)) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'connect URI is missing required fields')\n\t}\n\treturn {\n\t\torigin: q.origin,\n\t\tdappPublicKey: q.dapp_key,\n\t\tchallenge: q.challenge,\n\t\trequestId: q.id,\n\t\texp,\n\t\tredirectLink: q.redirect || undefined,\n\t\tbridgeUrl: q.bridge || undefined\n\t}\n}\n\n/**\n * Build the same-device callback URI the wallet opens to return the connect\n * response to the dApp. `data` fields are plaintext connect material (the shared\n * key is derived from them); post-connect requests use sealed envelopes instead.\n */\nexport function buildConnectResponseUri(\n\tredirectLink: string,\n\tresponse: ConnectResponseParams\n): string {\n\tconst sep = redirectLink.includes('?') ? '&' : '?'\n\tconst query = buildQuery({\n\t\tid: response.requestId,\n\t\taddress: response.address,\n\t\twallet_key: response.walletPublicKey,\n\t\tsig: response.signature\n\t})\n\treturn `${redirectLink}${sep}${query}`\n}\n\n/** Parse a connect response from a callback URL's query string. */\nexport function parseConnectResponseUri(uri: string): ConnectResponseParams {\n\tconst q = parseQuery(uri.includes('?') ? uri.slice(uri.indexOf('?') + 1) : uri)\n\tif (!q.id || !q.address || !q.wallet_key || !q.sig) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'connect response is missing required fields')\n\t}\n\treturn {\n\t\trequestId: q.id,\n\t\taddress: q.address,\n\t\twalletPublicKey: q.wallet_key,\n\t\tsignature: q.sig\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AAeA,MAAa,aAAa;AAyB1B,SAAS,WAAW,SAAqD;CACxE,OAAO,OAAO,QAAQ,OAAO,CAAC,CAC5B,QAAQ,GAAG,OAAO,MAAM,KAAA,KAAa,MAAM,EAAE,CAAC,CAC9C,KAAK,CAAC,GAAG,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7E,IAAI,SAAS,cACZ,MAAM,IAAI,eAAe,oBAAoB,oBAAoB,KAAK,EAAE;CAEzE,MAAM,IAAI,WAAW,KAAK;CAC1B,MAAM,MAAM,OAAO,EAAE,GAAG;CACxB,IAAI,CAAC,EAAE,UAAU,CAAC,EAAE,YAAY,CAAC,EAAE,aAAa,CAAC,EAAE,MAAM,CAAC,OAAO,UAAU,GAAG,GAC7E,MAAM,IAAI,eAAe,oBAAoB,wCAAwC;CAEtF,OAAO;EACN,QAAQ,EAAE;EACV,eAAe,EAAE;EACjB,WAAW,EAAE;EACb,WAAW,EAAE;EACb;EACA,cAAc,EAAE,YAAY,KAAA;EAC5B,WAAW,EAAE,UAAU,KAAA;CACxB;AACD;;;;;;AAOA,SAAgB,wBACf,cACA,UACS;CAQT,OAAO,GAAG,eAPE,aAAa,SAAS,GAAG,IAAI,MAAM,MACjC,WAAW;EACxB,IAAI,SAAS;EACb,SAAS,SAAS;EAClB,YAAY,SAAS;EACrB,KAAK,SAAS;CACf,CACmC;AACpC;;AAGA,SAAgB,wBAAwB,KAAoC;CAC3E,MAAM,IAAI,WAAW,IAAI,SAAS,GAAG,IAAI,IAAI,MAAM,IAAI,QAAQ,GAAG,IAAI,CAAC,IAAI,GAAG;CAC9E,IAAI,CAAC,EAAE,MAAM,CAAC,EAAE,WAAW,CAAC,EAAE,cAAc,CAAC,EAAE,KAC9C,MAAM,IAAI,eAAe,oBAAoB,6CAA6C;CAE3F,OAAO;EACN,WAAW,EAAE;EACb,SAAS,EAAE;EACX,iBAAiB,EAAE;EACnB,WAAW,EAAE;CACd;AACD"}
|
package/dist/tx.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
//#region src/tx.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Transaction signing + submission.
|
|
4
|
+
*
|
|
5
|
+
* Signing reuses `@amadeus-protocol/sdk`'s `TransactionBuilder` verbatim (so the
|
|
6
|
+
* packed bytes are identical to what the extension produces today) and layers on
|
|
7
|
+
* the two behaviors the wallet's sign handler applies: restore JSON-transported
|
|
8
|
+
* binary args, and convert a `Coin.transfer` Base58 recipient to raw bytes.
|
|
9
|
+
* The wallet signs only; the caller submits the returned `txPacked` to a node.
|
|
10
|
+
*/
|
|
11
|
+
interface SignTransactionParams {
|
|
12
|
+
/** Base58 wallet seed (private key). */
|
|
13
|
+
seed: string;
|
|
14
|
+
contract: string;
|
|
15
|
+
method: string;
|
|
16
|
+
/** Args may contain tagged binary values (see `encodeBinaryValues`). */
|
|
17
|
+
args: unknown[];
|
|
18
|
+
description?: string;
|
|
19
|
+
}
|
|
20
|
+
interface SignedTransaction {
|
|
21
|
+
/** Base58 transaction hash. */
|
|
22
|
+
txHash: string;
|
|
23
|
+
/** Packed transaction bytes as a plain number[] — ready to POST to a node. */
|
|
24
|
+
txPacked: number[];
|
|
25
|
+
}
|
|
26
|
+
declare function signTransaction(params: SignTransactionParams): SignedTransaction;
|
|
27
|
+
interface SubmitTransactionOptions {
|
|
28
|
+
/** Base URL of the node API, e.g. "https://mainnet-rpc.ama.one/api". */
|
|
29
|
+
nodeUrl: string;
|
|
30
|
+
/** Wait for inclusion (`/tx/submit_and_wait`) vs fire-and-forget (`/tx/submit`). */
|
|
31
|
+
wait?: boolean;
|
|
32
|
+
/** Abort the request after this many ms. */
|
|
33
|
+
timeoutMs?: number;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Submit packed transaction bytes to a node as an octet-stream, the way the
|
|
37
|
+
* dApps do today. Returns the parsed JSON body when possible, else raw text.
|
|
38
|
+
*/
|
|
39
|
+
declare function submitTransaction(txPacked: number[] | Uint8Array, options: SubmitTransactionOptions): Promise<unknown>;
|
|
40
|
+
//#endregion
|
|
41
|
+
export { SignTransactionParams, SignedTransaction, SubmitTransactionOptions, signTransaction, submitTransaction };
|
|
42
|
+
//# sourceMappingURL=tx.d.ts.map
|
package/dist/tx.d.ts.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tx.d.ts","names":[],"sources":["../src/tx.ts"],"mappings":";;;;;;;;;;UAeiB;;EAEhB;EACA;EACA;;EAEA;EACA;;UAGgB;;EAEhB;;EAEA;;iBAGe,gBAAgB,QAAQ,wBAAwB;UAwB/C;;EAEhB;;EAEA;;EAEA;;;;;;iBAOqB,kBACrB,qBAAqB,YACrB,SAAS,2BACP"}
|
package/dist/tx.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { WalletSdkError } from "./errors.js";
|
|
2
|
+
import { decodeBinaryValues } from "./binary.js";
|
|
3
|
+
import { TransactionBuilder, fromBase58 } from "@amadeus-protocol/sdk";
|
|
4
|
+
//#region src/tx.ts
|
|
5
|
+
/**
|
|
6
|
+
* Transaction signing + submission.
|
|
7
|
+
*
|
|
8
|
+
* Signing reuses `@amadeus-protocol/sdk`'s `TransactionBuilder` verbatim (so the
|
|
9
|
+
* packed bytes are identical to what the extension produces today) and layers on
|
|
10
|
+
* the two behaviors the wallet's sign handler applies: restore JSON-transported
|
|
11
|
+
* binary args, and convert a `Coin.transfer` Base58 recipient to raw bytes.
|
|
12
|
+
* The wallet signs only; the caller submits the returned `txPacked` to a node.
|
|
13
|
+
*/
|
|
14
|
+
function signTransaction(params) {
|
|
15
|
+
const builder = new TransactionBuilder(params.seed);
|
|
16
|
+
let processedArgs = decodeBinaryValues(params.args);
|
|
17
|
+
if (params.contract === "Coin" && params.method === "transfer" && typeof processedArgs[0] === "string") processedArgs = [
|
|
18
|
+
fromBase58(processedArgs[0]),
|
|
19
|
+
processedArgs[1],
|
|
20
|
+
processedArgs[2]
|
|
21
|
+
];
|
|
22
|
+
const { txHash, txPacked } = builder.buildAndSign(params.contract, params.method, processedArgs);
|
|
23
|
+
return {
|
|
24
|
+
txHash,
|
|
25
|
+
txPacked: Array.from(txPacked)
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Submit packed transaction bytes to a node as an octet-stream, the way the
|
|
30
|
+
* dApps do today. Returns the parsed JSON body when possible, else raw text.
|
|
31
|
+
*/
|
|
32
|
+
async function submitTransaction(txPacked, options) {
|
|
33
|
+
if (!/^https?:\/\//.test(options.nodeUrl)) throw new WalletSdkError("INVALID_ARGUMENT", "nodeUrl must be an http(s) URL");
|
|
34
|
+
const bytes = txPacked instanceof Uint8Array ? txPacked : Uint8Array.from(txPacked);
|
|
35
|
+
const body = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
36
|
+
const path = options.wait ? "/tx/submit_and_wait" : "/tx/submit";
|
|
37
|
+
const url = `${options.nodeUrl.replace(/\/$/, "")}${path}`;
|
|
38
|
+
const controller = new AbortController();
|
|
39
|
+
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 3e4);
|
|
40
|
+
try {
|
|
41
|
+
const res = await fetch(url, {
|
|
42
|
+
method: "POST",
|
|
43
|
+
headers: { "Content-Type": "application/octet-stream" },
|
|
44
|
+
body,
|
|
45
|
+
signal: controller.signal
|
|
46
|
+
});
|
|
47
|
+
const text = await res.text();
|
|
48
|
+
if (!res.ok) throw new WalletSdkError("SUBMIT_FAILED", `node returned ${res.status}: ${text}`);
|
|
49
|
+
try {
|
|
50
|
+
return JSON.parse(text);
|
|
51
|
+
} catch {
|
|
52
|
+
return text;
|
|
53
|
+
}
|
|
54
|
+
} finally {
|
|
55
|
+
clearTimeout(timer);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
//#endregion
|
|
59
|
+
export { signTransaction, submitTransaction };
|
|
60
|
+
|
|
61
|
+
//# sourceMappingURL=tx.js.map
|
package/dist/tx.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tx.js","names":[],"sources":["../src/tx.ts"],"sourcesContent":["/**\n * Transaction signing + submission.\n *\n * Signing reuses `@amadeus-protocol/sdk`'s `TransactionBuilder` verbatim (so the\n * packed bytes are identical to what the extension produces today) and layers on\n * the two behaviors the wallet's sign handler applies: restore JSON-transported\n * binary args, and convert a `Coin.transfer` Base58 recipient to raw bytes.\n * The wallet signs only; the caller submits the returned `txPacked` to a node.\n */\n\nimport { fromBase58, type SerializableValue, TransactionBuilder } from '@amadeus-protocol/sdk'\n\nimport { decodeBinaryValues } from './binary'\nimport { WalletSdkError } from './errors'\n\nexport interface SignTransactionParams {\n\t/** Base58 wallet seed (private key). */\n\tseed: string\n\tcontract: string\n\tmethod: string\n\t/** Args may contain tagged binary values (see `encodeBinaryValues`). */\n\targs: unknown[]\n\tdescription?: string\n}\n\nexport interface SignedTransaction {\n\t/** Base58 transaction hash. */\n\ttxHash: string\n\t/** Packed transaction bytes as a plain number[] — ready to POST to a node. */\n\ttxPacked: number[]\n}\n\nexport function signTransaction(params: SignTransactionParams): SignedTransaction {\n\tconst builder = new TransactionBuilder(params.seed)\n\n\t// Restore any binary args that were wrapped for a JSON/text transport.\n\tlet processedArgs = decodeBinaryValues(params.args) as unknown[]\n\n\t// Coin.transfer's recipient (arg 0) is a Base58 address on the wire but must\n\t// be raw bytes for the SDK to encode it as BYTES. Matches the extension.\n\tif (\n\t\tparams.contract === 'Coin' &&\n\t\tparams.method === 'transfer' &&\n\t\ttypeof processedArgs[0] === 'string'\n\t) {\n\t\tprocessedArgs = [fromBase58(processedArgs[0]), processedArgs[1], processedArgs[2]]\n\t}\n\n\tconst { txHash, txPacked } = builder.buildAndSign(\n\t\tparams.contract,\n\t\tparams.method,\n\t\tprocessedArgs as SerializableValue[]\n\t)\n\treturn { txHash, txPacked: Array.from(txPacked) }\n}\n\nexport interface SubmitTransactionOptions {\n\t/** Base URL of the node API, e.g. \"https://mainnet-rpc.ama.one/api\". */\n\tnodeUrl: string\n\t/** Wait for inclusion (`/tx/submit_and_wait`) vs fire-and-forget (`/tx/submit`). */\n\twait?: boolean\n\t/** Abort the request after this many ms. */\n\ttimeoutMs?: number\n}\n\n/**\n * Submit packed transaction bytes to a node as an octet-stream, the way the\n * dApps do today. Returns the parsed JSON body when possible, else raw text.\n */\nexport async function submitTransaction(\n\ttxPacked: number[] | Uint8Array,\n\toptions: SubmitTransactionOptions\n): Promise<unknown> {\n\t// nodeUrl is trusted config, but guard the scheme so a stray file:// or other\n\t// non-http target can never be fetched.\n\tif (!/^https?:\\/\\//.test(options.nodeUrl)) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'nodeUrl must be an http(s) URL')\n\t}\n\n\tconst bytes = txPacked instanceof Uint8Array ? txPacked : Uint8Array.from(txPacked)\n\t// Hand fetch a standalone ArrayBuffer — a clean BodyInit across DOM lib\n\t// versions and RN, and it never carries a shared/offset backing buffer.\n\tconst body = bytes.buffer.slice(\n\t\tbytes.byteOffset,\n\t\tbytes.byteOffset + bytes.byteLength\n\t) as ArrayBuffer\n\tconst path = options.wait ? '/tx/submit_and_wait' : '/tx/submit'\n\tconst url = `${options.nodeUrl.replace(/\\/$/, '')}${path}`\n\n\t// Always arm a timeout so a hung node can't block the caller forever.\n\tconst controller = new AbortController()\n\tconst timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 30_000)\n\n\ttry {\n\t\tconst res = await fetch(url, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: { 'Content-Type': 'application/octet-stream' },\n\t\t\tbody,\n\t\t\tsignal: controller.signal\n\t\t})\n\t\tconst text = await res.text()\n\t\tif (!res.ok) {\n\t\t\tthrow new WalletSdkError('SUBMIT_FAILED', `node returned ${res.status}: ${text}`)\n\t\t}\n\t\ttry {\n\t\t\treturn JSON.parse(text)\n\t\t} catch {\n\t\t\treturn text\n\t\t}\n\t} finally {\n\t\tclearTimeout(timer)\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;AAgCA,SAAgB,gBAAgB,QAAkD;CACjF,MAAM,UAAU,IAAI,mBAAmB,OAAO,IAAI;CAGlD,IAAI,gBAAgB,mBAAmB,OAAO,IAAI;CAIlD,IACC,OAAO,aAAa,UACpB,OAAO,WAAW,cAClB,OAAO,cAAc,OAAO,UAE5B,gBAAgB;EAAC,WAAW,cAAc,EAAE;EA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