Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove buffer usage in favor or Uint8Array and Dataview #800

Merged
merged 18 commits into from
Jul 18, 2023
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion examples/accounts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,11 @@ async function main() {

const acctInfo = await client.accountInformation(acct1.addr).do();

console.log(`Account Info: ${acctInfo} Auth Addr: ${acctInfo['auth-addr']}`);
console.log(
`Account Info: ${JSON.stringify(acctInfo)} Auth Addr: ${
acctInfo['auth-addr']
}`
);
// example: ACCOUNT_REKEY

// the transaction is from originalAccount, but signed with newSigner private key
Expand Down
34 changes: 15 additions & 19 deletions examples/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
/* eslint-disable no-console */
import fs from 'fs';
import path from 'path';
import { Buffer } from 'buffer';
import { getLocalAlgodClient, getLocalAccounts, compileProgram } from './utils';
import algosdk from '../src';
import { base64ToBytes, base64ToString } from '../src/utils/utils';
jasonpaulos marked this conversation as resolved.
Show resolved Hide resolved

async function main() {
const algodClient = getLocalAlgodClient();
Expand All @@ -27,20 +27,16 @@ async function main() {
// example: APP_SOURCE

// example: APP_COMPILE
const approvalCompileResp = await algodClient
.compile(Buffer.from(approvalProgram))
.do();
const approvalCompileResp = await algodClient.compile(approvalProgram).do();

const compiledApprovalProgram = new Uint8Array(
Buffer.from(approvalCompileResp.result, 'base64')
const compiledApprovalProgram: Uint8Array = base64ToBytes(
approvalCompileResp.result
);

const clearCompileResp = await algodClient
.compile(Buffer.from(clearProgram))
.do();
const clearCompileResp = await algodClient.compile(clearProgram).do();

const compiledClearProgram = new Uint8Array(
Buffer.from(clearCompileResp.result, 'base64')
const compiledClearProgram: Uint8Array = base64ToBytes(
clearCompileResp.result
);
// example: APP_COMPILE

Expand All @@ -55,8 +51,8 @@ async function main() {
// example: APP_CREATE
const appCreateTxn = algosdk.makeApplicationCreateTxnFromObject({
from: creator.addr,
approvalProgram: compiledApprovalProgram,
clearProgram: compiledClearProgram,
approvalProgram: new Uint8Array(compiledApprovalProgram),
clearProgram: new Uint8Array(compiledClearProgram),
numGlobalByteSlices,
numGlobalInts,
numLocalByteSlices,
Expand Down Expand Up @@ -138,7 +134,7 @@ async function main() {
from: caller.addr,
suggestedParams,
appIndex: appId,
appArgs: [new Uint8Array(Buffer.from(now))],
appArgs: [new TextEncoder().encode(now)],
});

await algodClient
Expand All @@ -157,10 +153,10 @@ async function main() {
console.log(`Raw global state - ${JSON.stringify(globalState)}`);

// decode b64 string key with Buffer
const globalKey = Buffer.from(globalState.key, 'base64').toString();
const globalKey = base64ToString(globalState.key);
// decode b64 address value with encodeAddress and Buffer
const globalValue = algosdk.encodeAddress(
Buffer.from(globalState.value.bytes, 'base64')
base64ToBytes(globalState.value.bytes)
);

console.log(`Decoded global state - ${globalKey}: ${globalValue}`);
Expand All @@ -173,7 +169,7 @@ async function main() {
console.log(`Raw local state - ${JSON.stringify(localState)}`);

// decode b64 string key with Buffer
const localKey = Buffer.from(localState.key, 'base64').toString();
const localKey = base64ToString(localState.key);
// get uint value directly
const localValue = localState.value.uint;

Expand Down Expand Up @@ -209,8 +205,8 @@ async function main() {
suggestedParams,
appIndex: appId,
// updates must define both approval and clear programs, even if unchanged
approvalProgram: compiledNewProgram,
clearProgram: compiledClearProgram,
approvalProgram: new Uint8Array(compiledNewProgram),
clearProgram: new Uint8Array(compiledClearProgram),
});

await algodClient
Expand Down
4 changes: 2 additions & 2 deletions examples/asa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@ async function main() {
// example: ASSET_INFO
const assetInfo = await algodClient.getAssetByID(assetIndex).do();
console.log(`Asset Name: ${assetInfo.params.name}`);
console.log(`Asset Params: ${assetInfo.params}`);
console.log(`Asset Params: ${JSON.stringify(assetInfo.params)}`);
// example: ASSET_INFO

await new Promise((f) => setTimeout(f, 1000)); // sleep to ensure indexer is caught up
await new Promise((f) => setTimeout(f, 2000)); // sleep to ensure indexer is caught up

// example: INDEXER_LOOKUP_ASSET
const indexer = getLocalIndexerClient();
Expand Down
3 changes: 1 addition & 2 deletions examples/atc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
/* eslint-disable no-console */
import fs from 'fs';
import path from 'path';
import { Buffer } from 'buffer';
import algosdk from '../src';
import { getLocalAlgodClient, getLocalAccounts, compileProgram } from './utils';

Expand Down Expand Up @@ -99,7 +98,7 @@ async function main() {

// example: ATC_BOX_REF
const boxATC = new algosdk.AtomicTransactionComposer();
const boxKey = new Uint8Array(Buffer.from('key'));
const boxKey = new TextEncoder().encode('key');
boxATC.addMethodCall({
appID: appIndex,
method: boxAccessorMethod,
Expand Down
23 changes: 13 additions & 10 deletions examples/codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@
/* eslint-disable import/no-unresolved */
/* eslint-disable no-promise-executor-return */
/* eslint-disable no-console */
import { Buffer } from 'buffer';
import algosdk from '../src';
import { getLocalAlgodClient, getLocalAccounts } from './utils';
import {
base64ToBytes,
base64ToString,
bytesToBase64,
bytesToHex,
} from '../src/utils/utils';

async function main() {
const client = getLocalAlgodClient();
Expand All @@ -22,7 +27,7 @@ async function main() {

// example: CODEC_BASE64
const b64Encoded = 'SGksIEknbSBkZWNvZGVkIGZyb20gYmFzZTY0';
const b64Decoded = Buffer.from(b64Encoded, 'base64').toString();
const b64Decoded = base64ToString(b64Encoded);
console.log(b64Encoded, b64Decoded);
// example: CODEC_BASE64

Expand All @@ -43,19 +48,17 @@ async function main() {
});

const txnBytes = algosdk.encodeUnsignedTransaction(txn);
const txnB64 = Buffer.from(txnBytes).toString('base64');
const txnB64 = bytesToBase64(txnBytes);
// ...
const restoredTxn = algosdk.decodeUnsignedTransaction(
Buffer.from(txnB64, 'base64')
);
const restoredTxn = algosdk.decodeUnsignedTransaction(base64ToBytes(txnB64));
console.log(restoredTxn);
// example: CODEC_TRANSACTION_UNSIGNED

// example: CODEC_TRANSACTION_SIGNED
const signedTxn = txn.signTxn(sender.privateKey);
const signedB64Txn = Buffer.from(signedTxn).toString('base64');
const signedB64Txn = bytesToBase64(signedTxn);
const restoredSignedTxn = algosdk.decodeSignedTransaction(
Buffer.from(signedB64Txn, 'base64')
base64ToBytes(signedB64Txn)
);
console.log(restoredSignedTxn);
// example: CODEC_TRANSACTION_SIGNED
Expand All @@ -65,7 +68,7 @@ async function main() {

const stringTupleData = ['hello', 'world'];
const encodedTuple = stringTupleCodec.encode(stringTupleData);
console.log(Buffer.from(encodedTuple).toString('hex'));
console.log(bytesToHex(encodedTuple));

const decodedTuple = stringTupleCodec.decode(encodedTuple);
console.log(decodedTuple); // ['hello', 'world']
Expand All @@ -74,7 +77,7 @@ async function main() {

const uintArrayData = [1, 2, 3, 4, 5];
const encodedArray = uintArrayCodec.encode(uintArrayData);
console.log(Buffer.from(encodedArray).toString('hex'));
console.log(bytesToHex(encodedArray));

const decodeArray = uintArrayCodec.decode(encodedArray);
console.log(decodeArray); // [1, 2, 3, 4, 5]
Expand Down
5 changes: 2 additions & 3 deletions examples/indexer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
/* eslint-disable import/no-unresolved */
/* eslint-disable no-promise-executor-return */
/* eslint-disable no-console */
import { Buffer } from 'buffer';
import {
getLocalIndexerClient,
getLocalAccounts,
Expand Down Expand Up @@ -68,7 +67,7 @@ async function main() {
from: sender.addr,
to: sender.addr,
amount: 1e6,
note: new Uint8Array(Buffer.from('Hello World!')),
note: new TextEncoder().encode('Hello World!'),
suggestedParams,
});

Expand All @@ -80,7 +79,7 @@ async function main() {
// example: INDEXER_PREFIX_SEARCH
const txnsWithNotePrefix = await indexerClient
.searchForTransactions()
.notePrefix(Buffer.from('Hello'))
.notePrefix(new TextEncoder().encode('Hello'))
.do();
console.log(
`Transactions with note prefix "Hello" ${JSON.stringify(
Expand Down
17 changes: 7 additions & 10 deletions examples/lsig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
/* eslint-disable import/no-unresolved */
/* eslint-disable no-promise-executor-return */
/* eslint-disable no-console */
import { Buffer } from 'buffer';
import algosdk from '../src';
import { base64ToBytes } from '../src/utils/utils';
import { getLocalAlgodClient, getLocalAccounts } from './utils';

async function main() {
Expand All @@ -14,7 +14,9 @@ async function main() {

// example: LSIG_COMPILE
const smartSigSource = '#pragma version 8\nint 1\nreturn'; // approve everything
const result = await client.compile(Buffer.from(smartSigSource)).do();
const result = await client
.compile(new TextEncoder().encode(smartSigSource))
.do();

// Hash is equivalent to the contract address
console.log('Hash: ', result.hash);
Expand All @@ -23,17 +25,12 @@ async function main() {
// example: LSIG_COMPILE

// example: LSIG_INIT
let smartSig = new algosdk.LogicSig(
new Uint8Array(Buffer.from(b64program, 'base64'))
);
let smartSig = new algosdk.LogicSig(base64ToBytes(b64program));
// example: LSIG_INIT

// example: LSIG_PASS_ARGS
const args = [Buffer.from('This is an argument!')];
smartSig = new algosdk.LogicSig(
new Uint8Array(Buffer.from(b64program, 'base64')),
args
);
const args = [new TextEncoder().encode('This is an argument!')];
smartSig = new algosdk.LogicSig(base64ToBytes(b64program), args);
// example: LSIG_PASS_ARGS

const fundSmartSigTxn = algosdk.makePaymentTxnWithSuggestedParamsFromObject({
Expand Down
9 changes: 5 additions & 4 deletions examples/overview.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { Buffer } from 'buffer';
import algosdk from '../src';
import { getLocalAccounts, getLocalAlgodClient } from './utils';

Expand Down Expand Up @@ -27,7 +26,7 @@ async function main() {
suggestedParams,
to: acct2.addr,
amount: 10000,
note: new Uint8Array(Buffer.from('hello world')),
note: new TextEncoder().encode('hello world'),
});
// example: TRANSACTION_PAYMENT_CREATE

Expand All @@ -39,8 +38,10 @@ async function main() {
const { txId } = await algodClient.sendRawTransaction(signedTxn).do();
const result = await algosdk.waitForConfirmation(algodClient, txId, 4);
console.log(result);
console.log(`Transaction Information: ${result.txn}`);
console.log(`Decoded Note: ${Buffer.from(result.txn.txn.note).toString()}`);
console.log(`Transaction Information: ${JSON.stringify(result.txn)}`);
console.log(
`Decoded Note: ${new TextDecoder('utf-8').decode(result.txn.txn.note)}`
);
// example: TRANSACTION_PAYMENT_SUBMIT

// example: ALGOD_FETCH_ACCOUNT_INFO
Expand Down
12 changes: 6 additions & 6 deletions examples/utils.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import fs from 'fs';
import path from 'path';
import { Buffer } from 'buffer';
import algosdk from '../src';
import { base64ToBytes } from '../src/utils/utils';

export async function compileProgram(
client: algosdk.Algodv2,
programSource: string
) {
const compileResponse = await client.compile(Buffer.from(programSource)).do();
const compiledBytes = new Uint8Array(
Buffer.from(compileResponse.result, 'base64')
);
const compileResponse = await client
.compile(new TextEncoder().encode(programSource))
.do();
const compiledBytes = base64ToBytes(compileResponse.result);
return compiledBytes;
}

Expand Down Expand Up @@ -70,7 +70,7 @@ export async function getLocalAccounts(): Promise<SandboxAccount[]> {

const addresses = await kmdClient.listKeys(handle);
// eslint-disable-next-line camelcase
const acctPromises: Promise<{ private_key: Buffer }>[] = [];
const acctPromises: Promise<{ private_key: Uint8Array }>[] = [];

// eslint-disable-next-line no-restricted-syntax
for (const addr of addresses.addresses) {
Expand Down
Loading