forked from DA0-DA0/dao-dao-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.ts
116 lines (105 loc) · 2.32 KB
/
auth.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import { OfflineAminoSigner, makeSignDoc } from '@cosmjs/amino'
import {
getChainForChainId,
getNativeTokenForChainId,
secp256k1PublicKeyToBech32Address,
} from './chain'
export type SignatureOptions<
Data extends Record<string, unknown> | undefined = Record<string, any>
> = {
type: string
nonce: number
chainId: string
hexPublicKey: string
data: Data
offlineSignerAmino: OfflineAminoSigner
/**
* If true, don't sign the message and leave the signature field blank.
* Defaults to false.
*/
generateOnly?: boolean
}
export type Auth = {
type: string
nonce: number
chainId: string
chainFeeDenom: string
chainBech32Prefix: string
publicKey: string
}
export type SignedBody<
Data extends Record<string, unknown> | undefined = Record<string, any>
> = {
data: {
auth: Auth
} & Data
signature: string
}
/**
* Function to sign a message as a wallet in the format expected by our various
* off-chain services.
*/
export const signOffChainAuth = async <
Data extends Record<string, unknown> | undefined = Record<string, any>
>({
type,
nonce,
chainId,
hexPublicKey,
data,
offlineSignerAmino,
generateOnly = false,
}: SignatureOptions<Data>): Promise<SignedBody<Data>> => {
const chain = getChainForChainId(chainId)
const dataWithAuth: SignedBody<Data>['data'] = {
...data,
auth: {
type,
nonce,
chainId,
chainFeeDenom: getNativeTokenForChainId(chainId).denomOrAddress,
chainBech32Prefix: chain.bech32_prefix,
publicKey: hexPublicKey,
},
}
const signer = await secp256k1PublicKeyToBech32Address(
hexPublicKey,
chain.bech32_prefix
)
// Generate data to sign.
const signDocAmino = makeSignDoc(
[
{
type: dataWithAuth.auth.type,
value: {
signer,
data: JSON.stringify(dataWithAuth, undefined, 2),
},
},
],
{
gas: '0',
amount: [
{
denom: dataWithAuth.auth.chainFeeDenom,
amount: '0',
},
],
},
chain.chain_id,
'',
0,
0
)
let signature = ''
// Sign data.
if (!generateOnly) {
signature = (await offlineSignerAmino.signAmino(signer, signDocAmino))
.signature.signature
}
const signedBody: SignedBody<Data> = {
data: dataWithAuth,
signature,
}
return signedBody
}