Skip to content

Commit

Permalink
Merge pull request o1-labs#974 from qwadratic/fix-fmt-rosetta-samples
Browse files Browse the repository at this point in the history
run dprint on rosetta typescript samples
  • Loading branch information
shimkiv authored May 22, 2024
2 parents 7382845 + 37b19d6 commit b8b1e05
Show file tree
Hide file tree
Showing 6 changed files with 424 additions and 321 deletions.
21 changes: 11 additions & 10 deletions docs/exchange-operators/rosetta/samples/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -16,25 +16,26 @@ Start with the required imports and define constants:
<TabItem value="ts" label="TypeScript">

```ts
import { Client } from 'mina-signer'
import axios from 'axios'
import axios from "axios"
import { Client } from "mina-signer"

const TESTNET_NETWORK_IDENTIFIER = {
"network_identifier": {
"blockchain": "mina",
"network": "testnet"
}
network_identifier: {
blockchain: "mina",
network: "testnet",
},
}
const MINA_TOKEN_ID = "1"
const MINA_TOKEN_ID = "wSHV2S4qX9jFsLjQo8r1BsMLH2ZRKsZx6EJd1sbozGPieEC4Jf"
const MINA_DECIMALS = 9
const MINA_SYMBOL = "MINA"
const MINA_CURVE_TYPE = "pallas"

const mina = new Client({network: 'testnet'})
const mina = new Client({ network: "testnet" })

const request = axios.create({
baseURL: "https://rosetta-devnet.minaprotocol.network/"
baseURL: "https://rosetta-devnet.minaprotocol.network/",
})
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
```

</TabItem>
Expand Down
220 changes: 133 additions & 87 deletions docs/exchange-operators/rosetta/samples/requests.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@ First, implement the generic `request` function to perform Rosetta API calls inj

```ts
async function makeRequest(endpoint: string, data?: any) {
if (data === undefined)
if (data === undefined) {
data = {}
if (endpoint !== '/network/list')
data = {...TESTNET_NETWORK_IDENTIFIER, ...data}
}
if (endpoint !== "/network/list") {
data = { ...TESTNET_NETWORK_IDENTIFIER, ...data }
}

const r = await request.post(endpoint, data)
return r.data
Expand Down Expand Up @@ -71,27 +73,27 @@ To implement helpers to construct the objects:

```ts
function makeBlockIdentifier(idOrHash: number | string) {
const identifierKey = (typeof idOrHash === "number") ? "index" : "hash"
return {
block_identifier: {[identifierKey]: idOrHash}
}
const identifierKey = (typeof idOrHash === "number") ? "index" : "hash"
return {
block_identifier: { [identifierKey]: idOrHash },
}
}

function makeTxIdentifier(hash: string) {
return {"transaction_identifier": {'hash': hash}}
return { transaction_identifier: { hash: hash } }
}

function makeAccountIdentifier(address: string) {
return {
account_identifier: {address, token_id: MINA_TOKEN_ID}
}
return {
account_identifier: { address, token_id: MINA_TOKEN_ID },
}
}

