Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Sends Token. Save transaction and send notification
- * @param string $_POST['from'] the from ethereum address
- * @param string $_POST['to'] the to ethereum address
- * @param integer $_POST['amount'] the amount to be send
- * @return 'id_token' 'data' 'status' 'token_price' 'wallet_address' 'url'
- * @throws CJSON
- */
- public function actionSend()
- {
- $fromAccount = $_POST['from'];
- $toAccount = $_POST['to'];
- $amount = $_POST['amount'];
- $amountForContract = $amount * 100; //PERCHE' I DECIMALI DEL TOKEN SONO 2
- //Carico i parametri
- $settings=NGatePay::loadSettings();
- if ($settings === null || empty($settings->poa_url)){//} || empty($settings->poa_port)){
- echo CJSON::encode(array(
- "error"=>'Errore: I parametri di configurazione POA non sono stati trovati',
- 'id'=>time()
- ));
- exit;
- }
- //Carico i parametri del wallet
- $wallets=Wallets::model()->findByAttributes(array('wallet_address'=>$fromAccount));
- if ($wallets === null || empty($wallets->wallet_key)){//} || empty($wallets->poa_port)){
- echo CJSON::encode(array(
- "error"=>'Errore: I parametri per la connessione al wallet non sono stati trovati',
- 'id'=>time()
- ));
- exit;
- }
- //CREO la transazione
- /**
- * This is fairly straightforward as per the ABI spec
- * First you need the function selector for test(address,uint256) which is the first four bytes of the keccak-256 hash of that string, namely 0xba14d606.
- * Then you need the address as a 32-byte word: 0x000000000000000000000000c5622be5861b7200cbace14e28b98c4ab77bd9b4.
- * Finally you need amount (10000) as a 32-byte word: 0x0000000000000000000000000000000000000000000000000000000000002710
- */
- $data_tx = [
- 'selector' => '0xa9059cbb000000000000000000000000', //ERC20 0xa9059cbb function transfer(address,uint256)
- 'address' => self::Encode("address", $toAccount), // $receiving_address è l'indirizzo destinatario,
- 'amount' => self::Encode("uint", $amountForContract), //$amount l'ammontare della transazione (da moltiplicare per 10^2)
- ];
- $transaction = new Transaction([
- 'nonce' => '0x01'.time(),
- 'from' => $fromAccount, //indirizzo commerciante
- 'to' => $settings->poa_contractAddress, //indirizzo contratto
- 'gas' => '0x200b20',
- //'gasPrice' => '0x9184e72a000', // gasPrice giusto?
- 'value' => '0',
- 'data' => $data_tx['selector'] . $data_tx['address'] . $data_tx['amount'],
- ]);
- //$transaction->offsetSet('chainId', 6174); //IL NUMERO DELLA CHAIN PUO' VARIARE NEL TEMPO???
- // E' IL CASO DI IMPOSTARLO NEL DB QUANDO SI INSERISCE L'URL DELLA POA?
- $transaction->offsetSet('chainId', 1516); //1516 è QUELLA DEL MIO UFFICIO
- #echo '<pre>Transazione: '.print_r($transaction,true).'</pre>';
- $signed_transaction = $transaction->sign(Utility::decryptURL($wallets->wallet_key)); // la chiave privata del wallet
- #echo '<pre>Transazione firmata: '.print_r($signed_transaction,true).'</pre>';
- $web3 = new Web3($settings->poa_url); // indirizzo della poa
- $eth = $web3->eth;
- $eth->sendRawTransaction(sprintf('0x%s', $signed_transaction), function ($err, $tx) {
- if ($err !== null) {
- echo CJSON::encode(array(
- "error"=>'Errore sendRawTransaction: '.$err->getMessage(),
- 'id'=>time()
- ));
- exit;
- }
- //echo 'TX: ' . $tx;
- //exit;
- self::setTransaction($tx);
- });
- // elimino l'inserimento del balance, perchè non serve a nulla
- // utilizzo questo campo per salvare il numero di blocco in cui presumibilmente avviene la transazione
- $response = null;
- $eth->getBlockByNumber('latest',false, function ($err, $block) use (&$response){
- if ($err !== null) {
- throw new CHttpException(404,'Errore: '.$err->getMessage());
- }
- $response = $block;
- });
- //salva la transazione ERC20
- $timestamp = time();
- $invoice_timestamp = $timestamp;
- //calcolo expiration time
- $totalseconds = $settings->poa_expiration * 60; //poa_expiration è in minuti, * 60 lo trasforma in secondi
- $expiration_timestamp = $timestamp + $totalseconds; //DEFAULT = 15 MINUTES
- //$rate = $this->getFiatRate(); // al momento il token è peggato 1/1 sull'euro
- $rate = NGatePay::getFiatRate('token'); //
- $attributes = array(
- 'id_pos' => 0,
- 'id_merchant' => Merchants::model()->findByAttributes(array('id_user'=>$wallets->id_user))->id_merchant,
- 'status' => 'sending',
- 'type' => 'token',
- 'token_price' => - $amount,
- 'token_ricevuti' => 0,
- 'fiat_price' => $rate * $amount,
- 'currency' => 'EUR',
- 'item_desc' => 'wallet',
- 'item_code' => '',
- 'invoice_timestamp' => $invoice_timestamp,
- 'expiration_timestamp' => $expiration_timestamp,
- 'rate' => $rate,
- 'wallet_address' => $fromAccount,
- 'balance' => hexdec($response->number), // numero del blocco in base 10
- 'txhash' => self::getTransaction(),
- 'poa_url' => $settings->poa_url, // QUESTI PARAMETRI SONO DA RIVEDERE!! pROBABILMENTE NON SERVONO PIù
- 'poa_port' => $settings->poa_port, //
- 'id_bill' => 0
- );
- //salvo la transazione in db. Restituisce object
- $tokens = NGatePay::saveETHTransaction($attributes);
- //salva la notifica
- $notification = array(
- 'type_notification' => $tokens->type,
- 'id_merchant' => $tokens->id_merchant,
- 'id_tocheck' => $tokens->id_token,
- 'status' => $tokens->status,
- 'description' => ' '.ucfirst($tokens->type), //.' da '. $tokens->item_desc,
- 'url' => "index.php?r=tokens/view&id=".Utility::encryptURL($tokens->id_token),
- 'timestamp' => $timestamp,
- 'price' => - $rate * $amount,
- 'deleted' => 0,
- );
- NGatePay::save_notification($notification);
- //eseguo lo script che si occuperà in background di verificare lo stato dell'invoice appena creata...
- $cmd = Yii::app()->basePath.DIRECTORY_SEPARATOR.'yiic send --id='.Utility::encryptURL($tokens->id_token);
- NGatePay::execInBackground($cmd);
- //adesso posso uscire
- $send_json = array(
- 'id' => $invoice_timestamp, //NECESSARIO PER IL SALVATAGGIO IN indexedDB quando ritorna al Service Worker
- 'id_token' => Utility::encryptURL($tokens->id_token),
- 'data' => date('d/m/Y H:i:s', $invoice_timestamp),
- 'status' => Yii::app()->controller->walletStatus($tokens->status),
- //'token_price' => $tokens->token_price,
- 'token_price' => Yii::app()->controller->typePrice($tokens->token_price,$tokens->type),
- 'wallet_address' => substr($fromAccount,0,10).'...',
- 'url' => Yii::app()->createUrl("wallet/details")."&id=".Utility::encryptURL($tokens->id_token),
- );
- echo CJSON::encode($send_json);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement