@oneswap/dapp-sdk 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +133 -2
- package/browser.d.ts +5 -0
- package/browser.js +20 -0
- package/example/accessChecks.mjs +22 -0
- package/example/proxyAuth.mjs +9 -0
- package/example/rewardProposals.mjs +32 -0
- package/example/server.mjs +416 -0
- package/package.json +39 -4
- package/server.d.ts +39 -0
- package/server.js +100 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 OneSwap
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,134 @@
|
|
|
1
|
-
#
|
|
1
|
+
# OneSwap dApp SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Connect a OneSwap Wallet to your website, check holder eligibility with user consent, accept a token payment and propose creator-funded rewards. The SDK includes an ESM server client for Node.js 20+ and separate browser helpers. Both entry points include TypeScript declarations.
|
|
4
|
+
|
|
5
|
+
## Install and register your site
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @oneswap/dapp-sdk@0.2.0
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Start on DevNet. Open **My launches → dApps** with the token's creator wallet, choose the token, register its official HTTPS website and callback, verify the domain, and create a server key. Save the app ID and secret in your backend’s secret store. Configure holder requirements and experiences in the same tab. [DevNet dashboard](https://devnet.oneswap.cc/launchpad/launches?tab=dapps) · [Creator integration guide](https://docs.oneswap.cc/guides/creator-dapp-sdk)
|
|
12
|
+
|
|
13
|
+
Choose the network explicitly on the server and in browser calls. Use each network’s own registration, callback, credentials and order records.
|
|
14
|
+
|
|
15
|
+
```js
|
|
16
|
+
import { createDappClient } from '@oneswap/dapp-sdk/server';
|
|
17
|
+
|
|
18
|
+
const network = 'devnet';
|
|
19
|
+
const sdk = createDappClient({
|
|
20
|
+
network,
|
|
21
|
+
appId: process.env.DAPP_ID,
|
|
22
|
+
secret: process.env.DAPP_SECRET,
|
|
23
|
+
redirectUri: 'https://members.example/callback',
|
|
24
|
+
});
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Sign in with OneSwap Wallet
|
|
28
|
+
|
|
29
|
+
Start sign-in on your backend. Save the SDK's pending request in a server-side session for this visitor before redirecting them to OneSwap for consent.
|
|
30
|
+
|
|
31
|
+
```js
|
|
32
|
+
const { url, pending } = sdk.auth.startSignIn();
|
|
33
|
+
// Store pending in this visitor’s server-side session, then redirect to url.
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
At your registered callback, consume the pending request once and exchange the returned code. The SDK verifies the callback and PKCE challenge. Supply the complete callback URL using your registered origin. Keep the callback query and tokens out of application logs, then redirect the visitor to a clean URL.
|
|
37
|
+
|
|
38
|
+
```js
|
|
39
|
+
const tokens = await sdk.auth.finishSignIn(pending, callbackUrl);
|
|
40
|
+
const member = await sdk.auth.me(tokens.access_token);
|
|
41
|
+
// Rotate the session and store the token, its expiry and member.subject on the server.
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Use the app-specific `member.subject` as your site's member ID. Start sign-in again when the access token expires. The visitor can disconnect in OneSwap Wallet, or your server can call `sdk.auth.revoke(accessToken)` and clear their local session.
|
|
45
|
+
|
|
46
|
+
## Gate an experience
|
|
47
|
+
|
|
48
|
+
Your backend enforces access before serving protected content. OneSwap returns a decision for the specific approved rule. It keeps the wallet’s balance private. Editing a requirement keeps its integration ID and requires fresh consent for the updated terms.
|
|
49
|
+
|
|
50
|
+
```js
|
|
51
|
+
import { hasFreshHolderAccess } from '@oneswap/dapp-sdk/server';
|
|
52
|
+
|
|
53
|
+
const result = await sdk.eligibility.check(session.accessToken, 'holder');
|
|
54
|
+
const allowed = hasFreshHolderAccess(result, {
|
|
55
|
+
appId: process.env.DAPP_ID,
|
|
56
|
+
subject: session.subject,
|
|
57
|
+
ruleId: 'holder',
|
|
58
|
+
network: 'canton:da-devnet',
|
|
59
|
+
});
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Grant access only when `allowed` is true. An `unknown` result means the holding could not be verified. Holder access is available both on the bonding curve and after graduation.
|
|
63
|
+
|
|
64
|
+
## Accept a token payment
|
|
65
|
+
|
|
66
|
+
Checkout becomes available after graduation and liquidity migration, when the token is transferable. Check `member.capabilities.checkout`. Each purchase uses one token. Create and store a stable order ID on your backend before calling OneSwap.
|
|
67
|
+
|
|
68
|
+
```js
|
|
69
|
+
const payment = await sdk.payments.create(session.accessToken, {
|
|
70
|
+
orderId: savedOrder.orderId,
|
|
71
|
+
experienceId: savedOrder.experienceId,
|
|
72
|
+
});
|
|
73
|
+
// Persist payment.id with the expected member, amount, symbol and experience for this order.
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Open the wallet checkout from your frontend.
|
|
77
|
+
|
|
78
|
+
```js
|
|
79
|
+
import { openCheckout } from '@oneswap/dapp-sdk/browser';
|
|
80
|
+
openCheckout(paymentId, 'devnet');
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Fetch the merchant receipt on your backend and match it against your saved order before delivering the item.
|
|
84
|
+
|
|
85
|
+
```js
|
|
86
|
+
import { isPaidReceiptFor } from '@oneswap/dapp-sdk/server';
|
|
87
|
+
|
|
88
|
+
const receipt = await sdk.payments.receipt(savedOrder.id);
|
|
89
|
+
if (isPaidReceiptFor(receipt, savedOrder)) {
|
|
90
|
+
// Atomically grant the entitlement once for this order.
|
|
91
|
+
}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
`savedOrder` contains `id` (the OneSwap payment ID), `orderId`, `subject`, `experienceId`, `amount` (decimal string) and `symbol`. Reuse the order ID when recovering an interrupted request. Keep pending or uncertain payments open for reconciliation. After expiry or decline, ask the member before creating a new purchase attempt. Existing invoices keep their original terms when the creator edits an experience.
|
|
95
|
+
|
|
96
|
+
## Propose and track rewards
|
|
97
|
+
|
|
98
|
+
Check `member.capabilities.rewards` before proposing a payout. Your server submits a stable event ID, the recipient's app-specific member ID and the token amount.
|
|
99
|
+
|
|
100
|
+
```js
|
|
101
|
+
const batch = await sdk.rewards.propose(eventId, [
|
|
102
|
+
{ recipientId: member.subject, amount: '1' },
|
|
103
|
+
]);
|
|
104
|
+
// Persist batch.id for this event and reuse eventId if the request is interrupted.
|
|
105
|
+
const receipt = await sdk.rewards.receipt(session.accessToken, batch.id);
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
The creator reviews the exact recipients, amounts and fee, approves the batch and funds it from their own wallet. A recipient may need to accept the transfer. Show delivery only when the member’s receipt reports `delivered`. A proposed or funded batch can still be pending.
|
|
109
|
+
|
|
110
|
+
In **My launches → dApps → Reward batches**, the creator can dismiss an unapproved draft. This frees a draft slot and closes the batch. A retry with the same event ID and awards returns the original dismissed batch. Handle `dismissed` as a terminal outcome with no payout.
|
|
111
|
+
|
|
112
|
+
## Run the included example
|
|
113
|
+
|
|
114
|
+
The membership-site example requires **Node.js 22.13+** for `node:sqlite`. Install the package in your project and configure `DAPP_NETWORK=devnet`, `DAPP_ID`, `DAPP_SECRET` and `EXAMPLE_ORIGIN` in your server environment. Use your exact registered HTTPS origin, with its callback at `/callback`. Set `RULE_ID` for holder access and `EXPERIENCE_ID` for checkout.
|
|
115
|
+
|
|
116
|
+
```sh
|
|
117
|
+
node ./node_modules/@oneswap/dapp-sdk/example/server.mjs
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Forward your registered HTTPS website to the example’s loopback listener (port 3481 by default, configurable via `PORT`). Set `EXAMPLE_DATABASE` to a writable, persistent SQLite file outside your public web directory. Use a separate database for each network. Orders and fulfillment survive a process restart. Visitor sessions live in memory on this example's single server.
|
|
121
|
+
|
|
122
|
+
From the same environment and database, you can propose a test reward for a connected DevNet member. Copy their app-specific member ID from their example page.
|
|
123
|
+
|
|
124
|
+
```sh
|
|
125
|
+
node ./node_modules/@oneswap/dapp-sdk/example/server.mjs --propose-reward welcome-001 "$MEMBER_ID" 1
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
Return to **My launches → dApps → Reward batches** to review and fund the proposal.
|
|
129
|
+
|
|
130
|
+
## Handling errors
|
|
131
|
+
|
|
132
|
+
The server client reports `DappApiError.status` and `.code`. For a 429, wait for `retryAfterMs` when provided. For `RULE_NOT_CONSENTED`, invite the member to reconnect and review the new terms. For `INVALID_CLIENT`, have the site operator check the app's backend credentials. Use the existing order or reward event to reconcile a transfer after an interruption.
|
|
133
|
+
|
|
134
|
+
MIT licensed. [License](./LICENSE)
|
package/browser.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
type DappNetwork = 'devnet' | 'mainnet';
|
|
2
|
+
export function walletOrigin(network: DappNetwork): string;
|
|
3
|
+
export function checkoutUrl(paymentId: string, network: DappNetwork): string;
|
|
4
|
+
export function openCheckout(paymentId: string, network: DappNetwork): void;
|
|
5
|
+
export function signIn(authorizeUrl: string, network: DappNetwork): void;
|
package/browser.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** Only the canonical OneSwap wallet for the explicitly selected network can receive a request. */
|
|
2
|
+
export function walletOrigin(network) {
|
|
3
|
+
if (network === 'devnet') return 'https://devnet.oneswap.cc';
|
|
4
|
+
if (network === 'mainnet') return 'https://www.oneswap.cc';
|
|
5
|
+
throw new TypeError('Choose the OneSwap devnet or mainnet network.');
|
|
6
|
+
}
|
|
7
|
+
export function checkoutUrl(paymentId, network) {
|
|
8
|
+
if (typeof paymentId !== 'string' || !/^dpc_[A-Za-z0-9_-]{43}$/.test(paymentId)) throw new TypeError('Invalid payment ID.');
|
|
9
|
+
return walletOrigin(network) + '/dapps/checkout?id=' + encodeURIComponent(paymentId);
|
|
10
|
+
}
|
|
11
|
+
export function openCheckout(paymentId, network) {
|
|
12
|
+
window.location.assign(checkoutUrl(paymentId, network));
|
|
13
|
+
}
|
|
14
|
+
export function signIn(authorizeUrl, network) {
|
|
15
|
+
const url = new URL(authorizeUrl);
|
|
16
|
+
if (url.origin !== walletOrigin(network) || url.pathname !== '/dapps/authorize' || url.username || url.password || url.hash) {
|
|
17
|
+
throw new TypeError('Invalid OneSwap sign-in URL.');
|
|
18
|
+
}
|
|
19
|
+
window.location.assign(url.href);
|
|
20
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export { hasFreshHolderAccess } from '../server.js';
|
|
2
|
+
import { isPaidReceiptFor } from '../server.js';
|
|
3
|
+
|
|
4
|
+
export function checkoutOrderRef(order) {
|
|
5
|
+
const attempt = order.attempt ?? 1;
|
|
6
|
+
return attempt === 1 ? order.order_id : order.order_id + '-r' + attempt;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function receiptMatchesOrder(payment, order, { subject, experienceId }) {
|
|
10
|
+
return typeof order.payment_id === 'string' && payment?.id === order.payment_id
|
|
11
|
+
&& payment.orderId === checkoutOrderRef(order) && payment.subject === subject
|
|
12
|
+
&& payment.experienceId === experienceId && typeof order.expected_amount === 'string'
|
|
13
|
+
&& typeof order.expected_symbol === 'string'
|
|
14
|
+
&& payment.amount === order.expected_amount && payment.symbol === order.expected_symbol;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function paidReceiptMatches(payment, order, scope) {
|
|
18
|
+
return isPaidReceiptFor(payment, {
|
|
19
|
+
id: order.payment_id, orderId: checkoutOrderRef(order), subject: scope.subject,
|
|
20
|
+
experienceId: scope.experienceId, amount: order.expected_amount, symbol: order.expected_symbol,
|
|
21
|
+
});
|
|
22
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { timingSafeEqual } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
export function isAuthorizedExampleProxy(headers, expected) {
|
|
4
|
+
if (!expected) return true;
|
|
5
|
+
const supplied = headers['x-onepump-example-proxy'];
|
|
6
|
+
if (typeof supplied !== 'string' || supplied.length > 128) return false;
|
|
7
|
+
const left = Buffer.from(supplied), right = Buffer.from(expected);
|
|
8
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
9
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// This module is used only by the example server and its operator CLI.
|
|
2
|
+
// A draft can be recovered after a lost response by reusing its immutable event ID.
|
|
3
|
+
export function exampleRewards(db, appId) {
|
|
4
|
+
db.exec(`
|
|
5
|
+
CREATE TABLE IF NOT EXISTS sample_reward_proposals (
|
|
6
|
+
app TEXT NOT NULL, event TEXT NOT NULL, subject TEXT NOT NULL, amount TEXT NOT NULL,
|
|
7
|
+
batch TEXT, PRIMARY KEY(app, event)
|
|
8
|
+
);
|
|
9
|
+
CREATE INDEX IF NOT EXISTS sample_rewards_member ON sample_reward_proposals(app, subject);
|
|
10
|
+
`);
|
|
11
|
+
const reserve = db.prepare('INSERT INTO sample_reward_proposals(app,event,subject,amount) VALUES(?,?,?,?) ON CONFLICT(app,event) DO NOTHING');
|
|
12
|
+
const lookup = db.prepare('SELECT subject, amount, batch FROM sample_reward_proposals WHERE app=? AND event=?');
|
|
13
|
+
const record = db.prepare('UPDATE sample_reward_proposals SET batch=? WHERE app=? AND event=? AND (batch IS NULL OR batch=?)');
|
|
14
|
+
const recent = db.prepare('SELECT batch FROM sample_reward_proposals WHERE app=? AND subject=? AND batch IS NOT NULL ORDER BY rowid DESC LIMIT 1');
|
|
15
|
+
return {
|
|
16
|
+
latestBatch(subject) { return recent.get(appId, subject)?.batch; },
|
|
17
|
+
async propose(sdk, event, subject, amount) {
|
|
18
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(event) || !/^aps_[a-zA-Z0-9_-]{43}$/.test(subject)
|
|
19
|
+
|| !/^(?:0|[1-9]\d{0,9})(?:\.\d{1,10})?$/.test(amount) || !/[1-9]/.test(amount)) {
|
|
20
|
+
throw new Error('Provide an event ID, an app-specific member ID and a positive decimal amount.');
|
|
21
|
+
}
|
|
22
|
+
reserve.run(appId, event, subject, amount);
|
|
23
|
+
const stored = lookup.get(appId, event);
|
|
24
|
+
if (stored.subject !== subject || stored.amount !== amount) throw new Error('This event ID already belongs to a different proposal.');
|
|
25
|
+
if (stored.batch) return stored.batch;
|
|
26
|
+
const batch = await sdk.rewards.propose(event, [{ recipientId: subject, amount }]);
|
|
27
|
+
if (batch?.eventId !== event || typeof batch.id !== 'string' || !/^rwb_[0-9a-f]{40}$/.test(batch.id)) throw new Error('Unexpected reward proposal response.');
|
|
28
|
+
if (record.run(batch.id, appId, event, batch.id).changes !== 1) throw new Error('Reward proposal identity changed.');
|
|
29
|
+
return batch.id;
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
}
|
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
// Run behind the registered HTTPS reverse proxy using Node 22.13 or newer.
|
|
2
|
+
import { createServer } from 'node:http';
|
|
3
|
+
import { randomBytes, createHash } from 'node:crypto';
|
|
4
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
5
|
+
import { createDappClient, hasFreshHolderAccess } from '../server.js';
|
|
6
|
+
import { checkoutUrl, walletOrigin } from '../browser.js';
|
|
7
|
+
import { isAuthorizedExampleProxy } from './proxyAuth.mjs';
|
|
8
|
+
import { checkoutOrderRef, paidReceiptMatches, receiptMatchesOrder } from './accessChecks.mjs';
|
|
9
|
+
import { exampleRewards } from './rewardProposals.mjs';
|
|
10
|
+
|
|
11
|
+
const { DAPP_ID, DAPP_SECRET, EXAMPLE_ORIGIN, RULE_ID, EXPERIENCE_ID, REWARD_BATCH_ID } = process.env;
|
|
12
|
+
const network = process.env.DAPP_NETWORK;
|
|
13
|
+
const wallet = walletOrigin(network);
|
|
14
|
+
const networkLabel = network === 'mainnet' ? 'MainNet' : 'DevNet';
|
|
15
|
+
const proxyToken = process.env.EXAMPLE_PROXY_TOKEN;
|
|
16
|
+
if (proxyToken && !/^[A-Za-z0-9_-]{43,128}$/.test(proxyToken))
|
|
17
|
+
throw new Error('EXAMPLE_PROXY_TOKEN must be an unpredictable URL-safe credential.');
|
|
18
|
+
if (
|
|
19
|
+
!DAPP_ID ||
|
|
20
|
+
!DAPP_SECRET ||
|
|
21
|
+
!EXAMPLE_ORIGIN ||
|
|
22
|
+
new URL(EXAMPLE_ORIGIN).origin !== EXAMPLE_ORIGIN ||
|
|
23
|
+
!EXAMPLE_ORIGIN.startsWith('https://')
|
|
24
|
+
)
|
|
25
|
+
throw new Error('Configure the app ID, secret and exact HTTPS origin.');
|
|
26
|
+
const sdk = createDappClient({
|
|
27
|
+
network,
|
|
28
|
+
appId: DAPP_ID,
|
|
29
|
+
secret: DAPP_SECRET,
|
|
30
|
+
redirectUri: EXAMPLE_ORIGIN + '/callback',
|
|
31
|
+
});
|
|
32
|
+
// Orders and app-specific member identifiers are private to this backend.
|
|
33
|
+
process.umask(0o077);
|
|
34
|
+
const db = new DatabaseSync(process.env.EXAMPLE_DATABASE ?? (network === 'mainnet' ? 'experience-mainnet.sqlite' : 'experience.sqlite'));
|
|
35
|
+
// Older example databases contain DevNet orders. Bind every database to its
|
|
36
|
+
// network before loading orders, using a transaction across concurrent starts.
|
|
37
|
+
db.exec('BEGIN IMMEDIATE');
|
|
38
|
+
try {
|
|
39
|
+
const existing = db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='orders'").get();
|
|
40
|
+
db.exec("CREATE TABLE IF NOT EXISTS example_network (id INTEGER PRIMARY KEY CHECK (id = 1), name TEXT NOT NULL)");
|
|
41
|
+
db.prepare('INSERT OR IGNORE INTO example_network (id, name) VALUES (1, ?)').run(existing ? 'devnet' : network);
|
|
42
|
+
if (db.prepare('SELECT name FROM example_network WHERE id=1').get().name !== network) {
|
|
43
|
+
throw new Error('Use a separate example database for each OneSwap network.');
|
|
44
|
+
}
|
|
45
|
+
db.exec('COMMIT');
|
|
46
|
+
} catch (error) {
|
|
47
|
+
db.exec('ROLLBACK');
|
|
48
|
+
db.close();
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
db.exec(`
|
|
52
|
+
CREATE TABLE IF NOT EXISTS orders (
|
|
53
|
+
app TEXT, subject TEXT, experience TEXT,
|
|
54
|
+
order_id TEXT UNIQUE, payment_id TEXT, delivered_at TEXT,
|
|
55
|
+
expected_amount TEXT, expected_symbol TEXT, attempt INTEGER NOT NULL DEFAULT 1,
|
|
56
|
+
PRIMARY KEY (app, subject, experience)
|
|
57
|
+
)
|
|
58
|
+
`);
|
|
59
|
+
db.exec('PRAGMA busy_timeout = 5000');
|
|
60
|
+
const rewards = exampleRewards(db, DAPP_ID);
|
|
61
|
+
if (process.argv.length > 2) {
|
|
62
|
+
const [command, eventId, subject, amount] = process.argv.slice(2);
|
|
63
|
+
if (command !== '--propose-reward' || process.argv.length !== 6) {
|
|
64
|
+
console.error('Usage: node example/server.mjs --propose-reward EVENT_ID MEMBER_ID AMOUNT');
|
|
65
|
+
process.exit(2);
|
|
66
|
+
}
|
|
67
|
+
try {
|
|
68
|
+
const batchId = await rewards.propose(sdk, eventId, subject, amount);
|
|
69
|
+
console.log('Reward batch ' + batchId + '. Review and fund it in My launches → dApps.');
|
|
70
|
+
db.close();
|
|
71
|
+
process.exit(0);
|
|
72
|
+
} catch (error) {
|
|
73
|
+
console.error(error.code ? 'Reward proposal failed: ' + error.code : error.message);
|
|
74
|
+
db.close();
|
|
75
|
+
process.exit(1);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const orderColumns = new Set(
|
|
79
|
+
db
|
|
80
|
+
.prepare('PRAGMA table_info(orders)')
|
|
81
|
+
.all()
|
|
82
|
+
.map((column) => column.name),
|
|
83
|
+
);
|
|
84
|
+
for (const column of ['expected_amount', 'expected_symbol'])
|
|
85
|
+
if (!orderColumns.has(column)) db.exec(`ALTER TABLE orders ADD COLUMN ${column} TEXT`);
|
|
86
|
+
if (!orderColumns.has('attempt')) db.exec('ALTER TABLE orders ADD COLUMN attempt INTEGER NOT NULL DEFAULT 1');
|
|
87
|
+
db.exec(`CREATE TABLE IF NOT EXISTS closed_checkout_attempts (
|
|
88
|
+
payment_id TEXT PRIMARY KEY, order_id TEXT NOT NULL, attempt INTEGER NOT NULL,
|
|
89
|
+
status TEXT NOT NULL, closed_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, UNIQUE(order_id, attempt)
|
|
90
|
+
)`);
|
|
91
|
+
const findOrder = db.prepare('SELECT * FROM orders WHERE app = ? AND subject = ? AND experience = ?');
|
|
92
|
+
const reserveOrder = db.prepare(`
|
|
93
|
+
INSERT INTO orders (app, subject, experience, order_id) VALUES (?, ?, ?, ?)
|
|
94
|
+
ON CONFLICT (app, subject, experience) DO NOTHING
|
|
95
|
+
`);
|
|
96
|
+
const bindInvoice = db.prepare(`
|
|
97
|
+
UPDATE orders
|
|
98
|
+
SET payment_id = :id,
|
|
99
|
+
expected_amount = COALESCE(expected_amount, :amount),
|
|
100
|
+
expected_symbol = COALESCE(expected_symbol, :symbol)
|
|
101
|
+
WHERE order_id = :order AND attempt = :attempt AND (payment_id IS NULL OR payment_id = :id)
|
|
102
|
+
AND (expected_amount IS NULL OR expected_amount = :amount)
|
|
103
|
+
AND (expected_symbol IS NULL OR expected_symbol = :symbol)
|
|
104
|
+
`);
|
|
105
|
+
const replaceClosedInvoice = db.prepare(`
|
|
106
|
+
UPDATE orders SET attempt = attempt + 1, payment_id = NULL, expected_amount = NULL, expected_symbol = NULL
|
|
107
|
+
WHERE order_id = ? AND payment_id = ? AND attempt = ? AND delivered_at IS NULL
|
|
108
|
+
`);
|
|
109
|
+
const archiveAttempt = db.prepare('INSERT INTO closed_checkout_attempts(payment_id,order_id,attempt,status) VALUES(?,?,?,?)');
|
|
110
|
+
function advanceClosedInvoice(order, status) {
|
|
111
|
+
db.exec('BEGIN IMMEDIATE');
|
|
112
|
+
try {
|
|
113
|
+
if (replaceClosedInvoice.run(order.order_id, order.payment_id, order.attempt).changes === 1)
|
|
114
|
+
archiveAttempt.run(order.payment_id, order.order_id, order.attempt, status);
|
|
115
|
+
db.exec('COMMIT');
|
|
116
|
+
} catch (err) {
|
|
117
|
+
db.exec('ROLLBACK');
|
|
118
|
+
throw err;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const markDelivered = db.prepare(`
|
|
122
|
+
UPDATE orders SET delivered_at = CURRENT_TIMESTAMP WHERE order_id = ? AND payment_id = ? AND delivered_at IS NULL
|
|
123
|
+
`);
|
|
124
|
+
|
|
125
|
+
const sessions = new Map();
|
|
126
|
+
const hash = (s) => createHash('sha256').update(s).digest('hex');
|
|
127
|
+
const token = () => randomBytes(32).toString('base64url');
|
|
128
|
+
const cookie = '__Host-onepump-demo';
|
|
129
|
+
const siteStyle = `
|
|
130
|
+
:root{color-scheme:light dark;font:16px/1.6 system-ui,sans-serif;background:#f4f5ef;color:#17201c}
|
|
131
|
+
*{box-sizing:border-box}body{margin:0}header,main{width:min(640px,100%);margin:auto;padding:22px clamp(18px,4vw,32px)}
|
|
132
|
+
header{display:flex;justify-content:space-between;border-bottom:1px solid #a5b2a5;color:#394a3c;font-size:13px}
|
|
133
|
+
h1{font-size:clamp(33px,6vw,54px);line-height:1.08;letter-spacing:-.045em;margin:22px 0 18px}
|
|
134
|
+
h2{font-size:21px;line-height:1.3;margin:28px 0 5px}p{margin:8px 0 15px}a{color:inherit}
|
|
135
|
+
button{border:0;border-radius:5px;background:#244534;color:#fff;min-height:44px;padding:10px 15px;font:600 14px/1.3 system-ui;cursor:pointer}
|
|
136
|
+
button:focus-visible,a:focus-visible,summary:focus-visible{outline:3px solid #6f977c;outline-offset:3px}
|
|
137
|
+
form{margin:17px 0}details{border-block:1px solid #b5c1b5;padding:11px 0}summary{cursor:pointer;font-size:14px}code{font-size:12px;overflow-wrap:anywhere}
|
|
138
|
+
@media(prefers-color-scheme:dark){:root{background:#17201c;color:#edf1e8}header{color:#bbc7b9;border-color:#425344}details{border-color:#425344}button{background:#c5e6bd;color:#193024}}
|
|
139
|
+
`;
|
|
140
|
+
const styleHash = createHash('sha256').update(siteStyle).digest('base64');
|
|
141
|
+
function prune() {
|
|
142
|
+
for (const [id, s] of sessions) if (s.expires <= Date.now()) sessions.delete(id);
|
|
143
|
+
}
|
|
144
|
+
const sweep = setInterval(prune, 60000);
|
|
145
|
+
sweep.unref();
|
|
146
|
+
const escape = (s) =>
|
|
147
|
+
String(s).replace(
|
|
148
|
+
/[&<>"']/g,
|
|
149
|
+
(c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],
|
|
150
|
+
);
|
|
151
|
+
const action = (p, label) =>
|
|
152
|
+
'<form action="' + p + '" method="post"><button>' + label + '</button></form>';
|
|
153
|
+
createServer(async (req, res) => {
|
|
154
|
+
if (!isAuthorizedExampleProxy(req.headers, proxyToken)) {
|
|
155
|
+
res.writeHead(404, { 'Cache-Control': 'no-store' });
|
|
156
|
+
res.end();
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
let url;
|
|
160
|
+
try {
|
|
161
|
+
url = new URL(req.url, EXAMPLE_ORIGIN);
|
|
162
|
+
if (url.origin !== EXAMPLE_ORIGIN) throw new Error('Unexpected origin');
|
|
163
|
+
} catch {
|
|
164
|
+
res.writeHead(400, { 'Cache-Control': 'no-store' });
|
|
165
|
+
res.end();
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
res.setHeader('Cache-Control', 'private, no-store');
|
|
169
|
+
// Browsers send Origin: null on HTML form posts from a no-referrer document.
|
|
170
|
+
const servesForms = req.method === 'GET' && url.pathname === '/';
|
|
171
|
+
res.setHeader('Referrer-Policy', servesForms ? 'same-origin' : 'no-referrer');
|
|
172
|
+
res.setHeader(
|
|
173
|
+
'Content-Security-Policy',
|
|
174
|
+
`default-src 'none'; style-src 'sha256-${styleHash}'; form-action 'self' ${wallet}; frame-ancestors 'none'; base-uri 'none'`,
|
|
175
|
+
);
|
|
176
|
+
const key = /(?:^|; )__Host-onepump-demo=([A-Za-z0-9_-]{43})(?:;|$)/.exec(
|
|
177
|
+
req.headers.cookie ?? '',
|
|
178
|
+
)?.[1];
|
|
179
|
+
let session = key ? sessions.get(hash(key)) : undefined;
|
|
180
|
+
if (session?.expires <= Date.now()) session = undefined;
|
|
181
|
+
function send(status, body) {
|
|
182
|
+
res.setHeader('X-Example-Style-Hash', styleHash);
|
|
183
|
+
res.writeHead(status, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
184
|
+
res.end(
|
|
185
|
+
'<!doctype html><html lang="en"><meta name="viewport" content="width=device-width,initial-scale=1"><title>' + networkLabel + ' member portal</title><style>' + siteStyle + '</style><header><strong>Membership site</strong><span>' + networkLabel + ' example</span></header><main><h1>Member portal</h1>' +
|
|
186
|
+
body +
|
|
187
|
+
'</main></html>',
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
function redirect(to) {
|
|
191
|
+
res.writeHead(303, { Location: to });
|
|
192
|
+
res.end();
|
|
193
|
+
}
|
|
194
|
+
function clearSession() {
|
|
195
|
+
if (key) sessions.delete(hash(key));
|
|
196
|
+
res.setHeader('Set-Cookie', cookie + '=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0');
|
|
197
|
+
}
|
|
198
|
+
function signInPage(message, status = 200) {
|
|
199
|
+
// A plain same-origin sign-in form needs an Origin header when it is submitted.
|
|
200
|
+
res.setHeader('Referrer-Policy', 'same-origin');
|
|
201
|
+
send(status, '<p>' + message + '</p>' + action('/start', 'Sign in with OneSwap Wallet'));
|
|
202
|
+
}
|
|
203
|
+
function siteUnavailable() {
|
|
204
|
+
send(503, '<p>This site’s OneSwap connection is temporarily unavailable. Please try again later.</p>');
|
|
205
|
+
}
|
|
206
|
+
function rateLimited(retryAfterMs) {
|
|
207
|
+
if (Number.isSafeInteger(retryAfterMs) && retryAfterMs >= 0) {
|
|
208
|
+
res.setHeader('Retry-After', String(Math.ceil(retryAfterMs / 1000)));
|
|
209
|
+
}
|
|
210
|
+
send(429, '<p>OneSwap is receiving too many requests. Please wait before trying again.</p><a href="/">Return to the site</a>');
|
|
211
|
+
}
|
|
212
|
+
function callbackNotice(notice) {
|
|
213
|
+
// The pre-login cookie is opaque and contains no wallet token. A notice
|
|
214
|
+
// survives precisely the redirect to the clean home page.
|
|
215
|
+
if (session && !session.access) {
|
|
216
|
+
delete session.pending;
|
|
217
|
+
session.notice = notice;
|
|
218
|
+
}
|
|
219
|
+
redirect('/');
|
|
220
|
+
}
|
|
221
|
+
function fresh(data) {
|
|
222
|
+
if (key) sessions.delete(hash(key));
|
|
223
|
+
prune();
|
|
224
|
+
if (sessions.size >= 500) throw new Error('Demo session capacity reached.');
|
|
225
|
+
const id = token();
|
|
226
|
+
sessions.set(hash(id), { expires: Date.now() + 600000, ...data });
|
|
227
|
+
res.setHeader(
|
|
228
|
+
'Set-Cookie',
|
|
229
|
+
cookie + '=' + id + '; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=600',
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
try {
|
|
233
|
+
if (req.method === 'POST' && req.headers.origin !== EXAMPLE_ORIGIN) {
|
|
234
|
+
send(403, 'Open the demo on its registered website.');
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
if (req.method === 'POST' && url.pathname === '/start') {
|
|
238
|
+
const { url, pending } = sdk.auth.startSignIn();
|
|
239
|
+
fresh({ pending });
|
|
240
|
+
redirect(url);
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (req.method === 'GET' && url.pathname === '/callback') {
|
|
244
|
+
const pending = session?.pending;
|
|
245
|
+
if (!pending) {
|
|
246
|
+
if (session?.access || session?.exchanging) redirect('/');
|
|
247
|
+
else callbackNotice('restart');
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
delete session.pending;
|
|
251
|
+
session.exchanging = true;
|
|
252
|
+
const result = await sdk.auth.finishSignIn(pending, url.href);
|
|
253
|
+
const me = await sdk.auth.me(result.access_token);
|
|
254
|
+
fresh({
|
|
255
|
+
access: result.access_token,
|
|
256
|
+
subject: me.subject,
|
|
257
|
+
expires: Date.now() + result.expires_in * 1000,
|
|
258
|
+
});
|
|
259
|
+
redirect('/');
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
if (req.method === 'GET' && url.pathname === '/' && !session?.access) {
|
|
263
|
+
const notice = session?.notice;
|
|
264
|
+
if (notice || (key && !session)) clearSession();
|
|
265
|
+
if (notice?.kind === 'rate-limited') rateLimited(notice.retryAfterMs);
|
|
266
|
+
else if (notice === 'unavailable') siteUnavailable();
|
|
267
|
+
else if (notice === 'declined') signInPage('You declined the wallet connection. You can sign in whenever you’re ready.');
|
|
268
|
+
else if (notice === 'restart' || (key && !session)) signInPage('Your sign-in expired. Sign in again to continue.');
|
|
269
|
+
else signInPage('Connect your wallet to check member access and view benefits for this site. OneSwap will ask you to review the connection.');
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
if (!session?.access) {
|
|
273
|
+
if (key) clearSession();
|
|
274
|
+
signInPage('Your wallet connection ended. Sign in again to continue.', 401);
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
const keyParts = [DAPP_ID, session.subject, EXPERIENCE_ID];
|
|
278
|
+
const order = () => findOrder.get(...keyParts);
|
|
279
|
+
const scope = { subject: session.subject, experienceId: EXPERIENCE_ID };
|
|
280
|
+
if (req.method === 'POST' && (url.pathname === '/buy' || url.pathname === '/retry')) {
|
|
281
|
+
const me = await sdk.auth.me(session.access);
|
|
282
|
+
if (!EXPERIENCE_ID || !me.capabilities.checkout) {
|
|
283
|
+
send(409, 'Checkout is unavailable for this experience. <a href="/">Return to the site</a>');
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
const retry = url.pathname === '/retry';
|
|
287
|
+
if (retry && (!session.closedPayment || session.closedPayment !== order()?.payment_id)) return redirect('/');
|
|
288
|
+
reserveOrder.run(...keyParts, 'demo_' + token());
|
|
289
|
+
let existing = order();
|
|
290
|
+
if (existing.delivered_at) return redirect('/');
|
|
291
|
+
if (existing.payment_id) {
|
|
292
|
+
const previous = await sdk.payments.receipt(existing.payment_id);
|
|
293
|
+
if (!receiptMatchesOrder(previous, existing, scope)) return redirect('/');
|
|
294
|
+
if (previous.status === 'open' || previous.status === 'approved') return redirect(checkoutUrl(previous.id, network));
|
|
295
|
+
if (!retry || !['expired', 'declined'].includes(previous.status)) return redirect('/');
|
|
296
|
+
if (session.closedPayment !== existing.payment_id) return redirect('/');
|
|
297
|
+
delete session.closedPayment;
|
|
298
|
+
advanceClosedInvoice(existing, previous.status);
|
|
299
|
+
existing = order();
|
|
300
|
+
if (existing.delivered_at) return redirect('/');
|
|
301
|
+
}
|
|
302
|
+
const orderRef = checkoutOrderRef(existing);
|
|
303
|
+
const invoice = await sdk.payments.create(session.access, {
|
|
304
|
+
experienceId: EXPERIENCE_ID,
|
|
305
|
+
orderId: orderRef,
|
|
306
|
+
});
|
|
307
|
+
if (
|
|
308
|
+
invoice.orderId !== orderRef ||
|
|
309
|
+
invoice.subject !== session.subject ||
|
|
310
|
+
invoice.experienceId !== EXPERIENCE_ID ||
|
|
311
|
+
typeof invoice.amount !== 'string' ||
|
|
312
|
+
typeof invoice.symbol !== 'string'
|
|
313
|
+
)
|
|
314
|
+
throw new Error('Unexpected payment binding.');
|
|
315
|
+
const walletCheckout = checkoutUrl(invoice.id, network);
|
|
316
|
+
const saved = bindInvoice.run({
|
|
317
|
+
id: invoice.id,
|
|
318
|
+
amount: invoice.amount,
|
|
319
|
+
symbol: invoice.symbol,
|
|
320
|
+
order: existing.order_id,
|
|
321
|
+
attempt: existing.attempt,
|
|
322
|
+
});
|
|
323
|
+
if (saved.changes !== 1) throw new Error('Payment terms changed.');
|
|
324
|
+
redirect(invoice.status === 'paid' ? '/' : walletCheckout);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
if (req.method === 'POST' && url.pathname === '/disconnect') {
|
|
328
|
+
await sdk.auth.revoke(session.access);
|
|
329
|
+
clearSession();
|
|
330
|
+
redirect('/');
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
if (req.method !== 'GET' || url.pathname !== '/') {
|
|
334
|
+
send(404, 'Page unavailable.');
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
const me = await sdk.auth.me(session.access);
|
|
338
|
+
let body = '<h2>Member area</h2><p>Your wallet is connected.</p>' +
|
|
339
|
+
'<details><summary>Your app-specific member ID</summary><code>' + escape(session.subject) + '</code></details>';
|
|
340
|
+
if (RULE_ID) {
|
|
341
|
+
const gate = await sdk.eligibility.check(session.access, RULE_ID);
|
|
342
|
+
if (hasFreshHolderAccess(gate, { subject: session.subject, appId: DAPP_ID, ruleId: RULE_ID, network: me.network })) {
|
|
343
|
+
body += '<h2>Holder area</h2><p>You have access.</p>';
|
|
344
|
+
} else if (gate.status === 'unsupported') {
|
|
345
|
+
body += '<p>Holder verification is not supported by the current configuration. The member area is still available.</p>';
|
|
346
|
+
} else if (gate.result === 'no' && gate.status === 'verified') {
|
|
347
|
+
body += '<p>This wallet has not qualified for the holder area.</p>';
|
|
348
|
+
} else {
|
|
349
|
+
body += '<p>Holder verification is temporarily unavailable.</p>';
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
if (EXPERIENCE_ID) {
|
|
353
|
+
const existing = order();
|
|
354
|
+
let checkout = me.capabilities.checkout
|
|
355
|
+
? action('/buy', 'Open checkout')
|
|
356
|
+
: '<p>Checkout becomes available after supported token graduation.</p>';
|
|
357
|
+
if (existing?.payment_id && !existing.delivered_at) {
|
|
358
|
+
const payment = await sdk.payments.receipt(existing.payment_id);
|
|
359
|
+
if (!receiptMatchesOrder(payment, existing, scope)) {
|
|
360
|
+
checkout = '<p>We could not verify the receipt for this order. <a href="/">Check payment status</a>.</p>';
|
|
361
|
+
} else if (paidReceiptMatches(payment, existing, scope)) {
|
|
362
|
+
markDelivered.run(existing.order_id, existing.payment_id);
|
|
363
|
+
} else if (['expired', 'declined'].includes(payment.status)) {
|
|
364
|
+
checkout = '<p>Your previous checkout ' + escape(payment.status) + ' without a completed payment.</p>';
|
|
365
|
+
if (me.capabilities.checkout) {
|
|
366
|
+
session.closedPayment = payment.id;
|
|
367
|
+
checkout += action('/retry', 'Start a new checkout');
|
|
368
|
+
}
|
|
369
|
+
} else if (['open', 'approved'].includes(payment.status)) {
|
|
370
|
+
checkout = '<p>You have an existing checkout for ' + escape(payment.amount) + ' ' + escape(payment.symbol) + '.</p>'
|
|
371
|
+
+ action('/buy', 'Return to existing checkout');
|
|
372
|
+
} else {
|
|
373
|
+
checkout = '<p>Your payment is awaiting confirmation. <a href="/">Refresh payment status</a>.</p>';
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
body += order()?.delivered_at ? '<h2>Your member pass</h2><p>Purchase confirmed.</p>' : checkout;
|
|
377
|
+
}
|
|
378
|
+
const rewardBatch = rewards.latestBatch(session.subject) ?? REWARD_BATCH_ID;
|
|
379
|
+
if (rewardBatch) {
|
|
380
|
+
try {
|
|
381
|
+
const r = await sdk.rewards.receipt(session.access, rewardBatch);
|
|
382
|
+
body += '<h2>Your reward</h2><p>' + (r.status === 'dismissed'
|
|
383
|
+
? 'The creator dismissed this reward proposal before funding.'
|
|
384
|
+
: 'Receipt status: ' + escape(r.status) + '.') + '</p>';
|
|
385
|
+
} catch (e) {
|
|
386
|
+
if (e.status !== 404) throw e;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
send(200, body + action('/disconnect', 'Disconnect wallet'));
|
|
390
|
+
} catch (e) {
|
|
391
|
+
if (req.method === 'GET' && url.pathname === '/callback') {
|
|
392
|
+
if (session) delete session.exchanging;
|
|
393
|
+
if (e.status === 429) callbackNotice({ kind: 'rate-limited', retryAfterMs: e.retryAfterMs });
|
|
394
|
+
else if (e.code === 'AUTHORIZATION_DENIED') callbackNotice('declined');
|
|
395
|
+
else if (e.code === 'INVALID_CALLBACK' || e.code === 'INVALID_AUTHORIZATION') callbackNotice('restart');
|
|
396
|
+
else callbackNotice('unavailable');
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
if (e.status === 429) {
|
|
400
|
+
rateLimited(e.retryAfterMs);
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
if (['INVALID_CLIENT', 'APP_UNAVAILABLE', 'APP_BINDING_CHANGED', 'COIN_NOT_ELIGIBLE', 'DAPPS_DISABLED'].includes(e.code)
|
|
404
|
+
|| e.status >= 500 || e instanceof TypeError || e.name === 'TimeoutError') {
|
|
405
|
+
siteUnavailable();
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
if (e.status === 401 || e.code === 'RULE_NOT_CONSENTED') {
|
|
409
|
+
clearSession();
|
|
410
|
+
if (url.pathname === '/disconnect') redirect('/');
|
|
411
|
+
else signInPage('Your wallet connection ended or needs new consent. Sign in again to continue.', 401);
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
send(400, 'The request could not be completed. <a href="/">Return to the site</a>');
|
|
415
|
+
}
|
|
416
|
+
}).listen(Number(process.env.PORT ?? 3481), '127.0.0.1');
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@oneswap/dapp-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "OneSwap SDK for wallet sign-in, token holder access, checkout and creator-funded rewards on Canton.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
"./server": {
|
|
8
|
+
"types": "./server.d.ts",
|
|
9
|
+
"import": "./server.js"
|
|
10
|
+
},
|
|
11
|
+
"./browser": {
|
|
12
|
+
"types": "./browser.d.ts",
|
|
13
|
+
"import": "./browser.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"server.js",
|
|
18
|
+
"server.d.ts",
|
|
19
|
+
"browser.js",
|
|
20
|
+
"browser.d.ts",
|
|
21
|
+
"README.md",
|
|
22
|
+
"example/server.mjs",
|
|
23
|
+
"example/accessChecks.mjs",
|
|
24
|
+
"example/proxyAuth.mjs",
|
|
25
|
+
"example/rewardProposals.mjs",
|
|
26
|
+
"LICENSE"
|
|
27
|
+
],
|
|
28
|
+
"scripts": {
|
|
29
|
+
"test": "node --test test/*.test.js"
|
|
30
|
+
},
|
|
31
|
+
"engines": {
|
|
32
|
+
"node": ">=20"
|
|
33
|
+
},
|
|
34
|
+
"author": "OneSwap",
|
|
35
|
+
"license": "MIT",
|
|
36
|
+
"homepage": "https://docs.oneswap.cc/guides/creator-dapp-sdk",
|
|
37
|
+
"publishConfig": {
|
|
38
|
+
"access": "public",
|
|
39
|
+
"registry": "https://registry.npmjs.org/"
|
|
40
|
+
}
|
|
41
|
+
}
|
package/server.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export class DappApiError extends Error { constructor(status:number, code:string, message:string); status:number;code:string;retryAfterMs?:number; }
|
|
2
|
+
export type DappNetwork = 'devnet' | 'mainnet';
|
|
3
|
+
export type NetworkId = 'canton:da-devnet' | 'canton:da-mainnet';
|
|
4
|
+
export type HolderAccessScope={subject:string;appId:string;ruleId:string;ruleVersion?:number;network?:NetworkId};
|
|
5
|
+
/** Accept only a fresh verified yes for this member, app and registered rule. */
|
|
6
|
+
export function hasFreshHolderAccess(gate:unknown,expected:HolderAccessScope,now?:number):boolean;
|
|
7
|
+
export type PendingSignIn={state:string;verifier:string;expiresAt:number};
|
|
8
|
+
export type Capabilities={signIn:true;freeExperiences:true;holderEligibility:boolean;checkout:boolean;rewards:boolean;eligibilityUnavailableReason:'TOKEN_LIFECYCLE_UNSUPPORTED'|null};
|
|
9
|
+
export type AppIdentity={subject:string;appId:string;coinId:string;network:NetworkId;phase:'pregraduation'|'graduated';capabilities:Capabilities;scopes:('app.identity'|'token.eligibility.read')[];expiresAt:string};
|
|
10
|
+
export type Eligibility={subject:string;appId:string;coinId:string;network:NetworkId;ruleId:string;ruleVersion:number;status:'verified'|'unavailable'|'unsupported';result:'yes'|'no'|'unknown';checkedAt:string|null;expiresAt:string|null;reason?:'TOKEN_LIFECYCLE_UNSUPPORTED'};
|
|
11
|
+
export type PaymentStatus='open'|'approved'|'processing'|'awaiting_acceptance'|'paid'|'declined'|'expired';
|
|
12
|
+
export type Payment={id:string;orderId:string;experienceId:string;subject:string;amount:string;symbol:string;status:PaymentStatus;expiresAt:string;receiptId:string|null};
|
|
13
|
+
export type ExpectedPayment = Pick<Payment, 'id'|'orderId'|'subject'|'experienceId'|'amount'|'symbol'>;
|
|
14
|
+
/** Use a server-fetched merchant receipt and the merchant's durable order. */
|
|
15
|
+
export function isPaidReceiptFor(receipt:unknown,order:ExpectedPayment):boolean;
|
|
16
|
+
export interface Award {recipientId:string;amount:string}
|
|
17
|
+
export type RewardAsset={instrumentAdmin:string;tokenId:string};
|
|
18
|
+
export type RewardBatch={id:string;eventId:string;status:'draft'|'approved'|'dismissed';planHash:string;totalAmount:string;recipientCount:number;asset:RewardAsset;campaignId:string|null;networkFeeCc:string|null;createdAt:string};
|
|
19
|
+
export type RewardReceipt={batchId:string;eventId:string;status:'pending_approval'}|{batchId:string;eventId:string;status:'dismissed'}|{
|
|
20
|
+
batchId:string;eventId:string;campaignId:string;amount:string;asset:RewardAsset;
|
|
21
|
+
status:'pending'|'awaiting_acceptance'|'delivered'|'returned'|'unknown';expiresAt?:string;
|
|
22
|
+
receipt?:{recordedAt:string;updateId:string}
|
|
23
|
+
};
|
|
24
|
+
export function createDappClient(options:{appId:string;secret:string;redirectUri:string;network:DappNetwork}):{
|
|
25
|
+
auth:{
|
|
26
|
+
startSignIn():{url:string;pending:PendingSignIn};
|
|
27
|
+
finishSignIn(pending:PendingSignIn,callback:string):Promise<{access_token:string;token_type:'Bearer';expires_in:number;scope:string}>;
|
|
28
|
+
me(token:string):Promise<AppIdentity>;
|
|
29
|
+
revoke(token:string):Promise<unknown>
|
|
30
|
+
};
|
|
31
|
+
eligibility:{check(token:string,ruleId:string):Promise<Eligibility>};
|
|
32
|
+
payments:{
|
|
33
|
+
receipt(id:string):Promise<Payment>;
|
|
34
|
+
create(token:string,order:{experienceId:string;orderId:string}):Promise<Payment>;
|
|
35
|
+
get(token:string,id:string):Promise<Payment>;
|
|
36
|
+
wait(token:string,id:string,options?:{timeoutMs?:number;intervalMs?:number}):Promise<Payment>
|
|
37
|
+
};
|
|
38
|
+
rewards:{propose(eventId:string,awards:Award[]):Promise<RewardBatch>;receipt(token:string,batchId:string):Promise<RewardReceipt>}
|
|
39
|
+
};
|
package/server.js
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
import { walletOrigin } from './browser.js';
|
|
4
|
+
const encode = encodeURIComponent;
|
|
5
|
+
export class DappApiError extends Error {
|
|
6
|
+
constructor(status,code,message) { super(message); this.name='DappApiError'; this.status=status; this.code=code; }
|
|
7
|
+
}
|
|
8
|
+
/** Compare an authenticated merchant receipt with the order already saved by the merchant. */
|
|
9
|
+
export function isPaidReceiptFor(receipt, order) {
|
|
10
|
+
if (!receipt || !order || receipt.status !== 'paid' || receipt.receiptId !== order.id) return false;
|
|
11
|
+
return ['id', 'orderId', 'subject', 'experienceId', 'amount', 'symbol'].every(field =>
|
|
12
|
+
typeof order[field] === 'string' && order[field].trim().length > 0 && receipt[field] === order[field]);
|
|
13
|
+
}
|
|
14
|
+
export function hasFreshHolderAccess(gate, expected, now = Date.now()) {
|
|
15
|
+
if (!gate || typeof gate !== 'object' || !expected || typeof expected !== 'object' || !Number.isFinite(now)) return false;
|
|
16
|
+
for (const key of ['subject', 'appId', 'ruleId']) {
|
|
17
|
+
const value = expected[key];
|
|
18
|
+
if (typeof value !== 'string' || !value.trim() || value.trim() !== value || gate[key] !== value) return false;
|
|
19
|
+
}
|
|
20
|
+
if (expected.ruleVersion !== undefined && (!Number.isSafeInteger(expected.ruleVersion) || expected.ruleVersion < 1 || gate.ruleVersion !== expected.ruleVersion)) return false;
|
|
21
|
+
if (expected.network !== undefined && gate.network !== expected.network) return false;
|
|
22
|
+
if (gate.status !== 'verified' || gate.result !== 'yes' || typeof gate.checkedAt !== 'string' || typeof gate.expiresAt !== 'string') return false;
|
|
23
|
+
const checkedAt = Date.parse(gate.checkedAt), expiresAt = Date.parse(gate.expiresAt);
|
|
24
|
+
return Number.isFinite(checkedAt) && Number.isFinite(expiresAt)
|
|
25
|
+
&& checkedAt <= now && now - checkedAt < 30000
|
|
26
|
+
&& expiresAt > now && expiresAt <= checkedAt + 30000;
|
|
27
|
+
}
|
|
28
|
+
export function createDappClient({appId,secret,redirectUri,network}) {
|
|
29
|
+
const wallet = walletOrigin(network);
|
|
30
|
+
const gateway = network === 'mainnet'
|
|
31
|
+
? 'https://api.oneswap.cc/swapv2/api/dapps'
|
|
32
|
+
: 'https://devnet.api.oneswap.cc/swapv2/api/dapps';
|
|
33
|
+
const registered=new URL(redirectUri);
|
|
34
|
+
if (typeof appId!=='string' || !appId || appId.includes(':') || typeof secret!=='string' || !secret || registered.protocol!=='https:' ||
|
|
35
|
+
registered.username || registered.password || registered.hash || ['code','state','error'].some(key=>registered.searchParams.has(key))) {
|
|
36
|
+
throw new TypeError('An app ID, server secret and registered HTTPS callback are required.');
|
|
37
|
+
}
|
|
38
|
+
const authorization='Basic '+Buffer.from(appId+':'+secret).toString('base64');
|
|
39
|
+
async function request(path,{method='GET',body,accessToken}={}) {
|
|
40
|
+
const response=await fetch(gateway+path,{method,redirect:'error',cache:'no-store',signal:AbortSignal.timeout(30000),
|
|
41
|
+
headers:{Authorization:authorization,...(accessToken?{'X-Dapp-Access-Token':accessToken}:{}),...(body?{'Content-Type':'application/json'}:{})},
|
|
42
|
+
...(body?{body:JSON.stringify(body)}:{})});
|
|
43
|
+
const data=await response.json().catch(()=>({}));
|
|
44
|
+
if (!response.ok) {
|
|
45
|
+
const error = new DappApiError(response.status,data.code??'REQUEST_FAILED',data.error??'OneSwap request failed.');
|
|
46
|
+
const delay = response.headers.get('retry-after');
|
|
47
|
+
if (response.status === 429 && delay && /^\d{1,5}$/.test(delay)) error.retryAfterMs = Number(delay) * 1000;
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
if ((path === '/me' || path === '/me/eligibility') && data.network !== 'canton:da-' + network) {
|
|
51
|
+
throw new DappApiError(502, 'NETWORK_MISMATCH', 'OneSwap returned an unexpected network.');
|
|
52
|
+
}
|
|
53
|
+
return data;
|
|
54
|
+
}
|
|
55
|
+
function startSignIn() {
|
|
56
|
+
const state=randomBytes(32).toString('base64url'),verifier=randomBytes(32).toString('base64url');
|
|
57
|
+
const url=new URL('/dapps/authorize',wallet);
|
|
58
|
+
url.search=new URLSearchParams({client_id:appId,redirect_uri:redirectUri,state,
|
|
59
|
+
code_challenge:createHash('sha256').update(verifier).digest('base64url'),code_challenge_method:'S256'}).toString();
|
|
60
|
+
return {url:url.toString(),pending:{state,verifier,expiresAt:Date.now()+600000}};
|
|
61
|
+
}
|
|
62
|
+
async function finishSignIn(pending,callback) {
|
|
63
|
+
const url=new URL(callback);
|
|
64
|
+
const state=url.searchParams.get('state')??'';
|
|
65
|
+
const left=Buffer.from(state),right=Buffer.from(pending?.state??'');
|
|
66
|
+
const staticQuery=params=>JSON.stringify([...params].filter(([key])=>!['code','state','error'].includes(key)).sort((a,b)=>a[0].localeCompare(b[0])||a[1].localeCompare(b[1])));
|
|
67
|
+
if (url.origin!==registered.origin || url.pathname!==registered.pathname || url.username || url.password || url.hash ||
|
|
68
|
+
staticQuery(url.searchParams)!==staticQuery(registered.searchParams) || !pending || !Number.isFinite(pending.expiresAt) ||
|
|
69
|
+
typeof pending.verifier!=='string' || !/^[A-Za-z0-9_-]{43}$/.test(pending.verifier) ||
|
|
70
|
+
Date.now()>pending.expiresAt || !state || left.length!==right.length || !timingSafeEqual(left,right) ||
|
|
71
|
+
url.searchParams.getAll('state').length!==1) throw new DappApiError(400,'INVALID_CALLBACK','Invalid or expired sign-in. Start again.');
|
|
72
|
+
if (url.searchParams.getAll('error').length===1 && !url.searchParams.has('code') && url.searchParams.get('error')==='access_denied') {
|
|
73
|
+
throw new DappApiError(403,'AUTHORIZATION_DENIED','The wallet connection was declined.');
|
|
74
|
+
}
|
|
75
|
+
if (url.searchParams.has('error') || url.searchParams.getAll('code').length!==1 || !url.searchParams.get('code')) {
|
|
76
|
+
throw new DappApiError(400,'INVALID_CALLBACK','Invalid sign-in response. Start again.');
|
|
77
|
+
}
|
|
78
|
+
return request('/token',{method:'POST',body:{grant_type:'authorization_code',code:url.searchParams.get('code'),redirect_uri:redirectUri,code_verifier:pending.verifier}});
|
|
79
|
+
}
|
|
80
|
+
const payments={
|
|
81
|
+
receipt:id=>request('/payments/'+encode(id)+'/receipt'),
|
|
82
|
+
create:(accessToken,{experienceId,orderId})=>request('/payments',{method:'POST',accessToken,body:{experienceId,orderId}}),
|
|
83
|
+
get:(accessToken,id)=>request('/payments/'+encode(id),{accessToken}),
|
|
84
|
+
async wait(accessToken,id,{timeoutMs=60000,intervalMs=3000}={}) {
|
|
85
|
+
if (!Number.isFinite(timeoutMs)||timeoutMs<=0||timeoutMs>300000 || !Number.isFinite(intervalMs)||intervalMs<1000) throw new RangeError('Use a polling interval of at least one second and a timeout of up to five minutes.');
|
|
86
|
+
const deadline=Date.now()+timeoutMs;
|
|
87
|
+
let payment=await payments.get(accessToken,id);
|
|
88
|
+
while (!['paid','declined','expired'].includes(payment.status) && Date.now()+intervalMs<=deadline) {
|
|
89
|
+
await new Promise(done=>setTimeout(done,intervalMs));payment=await payments.get(accessToken,id);
|
|
90
|
+
}
|
|
91
|
+
return payment;
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
const base='/apps/'+encode(appId)+'/reward-batches';
|
|
95
|
+
return {auth:{startSignIn,finishSignIn,me:accessToken=>request('/me',{accessToken}),
|
|
96
|
+
revoke:accessToken=>request('/revoke',{method:'POST',accessToken,body:{}})},
|
|
97
|
+
eligibility:{check:(accessToken,ruleId)=>request('/me/eligibility',{method:'POST',accessToken,body:{ruleId}})},
|
|
98
|
+
payments,rewards:{propose:(eventId,awards)=>request(base,{method:'POST',body:{eventId,awards}}),
|
|
99
|
+
receipt:(accessToken,batchId)=>request(base+'/'+encode(batchId)+'/receipt',{accessToken})}};
|
|
100
|
+
}
|