@redzone/taunt-logins 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "@seaders/redzone-taunt-logins",
3
+ "version": "1.0.4",
4
+ "description": "",
5
+ "type": "module",
6
+ "main": "dist/index.cjs",
7
+ "scripts": {
8
+ "clean": "rm -rf dist",
9
+ "prebuild": "npm run clean",
10
+ "build": "tsc"
11
+ },
12
+ "dependencies": {
13
+ "@metamask/providers": "^22.1.1",
14
+ "magic-sdk": "^30.0.0"
15
+ },
16
+ "devDependencies": {
17
+ "@ianvs/prettier-plugin-sort-imports": "^4.7.0",
18
+ "@types/chrome": "^0.1.16",
19
+ "@types/node": "^24.6.1",
20
+ "prettier": "^3.6.2",
21
+ "tsup": "^8.5.0",
22
+ "typescript": "^5.9.3"
23
+ }
24
+ }
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "@redzone/taunt-logins",
3
+ "version": "1.0.4",
4
+ "description": "",
5
+ "type": "module",
6
+ "main": "dist/index.cjs",
7
+ "scripts": {
8
+ "clean": "rm -rf dist",
9
+ "prebuild": "npm run clean",
10
+ "build": "tsc"
11
+ },
12
+ "dependencies": {
13
+ "@metamask/providers": "^22.1.1",
14
+ "magic-sdk": "^30.0.0"
15
+ },
16
+ "devDependencies": {
17
+ "@ianvs/prettier-plugin-sort-imports": "^4.7.0",
18
+ "@types/chrome": "^0.1.16",
19
+ "@types/node": "^24.6.1",
20
+ "prettier": "^3.6.2",
21
+ "tsup": "^8.5.0",
22
+ "typescript": "^5.9.3"
23
+ }
24
+ }
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "@redzone/taunt-logins",
3
+ "version": "0.0.1",
4
+ "description": "",
5
+ "type": "module",
6
+ "main": "dist/index.cjs",
7
+ "scripts": {
8
+ "clean": "rm -rf dist",
9
+ "prebuild": "npm run clean",
10
+ "build": "tsc"
11
+ },
12
+ "dependencies": {
13
+ "@metamask/providers": "^22.1.1",
14
+ "magic-sdk": "^30.0.0"
15
+ },
16
+ "devDependencies": {
17
+ "@ianvs/prettier-plugin-sort-imports": "^4.7.0",
18
+ "@types/chrome": "^0.1.16",
19
+ "@types/node": "^24.6.1",
20
+ "prettier": "^3.6.2",
21
+ "tsup": "^8.5.0",
22
+ "typescript": "^5.9.3"
23
+ }
24
+ }
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "@redzone/taunt-logins",
3
+ "version": "0.0.1",
4
+ "description": "",
5
+ "type": "module",
6
+ "main": "index.ts",
7
+ "scripts": {
8
+ "clean": "rm -rf dist",
9
+ "prebuild": "npm run clean",
10
+ "build": "tsc"
11
+ },
12
+ "dependencies": {
13
+ "@metamask/providers": "^22.1.1",
14
+ "magic-sdk": "^30.0.0"
15
+ },
16
+ "devDependencies": {
17
+ "@ianvs/prettier-plugin-sort-imports": "^4.7.0",
18
+ "@types/chrome": "^0.1.16",
19
+ "@types/node": "^24.6.1",
20
+ "prettier": "^3.6.2",
21
+ "tsup": "^8.5.0",
22
+ "typescript": "^5.9.3"
23
+ }
24
+ }
@@ -0,0 +1,136 @@
1
+ import { MetaMaskInpageProvider } from "@metamask/providers"
2
+
3
+ import { TauntApi } from "./taunt"
4
+
5
+ const CHROME_METAMASK_ID = "nkbihfbeogaeaoehlefnkodbefgpgknn"
6
+
7
+ export const createMetaMaskProvider = () =>
8
+ createWalletProvider(CHROME_METAMASK_ID)
9
+
10
+ declare global {
11
+ interface Window {
12
+ ethereum?: MetaMaskInpageProvider
13
+ }
14
+ }
15
+
16
+ async function createWalletProvider(ident: string) {
17
+ let provider
18
+ try {
19
+ let metamaskPort
20
+ try {
21
+ metamaskPort = chrome.runtime.connect(ident)
22
+ } catch (error) {
23
+ console.log("Failed to connect to MetaMask", error)
24
+ }
25
+
26
+ if (metamaskPort) {
27
+ const PortStream = await import("extension-port-stream").then(
28
+ (m) => m.default
29
+ )
30
+ const pluginStream = new PortStream(metamaskPort)
31
+ provider = new MetaMaskInpageProvider(pluginStream)
32
+ } else {
33
+ let eth
34
+ try {
35
+ eth = window?.ethereum
36
+ } catch (error) {
37
+ console.error("Failed to access window.ethereum", error)
38
+ }
39
+
40
+ if (eth) {
41
+ provider = eth
42
+ if (!provider.isMetaMask) {
43
+ console.warn(
44
+ "Injected ethereum provider is not MetaMask! You may experience issues."
45
+ )
46
+ }
47
+ }
48
+ }
49
+ } catch (e) {
50
+ console.dir(`Metamask connect error `, e)
51
+ throw e
52
+ }
53
+
54
+ return provider
55
+ }
56
+
57
+ export async function withMetamask(
58
+ tauntServiceEndpoint: string,
59
+ providerParam?: MetaMaskInpageProvider
60
+ ) {
61
+ const provider = providerParam || (await createMetaMaskProvider())
62
+ if (!provider) throw new Error("MetaMask provider not found")
63
+
64
+ const accounts = (await provider.request({
65
+ method: "eth_requestAccounts"
66
+ })) as string[]
67
+ if (!accounts.length) throw new Error("No accounts returned")
68
+
69
+ console.log("MetaMask", { accounts })
70
+
71
+ const walletAddress = accounts[0]
72
+ const baseUrl = `${tauntServiceEndpoint}/v1/auth`
73
+ const cryptoValuesArray = new Uint32Array(3)
74
+ const clientNonce = crypto.getRandomValues(cryptoValuesArray).toString()
75
+
76
+ const serverNonce = await fetch(`${baseUrl}/nonce/login`, {
77
+ method: "POST",
78
+ body: JSON.stringify({ walletAddress, clientNonce }),
79
+ headers: { "Content-Type": "application/json" }
80
+ }).then((res) => res.text())
81
+
82
+ const payload = JSON.stringify({ clientNonce, serverNonce })
83
+ const message = `Sign this message with your wallet to connect to Taunt Battleworld ::: ${payload}`
84
+ const params = [message, walletAddress]
85
+ const method = "personal_sign"
86
+
87
+ const signature = await new Promise<string>((resolve, reject) => {
88
+ provider.sendAsync(
89
+ {
90
+ id: 1,
91
+ method,
92
+ params,
93
+ jsonrpc: "2.0"
94
+ },
95
+ (err, response) => {
96
+ if (err) {
97
+ console.error(err)
98
+ reject(err)
99
+ return
100
+ }
101
+
102
+ const { result, error } = response as {
103
+ id: number
104
+ jsonrpc: string
105
+ result: string
106
+ error?: unknown
107
+ }
108
+ if (error) {
109
+ console.error(error)
110
+ reject(error)
111
+ return
112
+ }
113
+
114
+ resolve(result)
115
+ }
116
+ )
117
+ })
118
+
119
+ return { walletAddress, message, signature }
120
+ }
121
+
122
+ export async function loginWithMetamask(
123
+ tauntServiceEndpoint: string,
124
+ providerParam?: MetaMaskInpageProvider
125
+ ) {
126
+ const taunt = new TauntApi(tauntServiceEndpoint)
127
+ const { walletAddress, message, signature } = await withMetamask(
128
+ tauntServiceEndpoint,
129
+ providerParam
130
+ )
131
+ return taunt.loginWithWeb3WalletSignature({
132
+ walletAddress,
133
+ message,
134
+ signature
135
+ })
136
+ }
@@ -0,0 +1,90 @@
1
+ import { BaseProvider } from "@metamask/providers"
2
+
3
+ import { TauntApi } from "./taunt"
4
+
5
+ declare global {
6
+ interface Window {
7
+ ethereum?: BaseProvider
8
+ }
9
+ }
10
+
11
+ export async function withMetamask(
12
+ tauntServiceEndpoint: string,
13
+ provider?: BaseProvider
14
+ ) {
15
+ provider = provider || window.ethereum
16
+ if (!provider) throw new Error("MetaMask provider not found")
17
+
18
+ const accounts = (await provider.request({
19
+ method: "eth_requestAccounts"
20
+ })) as string[]
21
+ if (!accounts.length) throw new Error("No accounts returned")
22
+
23
+ console.log("MetaMask", { accounts })
24
+
25
+ const walletAddress = accounts[0]
26
+ const baseUrl = `${tauntServiceEndpoint}/v1/auth`
27
+ const cryptoValuesArray = new Uint32Array(3)
28
+ const clientNonce = crypto.getRandomValues(cryptoValuesArray).toString()
29
+
30
+ const serverNonce = await fetch(`${baseUrl}/nonce/login`, {
31
+ method: "POST",
32
+ body: JSON.stringify({ walletAddress, clientNonce }),
33
+ headers: { "Content-Type": "application/json" }
34
+ }).then((res) => res.text())
35
+
36
+ const payload = JSON.stringify({ clientNonce, serverNonce })
37
+ const message = `Sign this message with your wallet to connect to Taunt Battleworld ::: ${payload}`
38
+ const params = [message, walletAddress]
39
+ const method = "personal_sign"
40
+
41
+ const signature = await new Promise<string>((resolve, reject) => {
42
+ provider.sendAsync(
43
+ {
44
+ id: 1,
45
+ method,
46
+ params,
47
+ jsonrpc: "2.0"
48
+ },
49
+ (err, response) => {
50
+ if (err) {
51
+ console.error(err)
52
+ reject(err)
53
+ return
54
+ }
55
+
56
+ const { result, error } = response as {
57
+ id: number
58
+ jsonrpc: string
59
+ result: string
60
+ error?: unknown
61
+ }
62
+ if (error) {
63
+ console.error(error)
64
+ reject(error)
65
+ return
66
+ }
67
+
68
+ resolve(result)
69
+ }
70
+ )
71
+ })
72
+
73
+ return { walletAddress, message, signature }
74
+ }
75
+
76
+ export async function loginWithMetamask(
77
+ tauntServiceEndpoint: string,
78
+ providerParam?: MetaMaskInpageProvider
79
+ ) {
80
+ const taunt = new TauntApi(tauntServiceEndpoint)
81
+ const { walletAddress, message, signature } = await withMetamask(
82
+ tauntServiceEndpoint,
83
+ providerParam
84
+ )
85
+ return taunt.loginWithWeb3WalletSignature({
86
+ walletAddress,
87
+ message,
88
+ signature
89
+ })
90
+ }
@@ -0,0 +1,59 @@
1
+ import { BaseProvider } from "@metamask/providers"
2
+
3
+ import { TauntApi } from "./taunt"
4
+
5
+ declare global {
6
+ interface Window {
7
+ ethereum?: BaseProvider
8
+ }
9
+ }
10
+
11
+ export async function withMetamask(
12
+ tauntServiceEndpoint: string,
13
+ provider?: BaseProvider
14
+ ) {
15
+ provider = provider || window.ethereum
16
+ if (!provider) throw new Error("MetaMask provider not found")
17
+
18
+ const accounts = (await provider.request({
19
+ method: "eth_requestAccounts"
20
+ })) as string[]
21
+ if (!accounts.length) throw new Error("No accounts returned")
22
+
23
+ console.log("MetaMask", { accounts })
24
+
25
+ const walletAddress = accounts[0]
26
+ const baseUrl = `${tauntServiceEndpoint}/v1/auth`
27
+ const cryptoValuesArray = new Uint32Array(3)
28
+ const clientNonce = crypto.getRandomValues(cryptoValuesArray).toString()
29
+
30
+ const serverNonce = await fetch(`${baseUrl}/nonce/login`, {
31
+ method: "POST",
32
+ body: JSON.stringify({ walletAddress, clientNonce }),
33
+ headers: { "Content-Type": "application/json" }
34
+ }).then((res) => res.text())
35
+
36
+ const payload = JSON.stringify({ clientNonce, serverNonce })
37
+ const message = `Sign this message with your wallet to connect to Taunt Battleworld ::: ${payload}`
38
+ const params = [message, walletAddress]
39
+
40
+ const signature = await provider.request({ method: "personal_sign", params })
41
+
42
+ return { walletAddress, message, signature }
43
+ }
44
+
45
+ export async function loginWithMetamask(
46
+ tauntServiceEndpoint: string,
47
+ providerParam?: MetaMaskInpageProvider
48
+ ) {
49
+ const taunt = new TauntApi(tauntServiceEndpoint)
50
+ const { walletAddress, message, signature } = await withMetamask(
51
+ tauntServiceEndpoint,
52
+ providerParam
53
+ )
54
+ return taunt.loginWithWeb3WalletSignature({
55
+ walletAddress,
56
+ message,
57
+ signature
58
+ })
59
+ }
@@ -0,0 +1,61 @@
1
+ import { BaseProvider } from "@metamask/providers"
2
+
3
+ import { TauntApi } from "./taunt"
4
+
5
+ declare global {
6
+ interface Window {
7
+ ethereum?: BaseProvider
8
+ }
9
+ }
10
+
11
+ export async function withMetamask(
12
+ tauntServiceEndpoint: string,
13
+ provider?: BaseProvider
14
+ ) {
15
+ provider = provider || window.ethereum
16
+ if (!provider) throw new Error("MetaMask provider not found")
17
+
18
+ const accounts = (await provider.request({
19
+ method: "eth_requestAccounts"
20
+ })) as string[]
21
+ if (!accounts.length) throw new Error("No accounts returned")
22
+
23
+ console.log("MetaMask", { accounts })
24
+
25
+ const walletAddress = accounts[0]
26
+ const baseUrl = `${tauntServiceEndpoint}/v1/auth`
27
+ const cryptoValuesArray = new Uint32Array(3)
28
+ const clientNonce = crypto.getRandomValues(cryptoValuesArray).toString()
29
+
30
+ const serverNonce = await fetch(`${baseUrl}/nonce/login`, {
31
+ method: "POST",
32
+ body: JSON.stringify({ walletAddress, clientNonce }),
33
+ headers: { "Content-Type": "application/json" }
34
+ }).then((res) => res.text())
35
+
36
+ const payload = JSON.stringify({ clientNonce, serverNonce })
37
+ const message = `Sign this message with your wallet to connect to Taunt Battleworld ::: ${payload}`
38
+
39
+ const signature = await provider.request({
40
+ method: "personal_sign",
41
+ params: [message, walletAddress]
42
+ })
43
+
44
+ return { walletAddress, message, signature }
45
+ }
46
+
47
+ export async function loginWithMetamask(
48
+ tauntServiceEndpoint: string,
49
+ providerParam?: MetaMaskInpageProvider
50
+ ) {
51
+ const taunt = new TauntApi(tauntServiceEndpoint)
52
+ const { walletAddress, message, signature } = await withMetamask(
53
+ tauntServiceEndpoint,
54
+ providerParam
55
+ )
56
+ return taunt.loginWithWeb3WalletSignature({
57
+ walletAddress,
58
+ message,
59
+ signature
60
+ })
61
+ }
@@ -0,0 +1,66 @@
1
+ import { BaseProvider } from "@metamask/providers"
2
+
3
+ import { TauntApi } from "./taunt"
4
+
5
+ declare global {
6
+ interface Window {
7
+ ethereum?: BaseProvider
8
+ }
9
+ }
10
+
11
+ export async function withMetamask(
12
+ tauntServiceEndpoint: string,
13
+ provider?: BaseProvider
14
+ ) {
15
+ provider = provider || window.ethereum
16
+ if (!provider) throw new Error("MetaMask provider not found")
17
+
18
+ const accounts = (await provider.request({
19
+ method: "eth_requestAccounts"
20
+ })) as string[]
21
+ if (!accounts.length) throw new Error("No accounts returned")
22
+
23
+ console.log("MetaMask", { accounts })
24
+
25
+ const walletAddress = accounts[0]
26
+ const baseUrl = `${tauntServiceEndpoint}/v1/auth`
27
+ const cryptoValuesArray = new Uint32Array(3)
28
+ const clientNonce = crypto.getRandomValues(cryptoValuesArray).toString()
29
+
30
+ const serverNonce = await fetch(`${baseUrl}/nonce/login`, {
31
+ method: "POST",
32
+ body: JSON.stringify({ walletAddress, clientNonce }),
33
+ headers: { "Content-Type": "application/json" }
34
+ }).then((res) => res.text())
35
+
36
+ const payload = JSON.stringify({ clientNonce, serverNonce })
37
+ const message = `Sign this message with your wallet to connect to Taunt Battleworld ::: ${payload}`
38
+ let signature
39
+ try {
40
+ signature = await provider.request<string>({
41
+ method: "personal_sign",
42
+ params: [message, walletAddress]
43
+ })
44
+ } catch (err) {
45
+ throw new Error("User denied message signature")
46
+ }
47
+ if (!signature) throw new Error("No signature returned")
48
+
49
+ return { walletAddress, message, signature }
50
+ }
51
+
52
+ export async function loginWithMetamask(
53
+ tauntServiceEndpoint: string,
54
+ providerParam?: BaseProvider
55
+ ) {
56
+ const taunt = new TauntApi(tauntServiceEndpoint)
57
+ const { walletAddress, message, signature } = await withMetamask(
58
+ tauntServiceEndpoint,
59
+ providerParam
60
+ )
61
+ return taunt.loginWithWeb3WalletSignature({
62
+ walletAddress,
63
+ message,
64
+ signature
65
+ })
66
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @type {import('prettier').Options}
3
+ */
4
+ export default {
5
+ printWidth: 80,
6
+ tabWidth: 2,
7
+ useTabs: false,
8
+ semi: false,
9
+ singleQuote: false,
10
+ trailingComma: "none",
11
+ bracketSpacing: true,
12
+ bracketSameLine: true,
13
+ plugins: ["@ianvs/prettier-plugin-sort-imports"],
14
+ importOrder: [
15
+ "<BUILTIN_MODULES>", // Node.js built-in modules
16
+ "<THIRD_PARTY_MODULES>", // Imports not matched by other special words or groups.
17
+ "",
18
+ "^~(.*)$",
19
+ "",
20
+ "^[./]"
21
+ ]
22
+ }
package/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./src/magic"
2
+ export * from "./src/metamask"
package/package.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "@redzone/taunt-logins",
3
+ "version": "0.0.1",
4
+ "description": "",
5
+ "type": "module",
6
+ "main": "index.ts",
7
+ "scripts": {
8
+ "clean": "rm -rf dist",
9
+ "prebuild": "npm run clean",
10
+ "build": "tsc"
11
+ },
12
+ "dependencies": {
13
+ "@metamask/providers": "^22.1.1",
14
+ "magic-sdk": "^30.0.0"
15
+ },
16
+ "devDependencies": {
17
+ "@ianvs/prettier-plugin-sort-imports": "^4.7.0",
18
+ "@types/chrome": "^0.1.16",
19
+ "@types/node": "^24.6.1",
20
+ "prettier": "^3.6.2",
21
+ "tsup": "^8.5.0",
22
+ "typescript": "^5.9.3"
23
+ }
24
+ }
package/src/magic.ts ADDED
@@ -0,0 +1,30 @@
1
+ import { Magic } from "magic-sdk"
2
+
3
+ import { TauntApi } from "./taunt"
4
+
5
+ const customNodeOptions = {
6
+ rpcUrl: "https://polygon-rpc.com", // your ethereum, polygon, or optimism mainnet/testnet rpc URL
7
+ chainId: 137
8
+ }
9
+
10
+ export function withMagic(magicKey: string, email: string) {
11
+ const magic = new Magic(magicKey, {
12
+ network: customNodeOptions
13
+ })
14
+ return magic.auth.loginWithEmailOTP({ email })
15
+ }
16
+
17
+ export async function loginWithMagic(
18
+ tauntServiceEndpoint: string,
19
+ magicKey: string,
20
+ email: string
21
+ ) {
22
+ const taunt = new TauntApi(tauntServiceEndpoint)
23
+ try {
24
+ const did = await withMagic(magicKey, email)
25
+ return taunt.loginWithMagicDid(did!)
26
+ } catch (err) {
27
+ console.error("Magic login error:", err)
28
+ throw err
29
+ }
30
+ }
@@ -0,0 +1,66 @@
1
+ import { BaseProvider } from "@metamask/providers"
2
+
3
+ import { TauntApi } from "./taunt"
4
+
5
+ declare global {
6
+ interface Window {
7
+ ethereum?: BaseProvider
8
+ }
9
+ }
10
+
11
+ export async function withMetamask(
12
+ tauntServiceEndpoint: string,
13
+ provider?: BaseProvider
14
+ ) {
15
+ provider = provider || window.ethereum
16
+ if (!provider) throw new Error("MetaMask provider not found")
17
+
18
+ const accounts = (await provider.request({
19
+ method: "eth_requestAccounts"
20
+ })) as string[]
21
+ if (!accounts.length) throw new Error("No accounts returned")
22
+
23
+ console.log("MetaMask", { accounts })
24
+
25
+ const walletAddress = accounts[0]
26
+ const baseUrl = `${tauntServiceEndpoint}/v1/auth`
27
+ const cryptoValuesArray = new Uint32Array(3)
28
+ const clientNonce = crypto.getRandomValues(cryptoValuesArray).toString()
29
+
30
+ const serverNonce = await fetch(`${baseUrl}/nonce/login`, {
31
+ method: "POST",
32
+ body: JSON.stringify({ walletAddress, clientNonce }),
33
+ headers: { "Content-Type": "application/json" }
34
+ }).then((res) => res.text())
35
+
36
+ const payload = JSON.stringify({ clientNonce, serverNonce })
37
+ const message = `Sign this message with your wallet to connect to Taunt Battleworld ::: ${payload}`
38
+ let signature
39
+ try {
40
+ signature = await provider.request<string>({
41
+ method: "personal_sign",
42
+ params: [message, walletAddress]
43
+ })
44
+ } catch (err) {
45
+ throw new Error("User denied message signature")
46
+ }
47
+ if (!signature) throw new Error("No signature returned")
48
+
49
+ return { walletAddress, message, signature }
50
+ }
51
+
52
+ export async function loginWithMetamask(
53
+ tauntServiceEndpoint: string,
54
+ providerParam?: BaseProvider
55
+ ) {
56
+ const taunt = new TauntApi(tauntServiceEndpoint)
57
+ const { walletAddress, message, signature } = await withMetamask(
58
+ tauntServiceEndpoint,
59
+ providerParam
60
+ )
61
+ return taunt.loginWithWeb3WalletSignature({
62
+ walletAddress,
63
+ message,
64
+ signature
65
+ })
66
+ }
package/src/taunt.ts ADDED
@@ -0,0 +1,217 @@
1
+ export type TauntSigProps = {
2
+ walletAddress: string
3
+ message: string
4
+ signature: string
5
+ }
6
+ export type TauntExtSigProps = TauntSigProps & { extNonce: string }
7
+
8
+ type TauntRespType = {
9
+ accessToken: string
10
+ refreshToken: string
11
+ isNewUser: string
12
+ }
13
+
14
+ export type TauntUser = {
15
+ id: number
16
+ role: string
17
+ email: string | undefined
18
+ ethAddress: string | null
19
+ avatar: string | null
20
+
21
+ refreshToken: string
22
+ accessToken: string
23
+ }
24
+
25
+ export class TauntApi {
26
+ constructor(
27
+ private endpoint: string,
28
+ private api = this
29
+ ) {}
30
+
31
+ async stdPGET<T = TauntRespType>(
32
+ method: string,
33
+ url: string,
34
+ body?: unknown,
35
+ headers = {}
36
+ ) {
37
+ const response = await fetch(this.endpoint + url, {
38
+ method,
39
+ headers: {
40
+ "Content-Type": "application/json",
41
+ // Include credentials (cookies) in the request
42
+ Accept: "application/json",
43
+ ...headers
44
+ },
45
+ body: body ? JSON.stringify(body) : null,
46
+ credentials: "include" // This ensures cookies are sent with the request
47
+ })
48
+ return this.withResp<T>(response)
49
+ }
50
+
51
+ async withResp<T>(response: Response) {
52
+ if (!response.ok) {
53
+ const errorData = await response.json().catch(() => ({}))
54
+ const error = new Error("Network response was not ok")
55
+
56
+ Object.assign(error, { response, data: errorData })
57
+ throw error
58
+ }
59
+ return response.json().then((data) => ({ data: data as T, response }))
60
+ }
61
+
62
+ async post<T = TauntRespType>(url: string, body = {}) {
63
+ return this.stdPGET<T>("POST", url, body)
64
+ }
65
+
66
+ async get<T = TauntRespType>(url: string, headers = {}) {
67
+ return this.stdPGET<T>("GET", url, undefined, headers)
68
+ }
69
+
70
+ async loginWithMagicDid(did: string) {
71
+ const { data } = await this.api.post("/v1/auth/login/did", { did })
72
+ return data
73
+ }
74
+
75
+ async loginWithWeb3WalletSignature(props: TauntSigProps) {
76
+ const { data } = await this.api.post("/v1/auth/login/signature", props)
77
+ return data
78
+ }
79
+
80
+ async loginExtWithWeb3WalletSignature(props: TauntExtSigProps) {
81
+ const { data } = await this.api.post("/v1/auth/login/ext-signature", props)
82
+ return data
83
+ }
84
+
85
+ // Logout of the backend with access token. Assumes user is currently logged in and has a cookie with the access token
86
+ async logout(accessToken: string) {
87
+ // If logging out fails on the backend we'll still remove the user info
88
+ await this.api.post("/v1/auth/logout", { accessToken })
89
+ await this.writePlayerEvent("player_logged_out")
90
+ }
91
+
92
+ // Use the cookie stored in the browser to get the user and save user model in state and local storage
93
+ // This assumes that the user is logged to backend in and has a cookie jwt
94
+ async getLoggedInUser(accessToken: string) {
95
+ const { data } = await this.api.get<{ ethAddress: string }>("/v1/auth/me", {
96
+ Authorization: `Bearer ${accessToken}`
97
+ })
98
+ // this.user = data
99
+ // localStorage.setItem("user", JSON.stringify(data))
100
+ // localStorage.setItem(
101
+ // "name",
102
+ // this.user.email ? this.user.email.split("@")[0] : this.user.ethAddress
103
+ // )
104
+ // await this.getCToken()
105
+ // this.setRefId(this.router.currentRoute.value.query['ref_id'])
106
+
107
+ // const nftStore = useNftStore()
108
+ // nftStore.fetchAll()
109
+ return data as TauntUser
110
+ }
111
+
112
+ // async loginPlayFabPlayer() {}
113
+
114
+ /*async loginPlayFabPlayer() {
115
+ try {
116
+ // Get the user's playfab id from taunt api
117
+ let id = null;
118
+ if (!this.user && !this.user?.id) {
119
+ id = this.getPlayfabAnonId()
120
+ if (!id) {
121
+ const { data: playFabResponse } = await this.api.get('/v1/auth/playfab', {})
122
+ id = playFabResponse.playFabId
123
+ this.setAnonPlayfabUserId(playFabResponse.playFabId);
124
+ }
125
+ } else {
126
+ const { data: playFabResponse } = await this.api.get('/v1/auth/playfab', {})
127
+ id = playFabResponse.playFabId
128
+ }
129
+ // Login with playfab via the unique id from taunt api
130
+ const { data: playFabLoginResults } = await Axios.post(loginEndpoint, {
131
+ CustomId: id,
132
+ CreateAccount: true,
133
+ titleId: playFabTitleId,
134
+ })
135
+ const playFabSession = JSON.stringify(playFabLoginResults.data)
136
+ this.setPlayFabSession(playFabSession)
137
+ }
138
+ catch (error) {
139
+ const err = error as AxiosError
140
+ if (err?.response) {
141
+ console.log(err.response.status, err.response.data)
142
+ }
143
+ else {
144
+ console.log(error)
145
+ }
146
+ }
147
+ }*/
148
+
149
+ // async getCToken() {
150
+ // try {
151
+ // const url = "v1/claimr/token"
152
+ // const { data } = await this.api.get<{ data: { token: string } }>(`${url}`)
153
+ // this.claimrToken = data.data.token
154
+ // this.setClaimrToken(this.claimrToken)
155
+ // } catch (e) {
156
+ // console.error(e)
157
+ // }
158
+ // }
159
+
160
+ // setLastWalletConnection(lastWalletConnection: string) {
161
+ // localStorage.setItem("lastWalletConnection", lastWalletConnection)
162
+ // }
163
+ // setRefId(ref = "") {
164
+ // this.refId = ref
165
+ // }
166
+
167
+ // clearLocalAuthStorage() {
168
+ // localStorage.removeItem("user")
169
+ // localStorage.removeItem("refreshToken")
170
+ // localStorage.removeItem("playFabSession")
171
+ // this.user = null
172
+ // }
173
+
174
+ // setAccessToken(accessToken: string) {
175
+ // localStorage.setItem("accessToken", accessToken)
176
+ // }
177
+ // setRefreshToken(refreshToken: string) {
178
+ // localStorage.setItem("refreshToken", refreshToken)
179
+ // }
180
+ // setIsFirsTimeLogin(isFirstTimeLogin: string) {
181
+ // localStorage.setItem("isFirstTimeLogin", isFirstTimeLogin)
182
+ // }
183
+ // setPlayFabSession(playFabSession: string) {
184
+ // localStorage.setItem("playFabSession", playFabSession)
185
+ // }
186
+ // setAnonPlayfabUserId(id: string) {
187
+ // localStorage.setItem("playfabAnonId", id)
188
+ // }
189
+ // setClaimrToken(token: string) {
190
+ // localStorage.setItem("ctoken", token)
191
+ // }
192
+ // getAccessToken() {
193
+ // return localStorage.getItem("accessToken")
194
+ // }
195
+ // getRefreshToken() {
196
+ // return localStorage.getItem("refreshToken")
197
+ // }
198
+ // getPlayfabAnonId() {
199
+ // return localStorage.getItem("playfabAnonId")
200
+ // }
201
+
202
+ // Write a playfab event. retryfIfLoginNeeded should not be set by caller. It's used for stopping recursive calls when login is needed.
203
+ // If login is needed, for example, if the web browser has been open longer than playfab session timeout, we'll try to login again at most
204
+ // one time. Then we'll retry the event.
205
+ async writePlayerEvent(
206
+ eventName: string,
207
+ eventData: unknown = null,
208
+ retryIfLoginNeeded = true
209
+ ) {
210
+ console.log("writePlayerEvent", {
211
+ eventName,
212
+ eventData,
213
+ retryIfLoginNeeded
214
+ })
215
+ return Promise.resolve()
216
+ }
217
+ }
@@ -0,0 +1,80 @@
1
+ import { describe, expect, test } from "vitest"
2
+
3
+ import { remainingTimeString } from "../common"
4
+
5
+ describe("types test set", () => {
6
+ test("ensure times string format", async () => {
7
+ const now = new Date(),
8
+ aSecond = 1000,
9
+ aMinute = aSecond * 60,
10
+ anHour = aMinute * 60,
11
+ aDay = anHour * 24,
12
+ aWeek = aDay * 7
13
+
14
+ const twentySeconds = 20 * aSecond,
15
+ threeMinutes = 3 * aMinute,
16
+ twoHours = 2 * anHour,
17
+ fiveDays = 5 * aDay,
18
+ tenWeeks = 10 * aWeek
19
+
20
+ // 10 weeks, 5 days, 2 hours, 3 minutes
21
+ expect(
22
+ remainingTimeString(
23
+ new Date(+now + tenWeeks + fiveDays + twoHours + threeMinutes),
24
+ now
25
+ )
26
+ ).toBe("10:wks 5:days")
27
+
28
+ // 1 weeks, 5 days, 2 hours, 3 minutes
29
+ expect(
30
+ remainingTimeString(
31
+ new Date(+now + aWeek + fiveDays + twoHours + threeMinutes),
32
+ now
33
+ )
34
+ ).toBe("1:wk 5:days")
35
+
36
+ // 5 days, 2 hours, 3 minutes
37
+ expect(
38
+ remainingTimeString(
39
+ new Date(+now + fiveDays + twoHours + threeMinutes),
40
+ now
41
+ )
42
+ ).toBe("5:days 2:hrs")
43
+
44
+ // 1 day, 2 hours, 3 minutes
45
+ expect(
46
+ remainingTimeString(new Date(+now + aDay + twoHours + threeMinutes), now)
47
+ ).toBe("1:day 2:hrs")
48
+
49
+ // 2 hours, 3 minutes
50
+ expect(
51
+ remainingTimeString(new Date(+now + twoHours + threeMinutes), now)
52
+ ).toBe("2:hrs 03:min")
53
+
54
+ // 1 hours, 3 minutes
55
+ expect(
56
+ remainingTimeString(new Date(+now + anHour + threeMinutes), now)
57
+ ).toBe("1:hr 03:min")
58
+
59
+ // 3 minutes, 20 seconds
60
+ expect(
61
+ remainingTimeString(new Date(+now + threeMinutes + twentySeconds), now)
62
+ ).toBe("03:min 20:sec")
63
+
64
+ // 1 minutes, 20 seconds
65
+ expect(
66
+ remainingTimeString(new Date(+now + aMinute + twentySeconds), now)
67
+ ).toBe("01:min 20:sec")
68
+
69
+ // 20 seconds
70
+ expect(remainingTimeString(new Date(+now + twentySeconds), now)).toBe(
71
+ "20:sec"
72
+ )
73
+
74
+ // 1 seconds
75
+ expect(remainingTimeString(new Date(+now + aSecond), now)).toBe("1:sec")
76
+
77
+ // 0 seconds
78
+ expect(remainingTimeString(now, now)).toBe("0:sec")
79
+ })
80
+ })
package/tsconfig.json ADDED
@@ -0,0 +1,114 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig to read more about this file */
4
+
5
+ /* Projects */
6
+ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
+ // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
+
13
+ /* Language and Environment */
14
+ "target": "ES2020" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
15
+ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
17
+ // "libReplacement": true, /* Enable lib replacement. */
18
+ // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
19
+ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
20
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
21
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
22
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
23
+ // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
24
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
25
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
26
+ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
27
+
28
+ /* Modules */
29
+ "module": "ES2020" /* Specify what module code is generated. */,
30
+ // "rootDir": "./", /* Specify the root folder within your source files. */
31
+ "moduleResolution": "bundler" /* Specify how TypeScript looks up a file from a given module specifier. */,
32
+ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
33
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
34
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
35
+ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
36
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
37
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
38
+ // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
39
+ // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
40
+ // "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */
41
+ // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
42
+ // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
43
+ // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
44
+ // "noUncheckedSideEffectImports": true, /* Check side effect imports. */
45
+ // "resolveJsonModule": true, /* Enable importing .json files. */
46
+ // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
47
+ // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
48
+
49
+ /* JavaScript Support */
50
+ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
51
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
52
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
53
+
54
+ /* Emit */
55
+ "declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */,
56
+ // "declarationMap": true, /* Create sourcemaps for d.ts files. */
57
+ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
58
+ "sourceMap": true /* Create source map files for emitted JavaScript files. */,
59
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
60
+ // "noEmit": true, /* Disable emitting files from a compilation. */
61
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
62
+ "outDir": "./dist" /* Specify an output folder for all emitted files. */,
63
+ // "removeComments": true, /* Disable emitting comments. */
64
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
65
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
66
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
67
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
68
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
69
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
70
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
71
+ // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
72
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
73
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
74
+ // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
75
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
76
+
77
+ /* Interop Constraints */
78
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
79
+ // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
80
+ // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
81
+ // "erasableSyntaxOnly": true, /* Do not allow runtime constructs that are not part of ECMAScript. */
82
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
83
+ "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
84
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
85
+ "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
86
+
87
+ /* Type Checking */
88
+ "strict": true /* Enable all strict type-checking options. */,
89
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
90
+ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
91
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
92
+ // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
93
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
94
+ // "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
95
+ // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
96
+ // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
97
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
98
+ // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
99
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
100
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
101
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
102
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
103
+ // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
104
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
105
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
106
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
107
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
108
+
109
+ /* Completeness */
110
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
111
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
112
+ },
113
+ "exclude": ["node_modules", "vitest.config.mts", "src/test", "dist"]
114
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { defineConfig } from "tsup"
2
+
3
+ export default defineConfig({
4
+ entry: ["index.ts"],
5
+ splitting: true,
6
+ treeshake: true,
7
+ platform: "browser",
8
+ sourcemap: true,
9
+ clean: true
10
+ })