function makePublicKey(publicKey: string) {
return {
hex_bytes: publicKey,
curve_type: MINA_CURVE_TYPE
}
return {
hex_bytes: publicKey,
curve_type: MINA_CURVE_TYPE,
}
}
```

Expand Down Expand Up @@ -263,44 +265,68 @@ To implement a helper function to construct the operations array for a MINA toke

```ts
function makeTransferPayload(from: string, to: string, feeNano: number, valueNano: number) {

function makeOperation(idx: number, relatedIdxs: number[], op_type: string, addr: string, value: number, isPositive: boolean) {
const relatedOps = (relatedIdxs.length == 0) ? {} : {
related_operations: relatedIdxs.map((i) => {
return {index: i}
})
}

return {
operation_identifier: {index: idx},
...relatedOps,
type: op_type,
account: {
address: addr,
metadata: {
token_id: MINA_TOKEN_ID
}
},
amount: {
value: (isPositive ? "" : "-") + value.toString(),
currency: {
symbol: MINA_SYMBOL,
decimals: MINA_DECIMALS
}
}
}
function makeOperation(
idx: number,
relatedIdxs: number[],
opType: string,
addr: string,
value: number,
isPositive: boolean,
) {
const relatedOps = (relatedIdxs.length == 0) ? {} : {
related_operations: relatedIdxs.map((i) => {
return { index: i }
}),
}

return {
operations: [
makeOperation(
0, [], "fee_payment", from, feeNano, false),
makeOperation(
1, [], "payment_source_dec", from, valueNano, false),
makeOperation(
2, [1], "payment_receiver_inc", to, valueNano, true)
]
operation_identifier: { index: idx },
...relatedOps,
type: opType,
account: {
address: addr,
metadata: {
token_id: MINA_TOKEN_ID,
},
},
amount: {
value: (isPositive ? "" : "-") + value.toString(),
currency: {
symbol: MINA_SYMBOL,
decimals: MINA_DECIMALS,
},
},
}
}

return {
operations: [
makeOperation(
0,
[],
"fee_payment",
from,
feeNano,
false,
),
makeOperation(
1,
[],
"payment_source_dec",
from,
valueNano,
false,
),
makeOperation(
2,
[1],
"payment_receiver_inc",
to,
valueNano,
true,
),
],
}
}
```

Expand Down Expand Up @@ -364,90 +390,110 @@ Now that you have all helpers in place, you can implement all of the Rosetta cli

```ts
async function networkList() {
return await makeRequest('/network/list')
return await makeRequest("/network/list")
}

async function networkStatus() {
return await makeRequest('/network/status')
return await makeRequest("/network/status")
}

async function networkOptions() {
return await makeRequest('/network/options')
return await makeRequest("/network/options")
}

async function block(idOrHash: number | string) {
return await makeRequest('/block', makeBlockIdentifier(idOrHash))
return await makeRequest("/block", makeBlockIdentifier(idOrHash))
}

async function mempool() {
return await makeRequest('/mempool')
return await makeRequest("/mempool")
}

async function mempoolTx(hash: string) {
return await makeRequest('/mempool/transaction', makeTxIdentifier(hash))
return await makeRequest("/mempool/transaction", makeTxIdentifier(hash))
}

async function accountBalance(address: string) {
return await makeRequest('/account/balance', makeAccountIdentifier(address))
return await makeRequest("/account/balance", makeAccountIdentifier(address))
}

async function accountTransactions(address: string) {
return await makeRequest('/search/transactions', {address: address})
return await makeRequest("/search/transactions", { address: address })
}

async function getTransaction(hash: string) {
return await makeRequest('/search/transactions', makeTxIdentifier(hash))
return await makeRequest("/search/transactions", makeTxIdentifier(hash))
}

async function deriveAccountIdentifier(publicKey: string) {
return await makeRequest('/construction/derive', {
public_key: makePublicKey(publicKey)
})
return await makeRequest("/construction/derive", {
public_key: makePublicKey(publicKey),
})
}

async function txPreprocess(from: string, to: string, feeNano: number, valueNano: number) {
const payload = makeTransferPayload(from, to, feeNano, valueNano)
return await makeRequest('/construction/preprocess', payload)
const payload = makeTransferPayload(from, to, feeNano, valueNano)
return await makeRequest("/construction/preprocess", payload)
}

async function txMetadata(srcPublicKey: string, srcAddress: string, destAddress: string, feeNano: number, valueNano: number) {
const options = await txPreprocess(srcAddress, destAddress, feeNano, valueNano)
return await makeRequest('/construction/metadata', {
...options, public_keys: [makePublicKey(srcPublicKey)]
})
async function txMetadata(
srcPublicKey: string,
srcAddress: string,
destAddress: string,
feeNano: number,
valueNano: number,
) {
const options = await txPreprocess(srcAddress, destAddress, feeNano, valueNano)
return await makeRequest("/construction/metadata", {
...options,
public_keys: [makePublicKey(srcPublicKey)],
})
}

async function txPayloads(srcPublicKey: string, srcAddress: string, destAddress: string, feeNano: number, valueNano: number) {
// If fee_nano is undefined, it will get suggested fee from /construction/metadata response
const meta = await txMetadata(
srcPublicKey, srcAddress, destAddress, feeNano, valueNano)

if (feeNano === 0)
feeNano = meta.suggested_fee[0].value
console.log(feeNano)
const operations = makeTransferPayload(srcAddress, destAddress, feeNano, valueNano)
return makeRequest('/construction/payloads', {...operations, ...meta})
async function txPayloads(
srcPublicKey: string,
srcAddress: string,
destAddress: string,
feeNano: number,
valueNano: number,
) {
// If fee_nano is undefined, it will get suggested fee from /construction/metadata response
const meta = await txMetadata(
srcPublicKey,
srcAddress,
destAddress,
feeNano,
valueNano,
)

if (feeNano === 0) {
feeNano = meta.suggested_fee[0].value
}
console.log(feeNano)
const operations = makeTransferPayload(srcAddress, destAddress, feeNano, valueNano)
return makeRequest("/construction/payloads", { ...operations, ...meta })
}

async function txCombine(payloadsResponse: any, privateKey: string) {
const combinePayload = mina.rosettaCombinePayload(payloadsResponse, privateKey)
const r = await makeRequest('/construction/combine', combinePayload)
return r
// console.dir(payloadsResponse, {depth: null})
const combinePayload = mina.rosettaCombinePayload(payloadsResponse, privateKey)
const r = await makeRequest("/construction/combine", combinePayload)
return r
}

async function txParse(isSigned: boolean, blob: string) {
return makeRequest('/construction/parse', {
signed: isSigned,
transaction: blob
})
return makeRequest("/construction/parse", {
signed: isSigned,
transaction: blob,
})
}

async function txHash(blob: string) {
return await makeRequest('construction/hash', {signed_transaction: blob})
return await makeRequest("construction/hash", { signed_transaction: blob })
}

async function txSubmit(blob: string) {
return await makeRequest('construction/submit', {signed_transaction: blob})
return await makeRequest("construction/submit", { signed_transaction: blob })
}
```

Expand Down
20 changes: 10 additions & 10 deletions docs/exchange-operators/rosetta/samples/scan-blocks.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,14 @@ To implement a simple function to wait for a given block:

```ts
async function waitForBlock(blockHeight: number) {
let latestBlock = (await networkStatus()).current_block_identifier.index
while (true) {
if (blockHeight <= latestBlock)
return await block(blockHeight)
await sleep(10000)
latestBlock = (await networkStatus()).current_block_identifier.index
let latestBlock = (await networkStatus()).current_block_identifier.index
while (true) {
if (blockHeight <= latestBlock) {
return await block(blockHeight)
}
await sleep(10000)
latestBlock = (await networkStatus()).current_block_identifier.index
}
}
```

Expand Down Expand Up @@ -54,11 +55,10 @@ It can be used to scan blocks like this:
```ts
let latestBlockHeight = (await network_status()).current_block_identifier.index
while (true) {
const lastBlock = waitForBlock(latestBlockHeight)
const lastBlock = waitForBlock(latestBlockHeight)
// some processing according to business logic

# some processing according to business logic

latestBlockHeight += 1
latestBlockHeight += 1
}
```

Expand Down
Loading

0 comments on commit b8b1e05

Please sign in to comment.