Site=Lax; Max-Age=600`,
])
// Build authorization URL
const authUrl = new URL(serverInfo.authorization_endpoint)
authUrl.searchParams.set('client_id', clientId)
authUrl.searchParams.set('redirect_uri', redirectUri)
authUrl.searchParams.set('response_type', 'code')
authUrl.searchParams.set('scope', 'xion:transactions:submit')
authUrl.searchParams.set('state', state)
// Redirect to authorization endpoint
res.redirect(authUrl.toString())
} catch (error) {
console.error('Login error:', error)
res.status(500).json({ error: 'Failed to initiate OAuth flow' })
}
}
```
**Callback Endpoint (Token Exchange):**
```typescript
// pages/api/auth/callback.ts (Next.js API route example)
import type { NextApiRequest, NextApiResponse } from 'next'
import {
getOAuthServerInfo,
getClientId,
getClientSecret,
getRedirectUri,
} from '@/lib/oauth-config'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== 'GET') {
return res.status(405).json({ error: 'Method not allowed' })
}
const { code, state, error, error_description } = req.query
// Handle OAuth errors
if (error) {
return res.redirect(
`/?error=${encodeURIComponent(error as string)}&error_description=${encodeURIComponent(
(error_description as string) || ''
)}`
)
}
if (!code) {
return res.redirect('/?error=no_code')
}
// Verify state parameter
const storedState = req.cookies.oauth_state
if (!storedState || storedState !== state) {
res.setHeader('Set-Cookie', ['oauth_state=; Path=/; Max-Age=0'])
return res.redirect('/?error=invalid_state')
}
try {
const serverInfo = await getOAuthServerInfo()
const clientId = getClientId()
const clientSecret = getClientSecret()
const redirectUri = getRedirectUri(req)
// Exchange authorization code for access token
const tokenResponse = await fetch(serverInfo.token_endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'authorization_code',
code: code as string,
redirect_uri: redirectUri,
client_id: clientId,
client_secret: clientSecret, // Confidential Client: uses client_secret
}),
})
if (!tokenResponse.ok) {
const errorData = await tokenResponse.json().catch(() => ({ error: 'Token exchange failed' }))
throw new Error(errorData.error || 'Token exchange failed')
}
const tokens = await tokenResponse.json()
const expiresIn = tokens.expires_in || 3600
const expiration = Date.now() + expiresIn * 1000
// Clear state cookie
res.setHeader('Set-Cookie', ['oauth_state=; Path=/; Max-Age=0'])
// Store token in httpOnly cookie or session
res.setHeader('Set-Cookie', [
`oauth_token=${tokens.access_token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${expiresIn}`,
])
// Redirect to application
res.redirect('/dashboard')
} catch (error) {
console.error('Callback error:', error)
res.setHeader('Set-Cookie', ['oauth_state=; Path=/; Max-Age=0'])
res.redirect(
`/?error=${encodeURIComponent(
error instanceof Error ? error.message : 'Token exchange failed'
)}`
)
}
}
```
**Key Points for Backend Implementation:**
1. **Client Secret Security**: Never expose the `client_secret` to the client. Store it securely in environment variables and only use it server-side.
2. **State Verification**: Always verify the state parameter to prevent CSRF attacks. Store it in httpOnly cookies.
3. **Token Storage**: Store access tokens securely on the server. Use httpOnly cookies or server-side sessions.
4. **Error Handling**: Implement proper error handling for all OAuth2 flow steps and provide user-friendly error messages.
## 5. OAuth2 Protected APIs
Once you have an access token, you can use it to access protected OAuth2 APIs. These APIs allow you to interact with the Verona network on behalf of authenticated users.
### API Base URL
* **Testnet**: `https://oauth2.testnet.burnt.com/`
* **Mainnet**: `https://oauth2.burnt.com/`
#### API Documentation
For complete API documentation with interactive examples:
* **Testnet**: [OAuth2 Protected API Documentation](https://oauth2.testnet.burnt.com/protected-api-docs)
* **Mainnet**: [OAuth2 Protected API Documentation](https://oauth2.burnt.com/protected-api-docs)
#### Authentication
All protected API endpoints require authentication using a Bearer token in the `Authorization` header:
```typescript
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
}
```
### Available Endpoints
#### 1. Get Current User Information
**Endpoint**: `GET /api/v1/me`
Returns the authenticated user's **MetaAccount address** (`id`), **authenticators** registered on that account, and **balances** (e.g. Verona and USDC) resolved by the service.
**Request:**
```typescript
const response = await fetch('https://oauth2.testnet.burnt.com/api/v1/me', {
headers: {
'Authorization': `Bearer ${accessToken}`,
},
})
const userInfo = await response.json()
```
**Response** (shape is illustrative; see [OAuth2 Protected API Documentation](https://oauth2.testnet.burnt.com/protected-api-docs) for the live schema):
```json
{
"id": "xion1...",
"authenticators": [
{
"id": "xion1...-0",
"type": "secp256k1",
"index": 0,
"data": {}
}
],
"balances": {
"xion": {
"amount": "100.5",
"denom": "uxion",
"microAmount": "100500000"
},
"usdc": {
"amount": "0",
"denom": "uusdc",
"microAmount": "0"
}
}
}
```
Use **`id`** as the user's MetaAccount address when you need it for display, CosmJS queries, or building messages (the transaction API overwrites `fromAddress` / `sender` fields from the token for supported message types).
#### 2. Submit Transaction
**Endpoint**: `POST /api/v1/transaction`
Submits a blockchain transaction on behalf of the authenticated user. The transaction messages must be constructed using protobuf-based types from `@burnt-labs/xion-types`.
**Request:**
```typescript
const response = await fetch('https://oauth2.testnet.burnt.com/api/v1/transaction', {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
messages: [
// Array of EncodeObject messages
// See section 6 for message construction
],
}),
})
const result = await response.json()
```
**Response:**
```json
{
"success": true,
"tx_hash": "ABC123...",
"from": "xion1...",
"gasUsed": "100000",
"gasWanted": "150000"
}
```
`gasUsed` and `gasWanted` are included when available. There is **no** top-level block `height` on this response; use the transaction status endpoint below if you need inclusion height.
**Transaction Messages**: The `messages` array contains protobuf-encoded transaction messages. Each message must have a `typeUrl` and `value` field. See section 6: Building Transactions for details on constructing messages.
#### 3. Query Transaction Status
**Endpoint**: `GET /api/v1/transaction/{txHash}/status`
Queries the status of a previously submitted transaction from the chain (Cosmos SDK tx result).
**Request:**
```typescript
const txHash = 'ABC123...'
const response = await fetch(
`https://oauth2.testnet.burnt.com/api/v1/transaction/${txHash}/status`,
{
headers: {
'Authorization': `Bearer ${accessToken}`,
},
}
)
const status = await response.json()
```
**Response:**
```json
{
"hash": "ABC123...",
"height": 12345,
"code": 0,
"gasUsed": 100000,
"gasWanted": 150000
}
```
**`code`**: `0` means the transaction executed successfully; non-zero values indicate failure (Cosmos SDK convention). The response may also include a `tx` field with raw transaction data.
#### 4. Simulate Transaction
**Endpoint**: `POST /api/v1/transaction/simulate`
Simulates a transaction execution without actually submitting it to the blockchain. Useful for estimating gas costs and validating transaction logic.
**Request:**
```typescript
const response = await fetch('https://oauth2.testnet.burnt.com/api/v1/transaction/simulate', {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
messages: [
// Array of EncodeObject messages
],
}),
})
const simulation = await response.json()
```
**Response:**
```json
{
"success": true,
"gasEstimate": 50000,
"fees": {
"amount": [
{
"denom": "uxion",
"amount": "1250"
}
],
"gas": "50000"
},
"simulatedAt": "2024-01-01T00:00:00.000Z"
}
```
`fees.amount` is derived from the current gas price configuration; treat numbers as illustrative.
### Complete API Client Example
Here's a complete example of an API client with automatic token injection:
```typescript
// utils/api.ts
import axios, { AxiosInstance } from 'axios'
import { getTokenInfo, getOAuthServerUrl } from './oauth'
const createApiClient = (): AxiosInstance => {
const apiClient = axios.create({
baseURL: getOAuthServerUrl(),
headers: {
'Content-Type': 'application/json',
},
})
// Add Bearer token to all requests
apiClient.interceptors.request.use(
(config) => {
const tokenInfo = getTokenInfo()
if (tokenInfo) {
config.headers['Authorization'] = `Bearer ${tokenInfo.accessToken}`
}
return config
},
(error) => {
return Promise.reject(error)
}
)
return apiClient
}
export const apiClient = createApiClient()
export const accountApi = {
getMe: async () => {
const response = await apiClient.get('/api/v1/me')
return response.data
},
}
export const transactionApi = {
sendTransaction: async (messages: any[]) => {
const response = await apiClient.post('/api/v1/transaction', {
messages,
})
return response.data
},
getTransactionStatus: async (txHash: string) => {
const response = await apiClient.get(`/api/v1/transaction/${txHash}/status`)
return response.data
},
simulateTransaction: async (messages: any[]) => {
const response = await apiClient.post('/api/v1/transaction/simulate', {
messages,
})
return response.data
},
}
```
## 6. Building Transactions
To submit transactions via the OAuth2 API, you need to construct transaction messages using protobuf-based types from the `@burnt-labs/xion-types` package. These messages are then encoded and sent to the transaction API endpoint.
### Installing Verona Types
```bash
# npm
npm install @burnt-labs/xion-types
# pnpm
pnpm install @burnt-labs/xion-types
# yarn
yarn add @burnt-labs/xion-types
# bun
bun add @burnt-labs/xion-types
```
### Understanding Transaction Messages
Transaction messages on Verona use protobuf encoding. Each message has:
* **`typeUrl`**: The protobuf message type URL (e.g., `"/cosmos.bank.v1beta1.MsgSend"`)
* **`value`**: The protobuf-encoded message value
The OAuth2 Transaction API accepts an array of these messages in the `messages` field.
### Critical Relationship: Treasury Permissions
{% hint style="warning" %}
**Important**: Only message types that are explicitly authorized in your Treasury contract's permissions can be used in OAuth2 transaction requests.
{% endhint %}
For example:
* If your Treasury only has permission for `MsgSend`, you can only send tokens via OAuth2
* If your Treasury has permission for `MsgExecuteContract`, you can execute smart contract calls
* You can configure multiple permissions to allow different transaction types
Before constructing transaction messages, ensure the corresponding permissions are configured in your Treasury contract. See the [Treasury Contracts Documentation](/en/build-on-verona/accounts/getting-started/treasury-contracts) for details on configuring permissions.
The OAuth2 service may accept additional Cosmos message types when your Treasury grants allow them (for example staking, governance, or Verona-specific bank messages). The exhaustive list depends on the server version—use [OAuth2 Protected API Documentation](https://oauth2.testnet.burnt.com/protected-api-docs) and your Treasury configuration as the source of truth.
### Message Construction Examples
#### Sending Tokens (MsgSend)
Reference: [xion-types MsgSend Guide](https://github.com/burnt-labs/xion-types/blob/main/examples/typescript/GUIDE.md#msgsend-transfer-tokens)
```typescript
import { EncodeObject } from '@cosmjs/proto-signing'
import { MsgSend } from '@burnt-labs/xion-types/types/cosmos/bank/v1beta1/tx'
export function createSendTokensMessage(
toAddress: string,
amount: number,
denom: string
): EncodeObject {
return {
typeUrl: MsgSend.typeUrl,
value: MsgSend.fromPartial({
toAddress: toAddress,
amount: [
{
denom: denom,
amount: amount.toString(),
},
],
}),
}
}
// Usage in transaction API
const message = createSendTokensMessage(
'xion1...', // recipient address
1000000, // amount (in base units, e.g., uxion)
'uxion' // denomination
)
const response = await transactionApi.sendTransaction([message])
```
#### Executing Smart Contracts (MsgExecuteContract)
Reference: [xion-types MsgExecuteContract Guide](https://github.com/burnt-labs/xion-types/blob/main/examples/typescript/GUIDE.md#msgexecutecontract-call-a-smart-contract)
```typescript
import { EncodeObject } from '@cosmjs/proto-signing'
import { MsgExecuteContract } from '@burnt-labs/xion-types/types/cosmwasm/wasm/v1/tx'
export function createExecuteContractMessage(
sender: string,
contract: string,
msg: any, // Contract-specific message
funds: Array<{ denom: string; amount: string }> = []
): EncodeObject {
const executeMsg = MsgExecuteContract.fromPartial({
sender: sender,
contract: contract,
msg: new TextEncoder().encode(JSON.stringify(msg)),
funds: funds,
})
return MsgExecuteContract.toProtoMsg(executeMsg)
}
// Usage example: Execute a contract method (use GET /api/v1/me → `id` as sender when you need the MetaAccount address)
const message = createExecuteContractMessage(
'xion1...', // sender: MetaAccount address from `GET /api/v1/me` (`id`); server may overwrite from the OAuth token
'xion1contract...', // contract address
{ // contract message
increment: {},
},
[] // optional funds to send
)
const response = await transactionApi.sendTransaction([message])
```
#### Instantiating Contracts (MsgInstantiateContract)
Reference: [xion-types MsgInstantiateContract Guide](https://github.com/burnt-labs/xion-types/blob/main/examples/typescript/cosmwasm-v1-transaction-messages.ts#L177-L203)
```typescript
import { EncodeObject } from '@cosmjs/proto-signing'
import { MsgInstantiateContract } from '@burnt-labs/xion-types/types/cosmwasm/wasm/v1/tx'
export function createInstantiateContractMessage(
sender: string,
codeId: number,
initMsg: any,
label: string,
funds: Array<{ denom: string; amount: string }> = []
): EncodeObject {
const msg = MsgInstantiateContract.fromPartial({
sender: sender,
admin: sender, // Optional: address that can migrate contract
codeId: BigInt(codeId),
label: label,
msg: new TextEncoder().encode(JSON.stringify(initMsg)),
funds: funds,
})
return MsgInstantiateContract.toProtoMsg(msg)
}
// Usage example: Instantiate a CW20 token contract (prefer `GET /api/v1/me` → `id` for sender)
const sender = 'xion1...'
const cw20InitMsg = {
name: 'My Token',
symbol: 'MTK',
decimals: 6,
initial_balances: [
{ address: sender, amount: '1000000' },
],
mint: { minter: sender },
}
const message = createInstantiateContractMessage(
sender, // sender address
510, // code ID
cw20InitMsg, // initialization message
'My Token Contract', // label
[] // optional funds
)
const response = await transactionApi.sendTransaction([message])
```
### Complete Transaction Example
Here's a complete example combining message construction and API usage:
```typescript
// utils/transactions.ts
import { EncodeObject } from '@cosmjs/proto-signing'
import { MsgSend } from '@burnt-labs/xion-types/types/cosmos/bank/v1beta1/tx'
import { transactionApi } from './api'
export function createSendTokensMessage(
toAddress: string,
amount: number,
denom: string
): EncodeObject {
return {
typeUrl: MsgSend.typeUrl,
value: MsgSend.fromPartial({
toAddress: toAddress,
amount: [
{
denom: denom,
amount: amount.toString(),
},
],
}),
}
}
// Usage in a component or function
async function sendTokens(toAddress: string, amount: number) {
const message = createSendTokensMessage(toAddress, amount, 'uxion')
const result = await transactionApi.sendTransaction([message])
console.log('Transaction hash:', result.txhash)
return result
}
```
### More Examples
For more transaction message construction examples, see:
* [xion-types TypeScript Examples](https://github.com/burnt-labs/xion-types/tree/main/examples/typescript)
* [xion-types TypeScript Guide](https://github.com/burnt-labs/xion-types/blob/main/examples/typescript/GUIDE.md)
* [OAuth2 App Demo - Transactions](https://github.com/burnt-labs/xion-oauth2-app-demo/blob/main/examples/frontend%2Bpublic_client/src/utils/transactions.ts)
## 7. Querying Blockchain Data
While the OAuth2 API provides endpoints for submitting transactions and querying transaction status, for general blockchain data queries (account balances, contract state, block information, etc.), you should use `@cosmjs/stargate` directly.
### Using CosmJS for Queries
CosmJS is the standard library for interacting with Cosmos SDK-based blockchains, including Verona. For detailed instructions on using CosmJS with Verona, refer to the Interact with Verona via your Backend Service guide, specifically the "Querying the Blockchain" section.
### Installation
```bash
# npm
npm install @cosmjs/stargate
# pnpm
pnpm install @cosmjs/stargate
# yarn
yarn add @cosmjs/stargate
# bun
bun add @cosmjs/stargate
```
### Example: Querying Account Balance
```typescript
import { StargateClient } from '@cosmjs/stargate'
async function getBalance(address: string, denom: string = 'uxion') {
const rpcUrl = process.env.XION_RPC_URL || 'https://rpc.xion-testnet-2.burnt.com:443'
const client = await StargateClient.connect(rpcUrl)
const balance = await client.getBalance(address, denom)
return balance.amount
}
```
### Example: Querying Contract State
```typescript
import { StargateClient } from '@cosmjs/stargate'
async function queryContract(contractAddress: string, queryMsg: any) {
const rpcUrl = process.env.XION_RPC_URL || 'https://rpc.xion-testnet-2.burnt.com:443'
const client = await StargateClient.connect(rpcUrl)
return await client.queryContractSmart(contractAddress, queryMsg)
}
```
### Why Use CosmJS for Queries?
* **Comprehensive Query Support**: CosmJS provides access to all Cosmos SDK query endpoints
* **No Authentication Required**: Queries don't require OAuth2 tokens
* **Standard Library**: Well-documented and widely used in the Cosmos ecosystem
* **Direct RPC Access**: Connects directly to Verona RPC nodes
{% hint style="info" %}
**Future OAuth2 Query Endpoints**: The OAuth2 API may add query endpoints in future iterations based on product requirements. However, CosmJS already covers most use cases for querying blockchain data.
{% endhint %}
### RPC Endpoints
For a list of available RPC endpoints for each network, see the [Public Endpoints and Resources](/en/build-on-verona/references/public-endpoints-and-resources) documentation.
## Additional Resources
* **OAuth2 API (testnet)**: <https://oauth2.testnet.burnt.com/>
* **OAuth2 API (mainnet)**: <https://oauth2.burnt.com/>
* **OAuth2 Client Management (testnet)**: <https://dev.testnet.burnt.com/oauth2-clients>
* **OAuth2 Client Management (mainnet)**: <https://dev.burnt.com/oauth2-clients>
* **OAuth2 Protected API docs (testnet)**: <https://oauth2.testnet.burnt.com/protected-api-docs>
* **OAuth2 Protected API docs (mainnet)**: <https://oauth2.burnt.com/protected-api-docs>
* **OAuth2 App Examples**: <https://github.com/burnt-labs/xion-oauth2-app-demo>
* **Verona Types Repository**: <https://github.com/burnt-labs/xion-types>
* **Verona Types TypeScript Guide**: <https://github.com/burnt-labs/xion-types/blob/main/examples/typescript/GUIDE.md>
* **Treasury Contracts Documentation**: [Enabling Gasless Transactions with Treasury Contracts](/en/build-on-verona/accounts/g프로젝트로 돌아가기